I want to execute some php code on submit button click without refreshing/reloading my page. Is it possible? also i have javascript function on page load that\'s why i don\'t wa
Whenever you send request ajax (with plain js anyway) from a html form, make sure you add the return false statement to prevent redirection: something like:
You have to use ajax, but you can do it in plain javascript (without jquery). Jquery makes it easier.
plain javascript example: This function will trigger an ajax, via get, without parameter: you can tweak it so it run in POST and be able to send some parameter: file represent the php file to request and html represent the container whre the data will be displayed:
function plain_ajax(file,html){
if (window.XMLHttpRequest){
r=new XMLHttpRequest(); //For Most BRowser
} else{
r=new ActiveXObject("Microsoft.XMLHTTP"); //for Explorer
}
//When the state change
r.onreadystatechange=function(){
//ReadyState 4 = Loaded see: http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/
//status 200 = ok see: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
if(r.readyState==4 && r.status==200){
//Replace the content with the response, Using creatDocumentFragment is more efficient
//at the cost of a few more lines But it would alos allow you to append the data
//instead of replacing it using innerHTML;
document.getElementById(html).innerHTML = r.responseText;
}
}
//Opening the connection and sending the request.
r.open("GET",file,true);
r.send();
}