Cannot access data in JSON response - javascript

I am trying the access the json response from the server, using the following code. According to firebug, my server is outputting what looks like a valid json response as follows:
{"result":"error","message":"This group is not empty"}
my JavaScript is as below, but when I try to alert() the data from json response, I get nothing
$.ajax({
type: 'post',
url: data_ajax_url,
dataType: 'json',
data: 'data_mysql_record_id=' + data_mysql_record_id + '&data_mysql_table_name=' + data_mysql_table_name,
//success, annimate and remove row
success: function(data){
alert(data.result);
//get a json message from server if one exists
$ajax_response = data.message;
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Request has been completed';
}
//slide up table row
parent.slideUp(300, function(){
parent.remove();
});
//show noty notification 1 sec later
setTimeout(function(){
noty({
text: $ajax_response,
layout: 'bottomRight',
type: 'information',
timeout: 1300
});
}, 1000);
},
//error - alert
error: function(data){
alert(data.result); //my test
//get a json message from server if one exists
$ajax_response = data.message; //where 'message' is key in php jason output
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Error!- This request could not be completed';
}
//fire up a noty message
noty({
text: ''+$ajax_response,
layout: 'bottomRight',
type: 'warning',
timeout: 1300
});
}
UPDATE:
//data = jQuery.parseJSON(data);
console.log(data);
Console.log is giving me this
readyState
4
responseJSON
Object { result="error", message="This group is not empty"}
responseText
"{"result":"error","mess...is group is not empty"}"
status
400
statusText
"Bad Request"
and
data = jQuery.parseJSON(data);
console.log(data);
is giving this error
SyntaxError: JSON.parse: unexpected character
...nction(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i) {if("string"...
The status 400 and "bad request" is something I am oputiing in my php headers to show that there was an error backend

The error handler of an $.ajax request has the signature
Function( jqXHR jqXHR, String textStatus, String errorThrown )
[…] receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred.
Change your function to
error: function(jqXhr) {
var data = jqXhr.responseJSON; // you saw this in your console.log
if (data) {
…
} else {
// there might be other errors, where you don't get the server message
}
}

The problem is with parsing the JSON data in the javascript :
Before using the json data
data=jQuery.parseJSON(data);
alert(data.result);
Try this.

Use jQuery.parseJSON and might I suggest to use console.log instead of alert, like this:
$.ajax({
type: 'post',
url: data_ajax_url,
dataType: 'json',
data: 'data_mysql_record_id=' + data_mysql_record_id + '&data_mysql_table_name=' + data_mysql_table_name,
//success, annimate and remove row
success: function(data){
data = jQuery.parseJSON(data);
console.log(data.result);
//get a json message from server if one exists
$ajax_response = data.message;
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Request has been completed';
}
//slide up table row
parent.slideUp(300, function(){
parent.remove();
});
//show noty notification 1 sec later
setTimeout(function(){
noty({
text: $ajax_response,
layout: 'bottomRight',
type: 'information',
timeout: 1300
});
}, 1000);
},
//error - alert
error: function(data){
data = jQuery.parseJSON(data);
console.log(data); //my test
//get a json message from server if one exists
$ajax_response = data.message; //where 'message' is key in php jason output
if ($ajax_response == '' || $ajax_response == 'undefined') {
$ajax_response = 'Error!- This request could not be completed';
}
//fire up a noty message
noty({
text: ''+$ajax_response,
layout: 'bottomRight',
type: 'warning',
timeout: 1300
});
}

Related

how to get success or failure response from controller to ajax in laravel?

i want to show toaster on success or failer so i tried this code
$.ajax({
type: "GET",
dataType: "json",
url: '{{ route('users.update.visit_clear') }}',
data: {'visit_clear': visit_clear, 'user_id': userId , 'location': location , 'cs_location': cslocation },
success: function (data) {
if (data.message != ""){
toastr.success(data.message);
}
}
error: function (data) {
toastr.error(data.message1);
}
});
and in controller i have condition
if($var <= 1){
return response()->json(['message' => 'User status updated successfully.' ]);
}
else{
return response()->json(['message1' => 'Visit Failed Distance is too long' ]);
}
if i use error:function it doesnot response me
To be in the error ajax callback you have to return an http error code (ex: 500, 400 etc).
You can check the different http error codes here https://en.wikipedia.org/wiki/List_of_HTTP_status_codes.
You can add a status code as a second argument in your else response
ex: return response()->json(['message1' => 'Visit Failed Distance is too long' ],500);

Cannot read property 'id' of null if object Null using ajax

I am trying to retrieve data by using ajax and successfully the data appears, but there is my problem when data is not there I want to try to change its value, but it fails what is wrong with my script? and its error message is
Uncaught TypeError: Cannot read property 'id' of null //this error
$('[name="changeID"]').change(function () {
var url = base_url+'tools/get_id';
var idTools = $('[name="number_tools"]').val();
$.ajax({
url : url,
type: 'POST',
dataType: "JSON",
data: { id : idTools},
success: function(data) {
var result = data.id;
var getNewID = parseInt(result.substr(result.length -3)) + 1;
if (!data) {
$('[name="id"]').val("000"); //error here
}else{
$('[name="id"]').val(getNewID);
}
console.log(result);
},
error: function (request, jqXHR, textStatus, errorThrown) {
console.log(request.responseText);
}
});
});
Change your ajax response to below format,
if(!data)
{
$('[name="id"]').val("000");
}
else
{
var result = data.id;.
var getNewID = parseInt(result.substr(result.length -3)) + 1;
$('[name="id"]').val(getNewID);
}
You are use data object before checking null. If data is null then obviously you will get error of Uncaught TypeError: Cannot read property 'id' of null. You have to use data in if (!data) { } condition.

Ajax response status 200 but shows error message

I'm getting status as 200 but it's printing message present inside error message alert("error...");. Why so?
function makeSelect() {
var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value;
var url = "http://dukano.co/sakhidev/retailon/productoption/values";
alert(url);
var jsondata = $j('#customoption').serialize();
alert("jsondata: " + JSON.stringify(jsondata));
$j.ajax({
type : 'POST',
url : url,
data : jsondata,
dataType : 'json',
success : function(response) {
console.log("calling");
console.log(response);
alert("call success");
alert("response data:" + JSON.stringify(response));
if (response.status == 200) {
console.log("yes");
} else if (response.status == "error") {
console.log("no");
}
},
error : function(response) {
alert("error...");
alert("response:" + JSON.stringify(response));
console.log(response);
}
});
}
Magento's controller function returning json value
public function valuesAction(){
$blouseoption = $this->getRequest()->getParam('blouseoption');
$sareefinishing = $this->getRequest()->getParam('sareefinishing');
$data = array( 'sfinishing' => $sareefinishing, 'layout' => $this->getLayout());
Mage::dispatchEvent('product_custom_option', $data);
$jsonData = json_encode(array($blouseoption, $sareefinishing));
$this->getResponse()->clearHeaders()
->setHeader('Content-type','application/json',true);
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($jsonData));
$this->getResponse()->sendResponse();
}
As you are using
dataType: "json"
this evaluates the response as JSON and returns a JavaScript object.any malformed JSON is rejected and a parse error is thrown.
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function and set the textStatus parameter to "parsererror".
Make sure that the server returns valid JSON. empty response is also considered invalid JSON; you could return {} or null for example which validate as JSON.
try to check the textStatus in the error.
error : function(jqXHR,textStatus,errorThrown)
{console.log(textStatus)}
if this prints "parsererror" then of course you have problem with your returning json. please check that.
More Info
Alternative answer
Instead of returning status 200 with empty response, you can return status 204 and not return any response. Status 204 is for No Content. JQuery should not throw any error in this case.

AJAX showing error message

I have one form ,when i click submit button am saving those values and on button click am calling "SaveData() " method.
So when i try to add data and click on submit button and nothing is happening am getting following errors in my browser log.
My onclick function code
function requestReferral() {
var nameperson = $("#namefield").val();
var contact1 = $("#contact").val();
//Till this part working i mean alert is printing .
$.ajax({
url: '/mycontroller/myfunction',
data: 'name='+nameperson+'&contact='+contact1,
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}
});
}
my error is
Failed to load resource: the server responded with a status of 500 (Internal Server Error) with my controller url www.example.com/mycontroller/myfunction
First of all, check if your url is ok, for example, if you are using php with codeigniter your url need to be like this:
url: <?php echo base_url()?>mycontroller/myfunction
and second, when I used ajax, I send data like this
postData = {
name: nameperson,
contact: contact1
}
$.ajax({
url: '/mycontroller/myfunction',
data: postData
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}

ajax catch correct error code

i have this little code to post to my server
$.ajax({
type: 'POST',
url: 'post.php',
data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: '' },
success: function(data){
alert (data)
}
});
Wondering how i can "catch" the different errors for ajax request:
for eg, post.php return 'token error' when invalid token has been posted, or 'invalid title' for missing title.
Thanks in advance
If the server sends something else than 200 status code you could use the error handler:
$.ajax({
type: 'POST',
url: 'post.php',
data: {
token: '123456',
title: 'some title',
url: 'http://somedomain.com',
data: ''
},
success: function(data){
alert(data);
},
error: function() {
alert('some error occurred');
}
});
If your server performs some validation on the request arguments maybe it could return a JSON object containing the error information (and set the proper Content-Type: application/json):
{ error: 'some error message' }
In this case you could handle this in the success callback:
success: function(data) {
if (data.error != null && data.error != '') {
// TODO: the server returned an error message
alert(data.error);
} else {
// TODO: handle the success case as normally
}
}
// build the initial response object with no error specified
$response = array(
'error' => null
);
// the data checks went fine, process as normal
if (data is ok) {
$response['some_object'] = value;
// something is bad with the token
} else if (bad token) {
$response['error'] = 'token error';
// something is bad with the title
} else if (bad title) {
$response['error'] = 'bad title';
// some other error occured
} else {
$response['error'] = 'unspecified error';
}
// output, specifying that it's JSON data being returned
header('Content-Type: application/json');
echo json_encode($response);
and....
// $.ajax({ ...
success: function(data){
if (!data.error){
alert('OK!');
}else{
alert('Error: '+data.error);
}
}
// });
Something like that perhaps? (Unless you're talking legitimate AJAX errors, in which case supply the error: function(x,t,e){} ajax option or use .ajaxError)
What I like to do is set the dataType for the $.ajax() to 'json' and then in the PHP page you can just echo a json_encode()ed associative array. This will let you reference the values via your function parameter data (i.e. data.success, data.message). Let me know if you need some examples.
You probably want to set the 'error' handler function, which would treat the error you received.
Take a look at http://api.jquery.com/jQuery.ajax/ in the error setting.

Categories

Resources