Patrioticcow
Patrioticcow

Reputation: 27048

how to call a php function from javascript using ajax?

i know this question was probably asked 1 million times, but for the 1.000.001 time :)

i need to call a php function from JavaScript. And i am having a bit of an argument on if ajax will do it.

i don't want to send any data just a ajax call that will call and run that function.

here is what i have so far:

$.post('functions/test.php', function() {
    console.log("Hooray, it worked!");
});

is this gonna run the test.php ?

thanks

Upvotes: 0

Views: 1785

Answers (5)

KSchoniov
KSchoniov

Reputation: 416

I always use

jQuery.ajax("url.php");

Upvotes: 0

mathius1
mathius1

Reputation: 1391

In JQuery you can do:

$.post('functions/test.php', function(data) {
alert(data);
});

Whatever is returned in test.php will be put into the variable "data"

So you can do any php functions you need to in test.php and send the output back.

Upvotes: 1

Jasper
Jasper

Reputation: 76003

Yes the test.php script will run, and you can grab the output from the test.php script like this (if you want to):

$.post('functions/test.php', function(data) {
    //the `data` variable now stores the server response (whatever you output in `test.php`)
    console.log("Hooray, it worked!");
});

Upvotes: 1

PrimuS
PrimuS

Reputation: 2683

It definitely runs the test.php, to check it you may do sth. on succes

$.ajax({
    type: "POST",
    url: "ajax/test.php",
    success: function(data) {
        alert(data);
    }
});

But what's the purpose of sending if no data is send?

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Most likely, yes. I can't guarantee it because I don't do jQuery.

This, however, will definitely run it no problems (except versions of IE so old you shouldn't care about them):

var a = new XMLHttpRequest();
a.open("GET","functions/test.php");
a.onreadystatechange = function() {
    if( a.readyState == 4) {
        if( a.status == 200) {
            console.log("Hooray, it worked!");
            // optionally, do stuff with a.responseText here
            // a.responseText is the content the PHP file outputs, if any
        }
        else alert("HTTP error "+a.status+" "+a.statusText);
    }
}
a.send();

Upvotes: 1

Related Questions