I'm new to backbone but I've written a basic model and when trying to fetch data for my model. I know the server is returning the data but fetch is calling the error callback.
That's fine but I don't know how I can find what error is being generated.
Here's the relevant code:
mUser = Backbone.Model.extend({
urlRoot: CURRENT_URL+'user',
defaults: {
name: '',
age: 22,
email: ''
},
initialize: function(){
}
});
user = new mUser({'id':1});
var x = user.fetch({
error: function(model, xhr, options){
alert('Error on fetch')
console.log(xhr.responseText);
},
success: function(model, response, options) {
alert(user.toJSON());
}
})
console.log('x email',x.email)
As I mentioned, the responseText does have the data I expect to see from the server, which is:
{'id':'1','name':'joe','age':'25','email':'joe#example.com'}
Maybe I should mention that I'm, doing this as part of a PhoneGap android app. I don't think it's significant to the problem I'm having but it does limit my debugging options.
You are probably getting a parsererror when jQuery tries to parse the JSON response from your server. To check if you're getting a parsererror, add a complete callback and check the textStatus parameter. e.g.
user.fetch({
complete: function(xhr, textStatus) {
console.log(textStatus);
}
});
Related
I am not a JSON specialist and therefore I need help to solve a little problem.
When submitting a form, before the form closes, it returns 'Unexpected end of input'.
I have searched the Internet and this forum, I found nothing solving the problem. I hope you'll be able to help me sort it out.
So, to make it easier for you, what's going on?
The user requests a listing. He fills the form with a message and a price. The item_id is transmitted directly (and working as I get it working so far).
The form data are sent via JSON to a remote server (VPS) which un-json the data. However, in addition to the 'unexpected end of input', I got on my remote server 'Server response: 400 (Bad Request)'
I am almost sure it is due to this code and not the remote server one.
I have identified thanks to debug that the error is at the line :
JSON.parse(data);
$('#requestListingSubmit').click(function (evt) {
evt.preventDefault();
rL_form.hide();
rL_load.show();
rL_controls.hide();
rL_alert.empty();
var item_id = $(this).data('item-id');
var route = '/request';
$.ajax(
{
type: 'POST',
url: coreURL + route,
data:
{
'item_id': item_id,
'message': $('#message').val(),
'price': $('#price').val(),
},
success: function (data)
{
try
{
JSON.parse(data);
window.location = coreURL+'/account/listings?new';
}
catch(e)
{
rL_load.hide();
rL_form.show();
rL_controls.show();
rL_alert.alert(
{
type: 'danger',
message: 'Error: '+e.message
});
}
},
error: function (jqXHR, status, httperror) {
rL_load.hide();
rL_form.show();
rL_controls.show();
rL_alert.alert({
type: 'danger',
message: (jqXHR.responseJSON.message || httperror)
});
}
});
});
Thank you very much guys!
I am currently developping a new website
When I am trying to create an account, I get an error like this :
Uncaught TypeError: Cannot read property 'hasError' of null.
And this is the code
function submitFunction()
{
$('#create_account_error').html('').hide();
//send the ajax request to the server
$.ajax({
type: 'POST',
url: baseUri,
async: true,
cache: false,
dataType : "json",
data: {
controller: 'authentication',
SubmitCreate: 1,
ajax: true,
email_create: $('#email_create').val(),
back: $('input[name=back]').val(),
token: token
},
success: function(jsonData)
{
if (jsonData.hasError())
{
var errors = '';
for(error in jsonData.errors)
//IE6 bug fix
if(error != 'indexOf')
errors += '<li>'+jsonData.errors[error]+'</li>';
$('#create_account_error').html('<ol>'+errors+'</ol>').show();
}
else
{
// adding a div to display a transition
$('#center_column').html('<div id="noSlide">'+$('#center_column').html()+'</div>');
$('#noSlide').fadeOut('slow', function(){
$('#noSlide').html(jsonData.page);
// update the state (when this file is called from AJAX you still need to update the state)
bindStateInputAndUpdate();
$(this).fadeIn('slow', function(){
document.location = '#account-creation';
});
});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert("TECHNICAL ERROR: unable to load form.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
}
});
}
It seems to be the jsonData, on the function, which is not working as well. Any idea or suggestions?
The success handler will be passed the data returned from the ajax request.
It will not have a function called hasError() because it is just a json object it will not have any functions.
The error handler should be fired if there is an http error i.e. if the ajax call returns an http 500.
I'm not familiar with prestashop, but looking over the prestashop documentation hasError is returned as a bool (not a function), so instead try (without the parenthesis).
if (jsonData.hasError)
You may also want to check if any data is returned first.
if (jsonData)
I'm using backbone to post a login form to my server. After it queries the database it will flip a boolean value allowing me to retrieve GET responses from the server. The problem is that it tries to fetch (i think) before my login is validated. Given this code:
App.Login.add(newContact);
var out = newContact.save();
App.Contacts.fetch();
How do i write a callback to have it first finish newContact.save() before fetching Contacts?
This is what I have so far, but it never succeeds:
login: function(event) {
App.Browser.navigate('contacts');
event.preventDefault();
var $form = this.$('.login form');
var newContact = new App.Models.Login({
userName: $('input.userName', $form).val(),
passWord: $('input.passWord', $form).val(),
});
App.Login.add(newContact);
newContact.save({userName:"Frank"},{
wait: true,
success: function(model, response){
console.log('success');
},
error: function(){
console.log('error');
}
});
Model.save() accept callback to handle success or failure . which the code like:
App.Login.add(newContact);
var out=newContact.save(attributes,{
wait: true,// wait for the sever response finish
success:function(model, response,options){
App.Contacts.fetch();
},
error:function(model, xhr, options){
app.error(model);//custom handle for error
}
});
Trying to make work the example of backbonetutorials. I am not able to throw a callback when the method fetch().
$(document).ready(function() {
var Timer = Backbone.Model.extend({
urlRoot : 'timeserver/',
defaults: {
name: '',
email: ''
}
});
var timer = new Timer({id:1});
timer.fetch({
success: function(data) {
alert('success')
},
fail: function(model, response) {
alert('fail');
},
sync: function(data) {
alert('sync')
}
});
});
The ajax request it has been threw. But does not work at all. Because any alert its dispatched.
sync and fail aren't valid callbacks. fetch uses the standard jQuery XHR object's options; there's success, error, and complete.
Here's a demo:
http://jsfiddle.net/ccamarat/sGJy4/
I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.