I currently have a code snippet which I'd like to use to get Ajax Calls and return JSON data from my PHP file which I can use however I want in the jQuery side. My problem is that IF I change the data type to JSON, I always get error on the request, HOWEVER when I inspect it in Firebug I can see that the PHP file has just returned the JSON values fine!
This is the HTML:
<form id="formm" method="post">
<input type="text" name="test" value="" id="test"/>
<input type="submit" name="submit" value="Submit"/>
</form>
<div id="result"></div>
This is the JS:
$("#formm").submit(function(event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "functions.php",
type: "post",
dataType: "json",
data: values,
success: function(data) {
alert(data);
},
error:function(){
alert("failure");
$("#result").html('There is error while submit');
}
});
});
PHP file:
echo json_encode(array('returned_val' => $_POST['test']));
When I inspect with Firebug I get: returned_val "whatever I type in the textbox". Can anyone tell me what could be the problem?
UPDATE:
Response Headers:
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language ***
Content-Length 5
Content-Type application/json; charset=utf-8
Host localhost
Referer http://localhost/test/
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
X-Requested-With XMLHttpRequest
When I put the errors in the console, I get this:
The following error occured: parsererror SyntaxError: JSON.parse: unexpected character
JSON.stringify()instead of serializing it with jquery functionserialize()?