0

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

1
  • 1
    is this gonna run the test.php Yes, if the path to the php script is correct. Commented Feb 9, 2012 at 0:45

5 Answers 5

2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Generally when no data is sent then the script called does something intuitive, like log a view of a specific document or something like that. I think it's probably the first step in getting used to communicating between jQuery and PHP.
1

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();

Comments

1

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!");
});

Comments

1

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.

Comments

0

I always use

jQuery.ajax("url.php");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.