Click here to Skip to main content
15,911,315 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been having this trouble for several days and at my wits end now, I am frustrated! I tried making an ajax call to a script using jQuery's post method but it posts nothing and does not touch the script. I had $.post('server_script.php', $("form").serialize()); and after trying repeatedly, it neither touches/runs the script nor returns any errors. Any functions placed in the done method often run still the php script shows it was not touched.

What I have tried:

Now I switched to .ajax:

JavaScript
$('form').on("submit", function(){
				$.ajax({
				type: "POST",
				url: "test.php",
				data: $("form").serialize()
				});
	});

test.php
PHP
$name = $_POST["name"];
$email = $_POST["email"];
$rand = mt_rand();

echo $name . "\n" . $email . "\n" . $rand;
var_dump($_POST);

The above outputs the `rand` alone and my error log shows undefined index for the rest when I run the script on its own.
I also tried passing the data manually as an object {email: "vainglory7@gmail.com"}, didn't work. Tried parsing it as json, didn't work. Please someone help me as I am desperate. I have tried asking friends but no one seems forthcoming and I've been at this for days now
Posted
Updated 18-Apr-16 1:52am
v3
Comments
Mohibur Rashid 18-Apr-16 4:56am    
try print_r($_POST) and see whats happen
$("form").serialize()<- seems incorrect
Your form should have a name or id better try to give your form an id. Say "brandnewform"
now write that code
$("#brandnewform").serialize()

also try this:
if(isset($_POST["name"])==true){
$name=$_POST["name"];
}
else {
log("Name value is missing from POST"); // make a function to write everything in log file
exit;
}
nmeri17 18-Apr-16 6:45am    
I tried both var_dump and print_r but they all returned empty arrays. Your code did nothing too which means the variables are not picked from the ajax methods.
By the way, the form serializes. When I do

.done(function() {
console.log($("form-div form").serialize());
});

It logs a key/value pair string but the php code remains stagnant i.e. it does not grab the variables thrown by either .post or .ajax

1 solution

First, I always use $_REQUEST for retrieving values from a form. It works in place of both $_POST and $_GET.

Secondly, just for the sake of argument, try to build an ajax posting without the jQuery (I use 'raw' php/javaScript). Here's a link to what should give you a working example. Get that to work and then modify it to your needs (this should also point out where you went wrong).

AJAX Tutorial[^]


 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900