5

I'm having some trouble calling PHP scripts from Javascript without leaving the current HTML page (if it is at all possible). I understand it is possible using AJAX, although is it possible using Javascript alone?

Context:-

I want my page to perform a short animation using Javascript (using onclick), then immediately call a PHP script to insert data into a MySQL database - all without leaving the page so it does not inhibit the animation.

The animation part I can do and the inserting the data into the database, etc. but how can I call a PHP script at the end of that Javascript animation function?

Any pointers, code fragments, etc. would be greatly appreciated! ^_^

Apologies if this question has been asked previous.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Riyan
  • 187
  • 2
  • 5
  • 9

7 Answers7

9

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>
AbiusX
  • 2,379
  • 20
  • 26
3

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.

Slinky Sloth
  • 301
  • 2
  • 5
1

you can use jquery ajax:

http://api.jquery.com/jQuery.ajax/

Naftali
  • 144,921
  • 39
  • 244
  • 303
1

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).

Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
0

If you do not want to include the jquery library you can simple do the following

a) ad an iframe, size 0px so it is not visible, href is blank

b) execute this within your js code function

 window.frames['iframename'].location.replace('http://....your . php');

This will execute the php script and you can for example make a database update...

bodomalo
  • 153
  • 1
  • 1
  • 11
0

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.

alex
  • 479,566
  • 201
  • 878
  • 984
  • not appropriate here. This could be done with iframes as well. – AbiusX Mar 15 '11 at 01:22
  • @AbiusX It answers the question *can you make a request using JavaScript alone?* which I assume means without XHR. – alex Mar 15 '11 at 01:23
  • i'm not talking about the without XHR part, but about the image hack. Its used for CSRF not for a request. You can add a – AbiusX Mar 15 '11 at 01:27
  • @AbiusX I have no idea what you just said, sorry. – alex Mar 15 '11 at 01:28
  • Cross Site Request Forgery, For when you can only insert images in a forum or application but not script tags. The hack u mentions is used when you're inserting script inside another site, Not when you're developing your own. – AbiusX Mar 15 '11 at 01:32
  • @AbiusX What is stopping you from running this code on a site you have developed? I know the code is far from ideal, I only posted it for proof of concept. – alex Mar 15 '11 at 01:34
  • The fact that it looks like an exploit and certain security software will stop it! – AbiusX Mar 15 '11 at 01:53
  • 1
    @AbiusX: No security software will stop that... A `Image()` object pointing to a `.php` file can have legitimate uses (loading a dynamic image). – Andrew Moore Mar 15 '11 at 03:48
  • @Andrew yes it could but try Netcraft security toolbar. – AbiusX Mar 15 '11 at 13:56
  • @AbiusX: If you have "security software" that blocks this, your software is too trigger happy. That's not a good thing. – Andrew Moore Mar 15 '11 at 14:16
  • Andrew this is not correct. I'm also an active developer in many of the security software such as OWASP ESAPI and etc. – AbiusX Mar 15 '11 at 14:28
0

This has some good examples for using unadulterated XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

(Particularly, scroll down to the asynchronous examples - now you're cooking with gas.)

Edit: see also http://msdn.microsoft.com/en-us/library/ms535874%28v=vs.85%29.aspx which has examples for dealing with versions of IE which don't have native window.XMLHttpRequest.

Now, let's be frank - yes, working with XHR itself (especially cross-browser) is kind of obtuse. You can use just about anything out there (jQuery, Dojo, MooTools, Prototype, Closure, YUI, etc.) to do XHR more easily, because all of them, among other things, give you more concise XHR facilities.

It's still good to know what you're working with under the surface before you start letting a library do it for you though. :)

beaver
  • 523
  • 1
  • 9
  • 20
Ken Franqueiro
  • 10,559
  • 2
  • 23
  • 40