Question

When a $.post is made to a php page, or any other type of script, how is the php file executed on the server side?

For instance, if I have a php page that looks for a certain parameter to be passed in, and if that requirement is made, it calls echo to write something to the page. However, when I make that post, the actual php page is never loaded in my browser, so what exactly executes?

I feel like I'm asking something along the lines of..."If a tree falls and no one is around, does it still make a noise?" :)

Était-ce utile?

La solution

The server-side execution is no different in an AJAX call vs. any other call. For some clarification, take a look at the Network tab in a browser debugging tool (such as FireBug or Chrome tools). Watch the requests made to the server when the page loads, as well as when AJAX requests are made. They all share the same structure.

An HTTP request is sent to the server, which consists mainly of headers and perhaps content, and the server responds with an HTTP response, which consists mainly of headers and content. Requests also have verbs (GET, POST, etc.) and responses also have codes (200, 404, 500, etc.). These details are all the same regardless of whether it's an AJAX request or not.

For example, if you were to make an AJAX request to a "normal" PHP page, you'd see in the browser debugging tool that the response contains all the HTML for that page. The server saw no difference, it just responded to the request.

It's up to the client (the web browser) to know what to do with the response. For a "normal" page load the browser renders the HTML page. For an AJAX request the JavaScript would need to handle the response.

Autres conseils

As far as the server (and PHP) is concerned, a browser did load the page. It's only on client side that you don't see anything, but the "page" is still returned as the AJAX result.

To demonstrate:

If your $.post call looks like this:

$.post('test.php',
       { param1 : "value1" },
       function(data) {
         console.log(data)
       }
);

and your test.php script looked like this

<?php

echo $_POST["param1"]

?>

then console.log(data) will output "value1".

What your php script echos is available in the first parameter to the success handler of the $.post call. It does not get written to your html page directly.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top