Reputation: 27
I have a question about ajax script.
Is it necessary to put datatype: 'json'
in every ajax script?
When to put datatype: 'json'
?
Im questioning this because i have an ajax script that is working only if i remove the datatype: 'json'
and also i got an ajax script that requires datatype: 'json'
to run correctly.
I'm kinda confuse about when to use datatype: 'json'
...I'm just a newbie.
example of my script that only run if i remove the datatype:
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
data: {
email : email, password : password
},
type: "POST",
url: 'Oppa/view/user.php',
success: function(data)
{
if (Number(data) == 1)
{
$(".show-page[data-page=progBar]").trigger("click");
$('#myModal').modal('hide');
}
else
{
$('div#show:empty').show();
$('#show').html(data);
}
}
});
return false;
Upvotes: 0
Views: 132
Reputation: 3827
According to the $(ajax) documentation:
The type of data that you're expecting back from the server.
Meaning, you'll have to figure out the type of data the server is sending you back. In your case, I assume this will be specified somewhere in your user.php file (look for $_POST['someValue']).
The reason one of your AJAX calls isn't working, is because most likely you're dealing with another type of data like text or html.
Upvotes: 0
Reputation: 4925
datatype:'json'
is used to specify to jQuery what you are expecting as a response. This should not be confused with the datatype you are sending. To specify the type of data you are sending, use the header content-type:"application/json"
.
The reason your ajax only works if you remove this can only be explained by the url returning something other than JSON. And when that happens, jQuery will try to parse non-JSON as JSON, which will cause an error.
Upvotes: 2