Calling PHP Scripts From Javascript Without Leaving Current Page
Solution 1:
AJAX is Asynchronous Javascript And XML, Its a Javascript technology that allows you to send a request to the server (as your browser does when you enter a URL) and have the response in a javascript string instead of rendering it in the page.
The problem is different browsers do not implement AJAX the same way, So I suggest using jQuery for abstraction.
do this with jQuery:
<script>
$.get("backend.php",{param:value},callbackFunction);
callbackFunction(data)
{
alert(data);
}
</script>
Solution 2:
Just happened to have the same issue, so I came up with something like that. All you have to do is add the code you need, and assign the do_the_script function to the onclick event.
<script type="text/javascript">
var myIntv;
function do_the_script() {
// play animation ...
var address='fancy_script.php';
var tmp = new XMLHttpRequest();
myIntv=setInterval(function(){
tmp.addEventListener("load", doneHandler, false);
tmp.open("POST", address);
tmp.send(null);
}, 1000);
}
function doneHandler(event) {
// maybe do something when script is executed
clearInterval(myIntv);
}
</script>
As you may have noticed, the code that "calls" the address is executed every 1 second. This, is to ensure that the call is made enough times so as to get a single positive answer, call the doneHandler and clear the interval afterwards. If you believe that your server can respond faster or slower you should change those milliseconds accordingly.
Solution 3:
you can use jquery ajax:
Solution 4:
PHP is a server-side language. JavaScript is a client-side language.
If you want to execute server-side code, you don't have the choice to do a round-trip to the server. If you don't want to leave the page, your only option is doing an asynchronous request (aka AJAX).
Using a JavaScript library such as jQuery or MooTools greatly simplifies that kind of task. For example, you could use MooTools to do a request at the end of your script as such:
var req = new Request({url: '/backend/doPHPInsert.php'});
req.send();
There are ways to do so without AJAX by, for example, creating an iFrame dynamically (or any other element that fetches a resource).
Solution 5:
I understand it is possible using AJAX, although is it possible using Javascript alone?
If you don't want to use XHR, you could use this ugly hack...
var request = 'mysql-insert.php',
image = new Image();
image.onload = function() {
// Success
}
image.onerror = function() {
// Error
}
image.src = request;
Except that was only really used before widespread use of AJAX (or needing to make a cross domain request).
I would just use AJAX. jQuery provides some great abstractions for working with XHR.
Post a Comment for "Calling PHP Scripts From Javascript Without Leaving Current Page"