How to send and receive data through ajax to php. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to send and receive data through ajax to php.

in the index.html the user types a name and clicks send. data goes to a PHP file containing an array of names, it searches the array for the entered name and returns true or false. Now I want to get the return back to the index.html and display in a div without reloading. showing some example code might help because I already tried a lot of examples at stack overflow and failed

27th Aug 2017, 1:13 PM
Mashan Shaluka1
Mashan Shaluka1 - avatar
5 Answers
+ 9
I made a demo, then i just chose a random service to upload the .zip file. Check it out and let me know if it works. Run the index in localhost, naturally. https://uploadfiles.io/27epv
27th Aug 2017, 2:00 PM
Maz
Maz - avatar
+ 8
You can change the value of the params variable as you want, i just chose a related name, i used the POST method for security reason and i also clean the user input. Once you change the value of the params variable you have to fix the $_POST array by adding the new value. E.g js: params = "age=" + this.value; php: $_POST[ "age" ]; js: params = "gender=" + this.value; php: $_POST[ "gender" ]; The $_POST array is always referred to our params variable because i opened a request for that Php file: req.open( "POST", file.php, true ); I guess you can save the values inside a $_SESSION array without any kind of problem, i didn't test it yet. Tips: Save the ajaxReq( ) function in a separated file and use it in your real projects to get a crossBrowser support for your ajax requests. ;)
28th Aug 2017, 11:09 AM
Maz
Maz - avatar
+ 2
@max I have a few questions 1. why does the params variable have "name=" in front of the value we are sending. is how I understand if name there in the variable responds to $_POST["name"] it is possible to send various values like ages,genders or address arrays using it. correct me if I'm wrong. plus I see we are using the method post to send data so if I'm supposed to feed data to the $_SESSION variable can I still use post?
28th Aug 2017, 6:55 AM
Mashan Shaluka1
Mashan Shaluka1 - avatar
+ 2
@maz thank you again ;-)
28th Aug 2017, 2:02 PM
Mashan Shaluka1
Mashan Shaluka1 - avatar
+ 1
@maz it works. thank you so much
28th Aug 2017, 5:41 AM
Mashan Shaluka1
Mashan Shaluka1 - avatar