Tom Tom - 4 months ago 36
Javascript Question

Jquery Serialize form data returns error

I'm trying to use jquery to send form data to another PHP page.

This is the code I have :

var datastring = $("#form1").serialize();
$.ajax({
type: "POST",
url: "save.php",
data: datastring,
dataType: "json",
success: function(data) {
console.log(data)
},
error: function(data) {
alert('error handing here');
console.log(data)
}
});


When I run this I get an alert 'error handing here' and output logged to my console.

Save just contains:

<?php
ECHO "HELLO";
?>


The data logged on the console is :

Object {readyState: 4, responseText: "HELLO", status: 200, statusText: "OK"}


Can anyone advise why this isn't working.. and when it does how do I read the data submitted to save.php ?

Thanks

Answer

You don't response JSON in your script, it is plain text. So you should change your dataType to html or text:

dataType: "html",

Or change your php script to a json response:

echo json_encode(array("text" => "HELLO"));