I'm using Jquery's ajax method, and I need help parsing data coming back from backend server.
server response will be either "valid" or "not valid.
Currently my "if statement logic is not working, this is what I have tried so far).
$.ajax({
url: 'php/phone-valid.php',
type: 'POST',
data: {userid: $.trim($('#userid').val())},
success: function(data) {
console.log(data);
if (result.indexOf("not valid")) {
("#mustbevalid").val("You must validate your phone number");
console.log("Phone hasn't been validated");
e.preventDefault();
};
}
});
Your help is highly appreciated.
You're checking result.indexOf, but your response data is in data not result. Additionally, indexOf returns the position, which could be 0. So change to:
if(data.indexOf("not valid") > -1) {
Side note: this method of checking a result is error-prone and usually undesirable. It would be better for you to output a JSON object with a success property.
Example success response:
echo json_encode(array('success' => true));
// Outputs: {"success":true}
Example error response:
echo json_encode(array('success' => false));
// Outputs: {"success":false}
Now, you can parse the JSON:
$.ajax({
...
dataType : 'json', // <-- tell jQuery we're expecting JSON
success: function(data) {
if (data.success) {
// success
} else {
// error
};
}
});
indexOf will return the position in the string. So use this instead:
if(data.indexOf("not valid") == 0)
Related
I am trying to get customer details in a Laravel POS application. I am sending customer cell number via AJAX to serch and returning details from controller. When ever I am trying to apply JSON.parse on returned data from server I am getting:
Uncaught SyntaxError: Unexpected token s in JSON at position 0
I cant find errors in my code. I have searched product in exact same way from the server which works fine. Below is my code sample:
My Ajax Function
function customersearch(){
var token=$('input[name=_token]').val();
var baseUrl=document.getElementById("baseUrl").value;
var url=baseUrl+"/sales/searchcustomer";
var id=document.getElementById("customercell").value;
console.log(id);
$.ajax({
type: "GET",
headers: {'X-CSRF-TOKEN': token},
url:url,
data: {id:id},
datatype:'json',
success: function(data) {
var returndata =JSON.parse(data);
console.log(returndata);
var id=returndata[0].id;
if(id == "undefined") {
alert("No Customer found");
}
else {
document.getElementById("cname").value = returndata[0].fname;
document.getElementById("cid").value = returndata[0].id;
}
}
});
}
My Controller Function:
public function searchcustomer(Request $request){
$searchingkey = $request->input( 'id' );
//var_dump($searchingkey);
$customer = DB::table('customers')
->where('cellno', $searchingkey)
->get(['id','fname']);
var_dump($customer);
if (count($customer) == 0) {
$data = "No data returned"; // empty result
}
else {
$data = $customer;
}
return json_encode($data);
}
Response of var_dump($customer) in Network XHR
array(1) {
[0]=>
object(stdClass)#221 (2) {["id"]=>string(1) "1"
["fname"]=>string(5) "Ahnaf"}}
[{"id":"1","fname":"Ahnaf"}]
IF I dont apply JSON.parse on the returned data in ajax Function and just print the data variable like:
var returndata =data;
console.log(returndata);
this gives output in the consol like:
array(1) {
[0]=>
object(stdClass)#221 (2) {
["id"]=>string(1) "1"
["fname"]=>string(5) "Ahnaf"
}
}
[{"id":"1","fname":"Ahnaf"}]
The jquery docs for the ajax function say that the dataType parameter is spelled with a capital T.
You have this:
datatype:'json'
Try changing it to this:
dataType:'json'
and see if that helps.
You can try first() instead of get().
That should solve this.
You should use echo rather than return for ajax response
My Controller Function:
echo json_encode($data);
Also dataType must be
dataType: "json" // but remove this line because your already have JSON.parse(data);
I simply have:
<script>
$('#blah').on('click', function(){
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {"xxx":"yyy", "zzz":"nnn"}, // my variables...
success: function(response){
// response = "success,123" from server side
// so for accessing to the values "success" and "123" I just:
status = response.split(",")[0];
count = response.split(",")[1];
// now "status" and "count" are undefined in IE while it's working in all other browsers
}
});
});
</script>
As you can see in the above code, the server response to the Ajax is "success,123".
for accessing to values "success" and "123" I do:
status = response.split(",")[0];
count = response.split(",")[1];
Now status and count are undefined in IE while they are good in every other browsers.
What should I do to fix this?
Thanks
While I'm not sure why IE does this and I can't really test now, a smarter alternative would be to use JSON for response. If you use PHP, json_encode could be used to turn a simple array to JSON:
<?php
echo json_encode(array('status' => 'success', 'count' => 123));
And then:
// your response originally looks like this:
// { status: 'success', count: 123 }
// you can define $.ajax with { dataType : 'JSON' } instead of:
response = $.parseJSON(response);
console.log(response.status);
console.log(response.count);
If you're not using PHP just search for the way to do it on your language.
This will also save you the headache of handling responses which contain your separator inside later on (sentences with , in them, for example)
That's because you haven't defined the variables.Instead of:
status = response.split(",")[0];
I would try
var status = response.split(",")[0];
I have this ajax request to get the data from my server, and the dataType is always html by default. But sometimes it would return json from the server, so I want to check if the returned data is html then execute A else execute B. Is it possible?
My jquery,
$.ajax({
type: "GET",
dataType: "html",
url: request_url,
context: $('#meat'),
async: true,
beforeSend: function () {},
success: function (returndata, status, jqXHR) {
if ($.parseJSON(returndata) === false) A;
else B.
}
});
I get this error when the returned data is html,
SyntaxError: JSON.parse: unexpected character
So how can I make this code versatile?
I'm not sure if there is a better way, but you could try... catch
$.ajax({
type: "GET",
url: request_url,
context: $('#meat'),
async: true,
beforeSend: function() {
},
success: function (returndata, status, jqXHR) {
var parsed;
try
{
parsed = $.parseJSON(returndata);
// Execute B
}
catch(e)
{
// treat as html then
// do parsing here
parsed = returnData;
// Execute A
}
}
});
Essentially, your code is just plain wrong - your serverside API is violating all principles of predictability if the return type can vary in an inconsistent manner. Your code should never have to guess at the type of the returned data.
Having said that, a simple try/catch will help as a workaround for the erratic behaviour if you don't want to fix it. Ie.
try {
if ($.parseJSON(returndata) === false) A;
} catch(e) {
// Treat as HTML here.
}
It's not pretty, but that's what you get for having an unpredictable API that isn't pretty to begin with.
may be you need to handle it like this
try{
var response=jQuery.parseJSON('response from server');
if(typeof response =='object')
{
//control would reach this point if the data is returned as json
}
else
{
//control would reach this point if data is plain text
if(response ===false)
{
//the response was a string "false", parseJSON will convert it to boolean false
}
else
{
//the response was something else
}
}
}
catch(exp){
//controls reaches here, if the data is html
}
Since you need to check the html data as well, you may need to take care of this,
Might also need to use a try / catch for exceptions if it is possible that parseJSON is going to be dealing with something other than JSON values (i.e. HTML)
REF:How can I check if a value is a json object?
EDIT:Edited to make code more precise towards solution
Im using ajax .POST to run php script that suppose to return true/false. Im returning true/false using "echo" in my script. But after i get the result back to JS i compare the received text in an IF statement that never works! here is my code
$.ajax({ url: 'admin_checkuser.php',
data: {action: window.myId},
type: 'post',
success: function(output) {
if (output == "true"){
and here is the php script that being called
include_once('class.MySQL.php');
$userid = $_POST['action'];
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
}else{
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
I made sure that i receive true\false by doing "alert(output)" and it always displays true\false so i really dont understand why my IF statement fails even when alert(output) shows true
Thanks in advance!
Trying to parse the type of an ajax response tends to be super unreliable, in my experience.
For that reason, I (now) make darn sure that whenever I write a server side function that is meant for returning ajax data, I keep it perfectly in line with my own set response "standard", and then set my response type in the ajax method to JSON.
Doing so makes handling errors much more predictable.
An example of a standardized response would be:
$ajaxResponse = array(
'data' => $someData,
'result' => true,
'message' => 'your yadayada was succesful',
'timestamp' => time()
);
print json_encode($ajaxResponse);
and in ajax, your response would be like:
success: function( response ) {
if(response.result) {
alert(response.message);
}
}
Sorry if this isn't much help but you could try:
$.ajax({ url: 'admin_checkuser.php',
data: {action: window.myId},
type: 'post',
dataType: 'json',
success: function(output) {
if (output) { ... }
and
echo json_encode(true);
// echo json_encode($sharing);
The jQuery documentation gives more detail on what this call returns: http://api.jquery.com/jQuery.ajax/.
success(data, textStatus, jqXHR)Function, Array
A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter; a string describing the status;
and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery
1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
It looks like you are expecting the data that is returned from the AJAX call to be the string "true" in your test, so if that isn't passing it must be you are getting back something other than this exact string.
I recommend using the net tab of Firebug in Firefox to see the XHR request and to examine the response of what you are getting back to see if it is something other than what you expect.
Been getting a "parsererror" from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.
My project is in MVC3 and I'm using jQuery 1.5
I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.
Dropdown: (this loads the "Views" from the list in the Viewbag and firing the event works fine)
#{
var viewHtmls = new Dictionary<string, object>();
viewHtmls.Add("data-bind", "value: ViewID");
viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
#Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)
Javascript:
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'json',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
The above code successfully calls the MVC method and returns:
[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
{"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]
But jquery fires the error event for the $.ajax() method saying "parsererror".
I recently encountered this problem and stumbled upon this question.
I resolved it with a much easier way.
Method One
You can either remove the dataType: 'json' property from the object literal...
Method Two
Or you can do what #Sagiv was saying by returning your data as Json.
The reason why this parsererror message occurs is that when you simply return a string or another value, it is not really Json, so the parser fails when parsing it.
So if you remove the dataType: json property, it will not try to parse it as Json.
With the other method if you make sure to return your data as Json, the parser will know how to handle it properly.
See the answer by #david-east for the correct way to handle the issue
This answer is only relevant to a bug with jQuery 1.5 when using the file: protocol.
I had a similar problem recently when upgrading to jQuery 1.5. Despite getting a correct response the error handler fired. I resolved it by using the complete event and then checking the status value. e.g:
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
handleError();
}
else {
var data = xhr.responseText;
//...
}
}
You have specified the ajax call response dataType as:
'json'
where as the actual ajax response is not a valid JSON and as a result the JSON parser is throwing an error.
The best approach that I would recommend is to change the dataType to:
'text'
and within the success callback validate whether a valid JSON is being returned or not, and if JSON validation fails, alert it on the screen so that its obvious for what purpose the ajax call is actually failing. Have a look at this:
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'text',
data: {viewID: $("#view").val()},
success: function (data) {
try {
var output = JSON.parse(data);
alert(output);
} catch (e) {
alert("Output is not valid JSON: " + data);
}
}, error: function (request, error) {
alert("AJAX Call Error: " + error);
}
});
the problem is that your controller returning string or other object that can't be parsed.
the ajax call expected to get Json in return. try to return JsonResult in the controller like that:
public JsonResult YourAction()
{
...return Json(YourReturnObject);
}
hope it helps :)
There are lots of suggestions to remove
dataType: "json"
While I grant that this works it's ignoring the underlying issue. If you're confident the return string really is JSON then look for errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping
dataType: json
Your JSON data might be wrong. http://jsonformatter.curiousconcept.com/ to validate it.
Make sure that you remove any debug code or anything else that might be outputting unintended information. Somewhat obvious, but easy to forgot in the moment.
I don't know if this is still actual but problem was with Encoding. Changing to ANSI resolved the problem for me.
If you get this problem using HTTP GET in IE I solved this issue by setting the cache: false.
As I used the same url for both HTML and json requests it hit the cache instead of doing a json call.
$.ajax({
url: '/Test/Something/',
type: 'GET',
dataType: 'json',
cache: false,
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
you should remove the dataType: "json". Then see the magic... the reason of doing such thing is that you are converting json object to simple string.. so json parser is not able to parse that string due to not being a json object.
this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
incase of Get operation from web .net mvc/api, make sure you are allow get
return Json(data,JsonRequestBehavior.AllowGet);
If you don't want to remove/change dataType: json, you can override jQuery's strict parsing by defining a custom converter:
$.ajax({
// We're expecting a JSON response...
dataType: 'json',
// ...but we need to override jQuery's strict JSON parsing
converters: {
'text json': function(result) {
try {
// First try to use native browser parsing
if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
return JSON.parse(result);
} else {
// Fallback to jQuery's parser
return $.parseJSON(result);
}
} catch (e) {
// Whatever you want as your alternative behavior, goes here.
// In this example, we send a warning to the console and return
// an empty JS object.
console.log("Warning: Could not parse expected JSON response.");
return {};
}
}
},
...
Using this, you can customize the behavior when the response cannot be parsed as JSON (even if you get an empty response body!)
With this custom converter, .done()/success will be triggered as long as the request was otherwise successful (1xx or 2xx response code).
I was also getting "Request return with error:parsererror." in the javascript console.
In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.
String encodedString = getEncodedString(text, encoding);
view.setTextAreaContent(encodedString);
I have encountered such error but after modifying my response before sending it to the client it worked fine.
//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response); // Sending to client
//Client side
success: function(res, status) {
response = JSON.parse(res); // Getting as expected
//Do something
}
I had the same problem, turned out my web.config was not the same with my teammates.
So please check your web.config.
Hope this helps someone.
I ran into the same issue. What I found to solve my issue was to make sure to use double quotes instead of single quotes.
echo "{'error':'Sorry, your file is too large. (Keep it under 2MB)'}";
-to-
echo '{"error":"Sorry, your file is too large. (Keep it under 2MB)"}';
The problem
window.JSON.parse raises an error in $.parseJSON function.
<pre>
$.parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
</pre>
My solution
Overloading JQuery using requirejs tool.
<pre>
define(['jquery', 'jquery.overload'], function() {
//Loading jquery.overload
});
</pre>
jquery.overload.js file content
<pre>
define(['jquery'],function ($) {
$.parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
/** THIS RAISES Parsing ERROR
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
**/
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = $.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "#" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
$.error( "Invalid JSON: " + data );
}
return $;
});
</pre>