I know people probably will get real confused why I am not using rails but I feel better using php thus I've picked it. I'm basically trying to create a really simplebackbone.js. I've predefined the urlRoot and url functions. I've coded php to just simply return me a message (using echo).
But no matter what I do, whenever I try receive the response it always falls to the error callback. I do get the responseText in response, however I still cannot understand why the error callback is triggered. Here is my full html and back-end php code. Why is it always going to the error callback? I would also like to state I receive header
HTTP/1.1 200 OK
HTML (also with Backbone.js inside);
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
</head>
<body>
<div id='place'>
<input id='clicker' type='button' value='Click Me'/>
</div>
<script type='text/javascript'>
(function($){
Backbone.emulateHTTP=true;
Backbone.emulateJSON=true;
var URL=Backbone.Model.extend({
initialize:function(){
console.log("URL object has been created");
},
defaults:{
url:'not actually defined'
},
urlRoot:'/StupidExample/server.php',
url:function(){
var base=this.urlRoot || (this.collection && this.collection.url) || "/";
if(this.isNew()) return base;
return base+"?id="+encodeURIComponent(this.id);
}
});
var URLView=Backbone.View.extend({
initialize:function(){
console.log('URL View has been created');
},
el:('#place'),
events:{
"click #clicker":"alerter"
},
alerter:function(){
console.log("I've been clicked");
var obj=new URL();
obj.save(obj.toJSON,{
success:function(){
console.log("Success")
},
error:function(model,response,xhr){
console.log(model);
console.log(response);
console.log(xhr);
console.log("Error");
}
});
}
});
var urlView=new URLView();
})(jQuery);
</script>
</body>
</html>
PHP;
<?php
echo "I've received something";
?>
You must return a valid JSON object with your HTTP 200 response. Backbone throws an error on your echo return value because it tries to parse the response as JSON, which fails.
As Derick said you need to return JSON, which you can do by changing your php file to:
<?php print json_encode(array( 'response' => 'success' ));
But you will also need to not use absolute paths as your URL because AJAX is not allowed across domains so it's required to be relative.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With