When using jquery with php, is it possible to send data as HTML but receive data back as json? In my case i’m sending form data as HTML since json can only handle alphanumeric data. If the form contained error, an array of error messages is returned, which I’ll append to error message divs, if not, the user is redirected. Is it possible to do this? What datatype should I specify and should I return the array using json_encode
$("#sform").submit(function() {
$.ajax({
type: "POST",
data: $(#sform).serialize(),
cache: false,
//What data type to sepcify here? Data goes as HTML but returns as json
url: "user_verify.php",
success: function(data) {
//Print the php arrays data here to errormessage divs
}
});
return false;
});
To tell the server what type of data you’re expecting back, use the
dataTypeargument:If you don’t specify
dataTypethen$.ajaxwill try to guess the type based on the header sent back from the server.In your case, you can also add this to your php page:
and as you stated, return your data with
json_encode().If you don’t to
POSTdata, you can also check out thegetJSON()method: http://api.jquery.com/jQuery.getJSON/note: using
dataTypeAND setting thecontent-typetoapplication/jsonmay be redundant, but it can add clarity.