-
Ajax Loading
I have a div called content and I have links that load different files and replace the content.innerHTML once loaded so that keeps changing.
Now in share.php I have a form but if I try to post through it, it loads the actual page all over, not the content part.
I can't figure out how to use a form within the file that is being loaded into the content div.
Any ideas?
-
Re: Ajax Loading
Write a javascript function which will post the form through ajax but return false. Call this function on form submission. If you do not do so then it will refresh the page when form will be submitted.
Another way is to put form in iframe. In putting iframe page will not be refreshed
-
Re: Ajax Loading
Since you are working with a form, the easiest way to do this is with a hidden iframe as already stated. Here is a small example.
Code:
<iframe name="theframe" width="0" height="0" frameborder="0"></iframe>
<form target="theframe" ...>
Now, in your PHP file, to change the <div> content, you will use JavaScript. Have the PHP echo the following.
Code:
parent.document.getElementById('DIV ID HERE').innerHTML = ...
If you use AJAX, you will, as stated already also, have to return the form false. But you will also have to clear the form once the information is returned. This is the method I would use. The following example is somewhat customized, you will have to tweak some things for it to work for you.
Code:
<script type="text/javascript">
var AJAX = {
initialize: function(){
var xmlHTTP;
try{xmlHTTP = new XMLHttpRequest();}
catch(e){
try{xmlHTTP = new ActiveXObject("Msxml2.XMLHTTP");}
catch(e){
try{xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");}
catch(e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHTTP;
},
post: function(url, parameters, func){
var obj = this.initialize();
obj.open('POST', url, true);
obj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
obj.setRequestHeader('Content-length', parameters.length);
obj.setRequestHeader('Connection', 'close');
obj.send(parameters);
obj.onreadystatechange = function(){
if(obj.readyState==4){
func(obj.responseText);
}
}
}
}
function postTrap(ret){
document.getElementById('DIV ID HERE').innerHTML = ret;
document.FORMNAME.reset();
}
function ajaxForm(){
// you will have to retrieve the parameters for this yourself.
AJAX.post('share.php', 'param1=value1¶m2=value2', postTrap);
return false;
}
</script>
<form onsubmit="return ajaxForm()">