+ 5

Help me understand how PHP and AJAX work together.

it's too much to copy and paste, so if you would, please go here. https://www.digitalocean.com/community/tutorials/submitting-ajax-forms-with-jquery and look at step 4. Then step 1. On the PHP code on step 1, last line, echo json_encode($data); wouldn't that just print the data on the screen. Same as echo "hello world"? How is it passing the variable $data from PHP to the Ajax on step 4?

13th Jan 2022, 2:48 AM
Ginfio
Ginfio - avatar
4 Respuestas
+ 5
It's 2 different machines right. The PHP backend on your server in the US and the javascript in my browser, on my PC, in austria, doing ajax things. What happens in between is a plain old HTTP request, over the internet. Like, it's what your browser does when you visit example.org. Maybe what you see there was even caused by a php script that does `echo "<h1>Example Domain</h1>"`! So your browser sends a HTTP request to example.org, the server at example.org (maybe XAMPP or nginx) receives the request, runs that PHP script, and the output of the PHP script will be sent back as a text response, and your browser makes sense of the text and displays it as a nice looking website. An AJAX call does much the same. Of course with it you aren't grabbing a whole website but some json data, at the end of the day both are just text though. jquery will parse the text for you so you can easily use the data in javascript. Maybe helpful: Look at how HTTP works, or the OSI/ISO stack in general.
13th Jan 2022, 4:04 AM
Schindlabua
Schindlabua - avatar
+ 5
And there is nothing special about PHP either. You can probably configure the webserver, say nginx, to run C++ code, and everything that you `cout << ` from there will be sent as the HTTP response. Maybe I've hammered the point home enough but I remember having the same questions when I started, so I'll even say it again: It's two different programs, running at different points in time, on different machines, in different parts of the world. The output of one is just sent to the other. As text, via HTTP.
13th Jan 2022, 4:35 AM
Schindlabua
Schindlabua - avatar
+ 3
The answer of Schindlabua is perfect !!
13th Jan 2022, 5:17 PM
Elon
Elon - avatar
0
amr
21st Jan 2022, 8:50 PM
Amr khaled Saad
Amr khaled Saad - avatar