backbone.js error handling with laravel issues - javascript

I have a model.save, it works fine.
this.model.save({
success: function (model, response) {
alert('hello');
},
error: function (model, xhr, options) {
alert('hello');
},
});
The controller is sending back 500, which i want it to right now for testing.
$response = [
'status' => 'error',
'message' => 'Cannot delete! Image is in use.'
];
return Response::json($response, 500);
console.log shows: POST /mysite/public/api/test 500 (Internal Server Error)
It is not alerting me 'hello', so for some reason my error callback function is not working. I can't find any problems with the syntax. Anyone else spot my problem? If so thank you!

The first argument of the save method is a set of attributes to save, and the second argument is the the options hash which should contain your callbacks. Modify your call to look like this:
this.model.save(null, {
success: function (model, response) {
console.log("success");
},
error: function (model, response) {
console.log("error");
}
});

Related

AJAX: only error callback is been fired

I have declared success and error callbacks, but in case of status code 200 also it calls error callback only.
I have been making curl call to some other php file too inside registry.php.
Here what i tried:
$.ajax({
type: "POST"
,data: {
action: "blah"
,mobileNo: that.mobNo
,token: that.key
}
,url: "http://90.8.41.232/localhost/registry.php"
,cache: false
,dataType: "json"
,success: function (response) {
console.log("success");
}
,error: function () {
console.log("error");
}
});
I have read in documentation that we don't have to call success callback explicitly, hope it's correct.
Any idea how to call success callback when it is 200 status code.
RESPONSE
hope this will help, this I copied from chrome console, not printed by console.log().
bort: (statusText)
always: ()
complete: ()
done: ()
error: ()
fail: ()
getAllResponseHeaders: ()
getResponseHeader: (key)
overrideMimeType: (type)
pipe: ()
progress: ()
promise: (obj)
readyState: 4
responseText: "{"success":"Mobile No 9535746622 is approved"} {"report":true}"
setRequestHeader: (name,value)
state: ()
status: 200
statusCode: (map)
statusText: "OK"
success: ()
then: ()
As you have mentioned that you are making a curl call to some other php, what happens is whenever you make curl call you have to return the response of the curl to the client. So to transfer the return value of curl call, you have to set an option curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);.
This will sort your problem. Hope so.
First, checkout the real error you get (not certain you really get a 200 status ?)
error: function (err) {
console.error("error");
console.log(err);
console.log(err.stack);
throw err;
}
Show us the resulting log please.
I did that a few weeks ago and for me it works if I call it like
$.ajax(
{
type: "POST",
data: { action: "blah", mobileNo: that.mobNo, token: that.key },
url: "http://90.8.41.232/localhost/registry.php",
cache: false,
dataType: json,
})
.success (function (data, status, jqxhr)
{
// do your stuff
})
.error (function(x, status, jqxhr)
{
// handle your errors
});

Ajax is undefined and throws runtime exception

ajax.postJson(
"/foo/GetFoo",
{ fooName: fooName },
function (data) {
},
function (error) { });
};
My Rest api call is GetAsync()
It throws ajax is undefined : JavaScript runtime error: Unable to get property 'exceptionStart' of undefined or null reference. The custom code to make ajax call is below. The api call Getfoo is GetAsync method using attribute HttpGet. Can someone point me to the cause of this failure
var ajax = {
defaultAjaxTimeout: 600000,
exceptionStart: '<!--',
exceptionEnd: '-->',
postJson: function (url, data, success, error) {
$.ajax(
{
type: "POST",
dateType: "json",
url: url,
data: data,
timeout: ajax.defaultAjaxTimeout,
success: function (result) {
if (success) success(result);
},
error: function (jqXhr, textStatus, errorThrown) {
if (error && jqXhr) {
var responseText = jqXhr.responseText;
var index = responseText.indexOf(ajax.exceptionStart);
if (index > 0) {
var exception = responseText.substr(index + ajax.exceptionStart.length + 1);
index = exception.lastIndexOf(ajax.exceptionEnd);
if (index > 0) {
exception = exception.substr(0, index);
}
error(exception);
} else {
error(errorThrown);
}
}
}
});
},
}
The issue you're having here is that you're attempting to access the variable ajax from a closure before it's created:
var myVariable = {
myProperty: "Hello",
myFunction: function () {
//... access myVariable.myProperty -> error
}
};
There are two options here. The cleaner one, and the one I'd use is this:
var ajaxOptions = {
defaultAjaxTimeout: 600000,
exceptionStart: '<!--',
exceptionEnd: '-->'
};
var ajax = {
postJson: function (url, data, success, error) {
... ajaxOptions.exceptionStart.length
}
};
The reason this works is because ajaxOptions exists already in the scope where you declare the function ajax.postJson so it's able to reference it correctly from its closure.
The variation on this option is this:
var ajax = {
defaultAjaxTimeout: 600000,
exceptionStart: '<!--',
exceptionEnd: '-->'
};
ajax.postJson = function (url, data, success, error) {
... ajax.exceptionStart.length
};
The reason this works is because ajax is already declared, and is just attached to the closure of the function.
A second, less-clean option is to put the ajax variable as a child of the window object:
window.ajax = {
defaultAjaxTimeout: 600000,
exceptionStart: '<!--',
exceptionEnd: '-->',
postJson: function (url, data, success, error) {
... window.ajax.exceptionStart.length
}
};
The reason this works is because window always exists in all lexical scopes, so it'll have no problem referencing it. The reason it's less clean is because it pollutes the window object and any JavaScript anywhere on your page can access and change it, potentially causing unknown behavior. I'm not recommending it, I'm just providing it as an example.
The following steps helped me resolve similar problem, I used IE11
the solution to it in IE 11 can be:
under internet settings select 'Compatibility View settings',
in 'Add this website' enter server name for your website (for example: localhost ), click 'Add' btn.
Tick 'Display intranet steps in Compatibility View' box.

Laravel with Jquery - Ajax Throwing 500 Error - Prob with Server Side

. Hello y'all. I am trying to gather a few variables and send it to my controller. I keep getting a 500 error and can't figure out where exactly I'm going wrong other than I'm pretty sure its server side. Any pointers about where I went wrong or better practices would be greatly appreciated! Thank yall so much!
Route:
/*Ajax Edit Price on Price Page*/
Route::post('edit_price', array(
'as' => 'edit_price',
'uses' => 'PriceController#edit_price'
));
Controller:
public function price_edit(){
console.log($id_and_db);
}
JS:
/*Ajax edit prices*/
$(document).ready(function(){
$('.edit_button').click(function(e){
e.preventDefault();
var id_and_db = $(this).prop('name').replace('edit', 'newprice'),
new_price = $('[name=' + id_and_db + ']').val();
$('#test').val(id_and_db);
$.ajax({
url: 'edit_price',
type: "POST",
data: {
"id_and_db": id_and_db,
"new_price": new_price,
},
success: function(data){
$("#edit_results").html(data);
$("#edit_results").addClass('panel callout radius');
console.log(data);
},
error: function(xhr, status, error){
console.log(xhr);
console.log(status);
console.log(error);
},
});
});
});
Error Message:
POST http://localhost/local/example/public/edit_price 500 (Internal Server Error) jquery.min.js:4
XHR finished loading: POST "http://localhost/local/example/public/edit_price". jquery.min.js:4
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
price_index_admin.js:40
error price_index_admin.js:41
Internal Server Error
You did
'uses' => 'PriceController#edit_price'
but your controller method is price_edit().
Try change your controller method to
public function edit_price() {
This is not valid for a controller - it looks like you are trying to run java inside php:
public function price_edit(){
console.log($id_and_db);
}
it should be something like this
public function price_edit(){
return Response::json(['your response here']);
}

How to capture the 500 error message using jquery?

How can i capture the 500 error message using jquery? I want to keep on checking for the 500 error message for sometime until it changes and time out after 50 sec.
I used the code below to try to capture and check the 500 error message but it doesnt seem to catch the 500 error message. I can see it in the firebug
$.ajax({
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
Dispite the accepted answer mentioned by #Danny, you can also do this in newer versions of jQuery.
var xhr = $.ajax({
url: "somewhere"
});
xhr.fail(function(xhr, textStatus, error) {
// Error handling stuff here ...
});
See Deferred Object.
Are you missing url in $.ajax like the one below
$.ajax({
url: "/path to page",
statusCode: {
500: function() {
alert(" 500 data still loading");
console.log('500 ');
}
}
});
You can check the status in error of ajax post please check the below code.
$.ajax({
.....
success: function (data) {
},
complete: function (XMLHttpRequest, textStatus) {
},
error: function (e, status) {
if (e.status == 404)
alert("404 error");
}
});
Thanks

Backbone.js fetch callback

I'm using Backbone.js and using fetch with options, but it doesn't seem to get the error or success callbacks, however data is being returned.
this.user.fetch({data: {username : this.username.val(), check : 'true'}}, {
error: function(model, response) {
console.log(response);
},
success: function(model, response) {
console.log(response);
}
});
This is what I have setup, am I missing something? It never hits error or success, but it does do the ajax request and it's returning data.
Thank you!
You're passing 2 separate arguments to fetch. Combine them into a single object with data, success, and error fields and it should work for you.
Example for x1a4 answer
var myModel = new MyModel({id: modelId});
myModel.fetch({
success: function (model) {
console.log('success: model fetched');
},
error: function () {
console.log('error: loading model');
}
});

Categories

Resources