I'm using Backbone.js and Parse for persistence. I'm trying to save a parse object when a Backbone event fires, but it's not working. Here's my code (edited to remove unnecessary stuff):
Parse.initialize("abc123", "omgwtf");
var ListsView = Parse.View.extend({
events: {
"submit form": "newList"
},
newList: function() {
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.set("score", 2222);
gameScore.set("playerName", "Mike Hunt");
gameScore.set("cheatMode", true);
gameScore.save(null, {
success: function(gameScore) {
alert("success");
},
error: function(gameScore, error) {
alert("error: " + error.message);
}
});
}
});
My error alert is showing, but the error message is an empty string. The Parse object saves just fine when my saving code is at the same top-level scope as the Parse.initialize method. I'm in the process of learning Javascript, so any background on why this code isn't working would be awesome.
Based on your code it's hard to pinpoint the mistake, but here are some ideas:
Look at the response from the request: In Chrome, View->Developer->Developer Tools, click on the Network tab, and try submitting your form. You should see a new request entry come up (probably in red, since yours fails). Click on it and check the response to see if you get a useful error.
Check your settings on the GameScore table in your Data Browser: Click on More->Permissions and ensure that you have Create set to Public.
Related
Trying to send form data to a PHP page, all parameters are sending successfully except data:imagesBase64
this imagesBase64 is an array which I am trying to send, a few hours ago everything was fine but now it is not working I really don't know why.
All values are Posting successfully only this value is not posting also I am not able to see error in console because it redirected to URL where I am posting the data
var imagesBase64 = ['abcdfd','dhydsu333ud','djhbsd'];
$(function () {
var frm = $("#saveform");
frm.submit(function (ev) {
$.ajax({
type: frm.attr("method"),
url: frm.attr("action"),
data: {
data: imagesBase64,
PubId: $("#Publications").val(),
sdate: $("#datepicker").val(),
pnumber: $("#pnumber").val()
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
alert("New message received");
},
});
ev.preventDefault();
});
});
In PHP page -
print_r($_POST['data']);
it gives an error undefined data, though when I tried with postman everything is working fine.
also I am not able to see error in console because it redirected to URL where I am posting the data
That's the problem.
You are submitting data to the server using a regular form submission and not with Ajax. Since your Ajax code isn't used, the data added in from outside the form isn't included.
This is usually caused by the regular form submission interrupting the Ajax request, but since you have ev.preventDefault(); that shouldn't be the case here.
Possible reasons that might apply are:
var frm = $("#saveform") fails to find the form because the selector is wrong or the form is added after the document is loaded with other JS
You don't have jQuery loaded so the call to $ fails
You have jQuery Slim loaded which doesn't include an ajax method (moving the call to preventDefault so it is before the call to ajax would help catch this).
Your browser's developer tools should have an called something like "Persist Logs" which will prevent it from clearing the console when you navigate to a new page. Turn it on to aid your debugging. Here's what it looks like in Firefox:
I can successfully create an indexeddb database and load data into it. I can also read data from this database from the same page. I then try and read from the database from another page on my site.
db = new ydn.db.Storage('test');
db.keys('items').done(function(d) {
alert(d);
});
This does not work. I just get an empty result. However if I enter the above code into the javascript console of Chrome directly it does work. After looking around it seems that the database may not be ready. So I try this.
db = new ydn.db.Storage('test');
db.addEventListener('ready', function() {
db.keys('items').done(function(d) {
alert(d);
});
});
This however gives me the the following error in the console.
Uncaught TypeError: undefined is not a function
The error is show for the following line of code.
db.addEventListener('ready', function() {
I am not sure what I am missing here.
Opening database connection is an asynchronous operation. This ready event listener is invoked when database is connected and after necessary schema changes are made. This is the first asynchronous function call make by the database instance.
If database opening fail, the callback is invoke with error event object. Multiple listener can be added. Heavy database write operation should invoke after this ready event handler. Alternatively ready event can be listen through DOM event listener pattern.
You can add database ready event listener in similar way:
var db = new ydn.db.Storage('test');
db.onReady(function(e) {
if (e) {
if (e.target.error) {
console.log('Error due to: ' + e.target.error.name + ' ' + e.target.error.message);
}
throw e;
}
db.put('statement1', large_data);
});
I have a form which submits data via AJAX to an external server.
The data which gets sent is then validated and if correct the user can then advance onto the next step of the form.
If the data is not valid, then the server returns an error which is outputted as a JSON object.
I can see the JSON object in FIDDLER.
My aim is to grab that JSON data and output it on the page and notify the user.
Ideally, i would do this as part of an error handler on the AJAX request(found below).
Is this achievable?
PS:
Unfortunately, I can't set up a demo because the link that the data is posted to is only available on my network.
It is also worth pointing out that the error that the back-end script outputs is actually stored in the link that the data is posted to.
AJAX REQUEST:
var setUpVrmData = function() {
$("#getvrmdata").click(function () {
var p_vrm = $('#p_vrm').val();
$.ajax({
dataType: "JSON",
type: "POST",
url: "http://217.35.33.226:8888/l4_site/public/api/v1/BC8F9D383321AACD64C4BD638897A/vdata",
data: {
vrm: p_vrm,
},
success: function(data) {
//Empty the dropdown box first.
$("#p_model").empty();
appendString = "<option value='none'>-- Select your model --</option>";
$.each(data['vehiclemodel'], function (k, v) {
// += concatenate the string
appendString += "<option value='" + k + "'>" + v + "</option>";
});
$("#p_model, #ent_mileage").show();
$('.js-find-my-car').hide();
$('.js-get-price').show();
$("#p_model").append(appendString);
$("#p_model").prop("disabled", false);
$('#skey').val(data['skey']);
},
error: function() {
console.log("We return error!");
}
});
});
The Error function will return an XHR object that you may be able to parse to get the message you want. I don't know what is serving the data so depending on how that's setup your mileage may vary. I've done this using PHP as well as C# and writing to Console, but in both cases I was able to control the returned data.
I used this article : http://encosia.com/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/ as a starting point.
You'll need to update:
error: function() {
console.log("We return error!");
}
to
error: function(xhr, status, error) {
console.log("We return error!");
}
Set a break point there in Firebug to check if an XHR object is passed, if not you'll need to find a way to get it.. You mention you can see the JSON in fiddler, it should be available to you. If it is, just use the eval posed in the article and you should be okay. If not you'll have to go and figure out how to get it, depending on your platform difficulty will vary.
A few things to note, eval is messy and can get you into trouble. In the cases I've done this, I removed the eval in production.
Also as of jQuery 1.8 success error and complete are deprecated. Use done fail and always if you plan on updating jQuery in the future.
jQuery API reference, for reference.
http://api.jquery.com/jquery.ajax/
Using the following as an example:
var Case = Backbone.Model.extend({
initialize: function(){
this.bind("error", function(model, error){
console.log(error)
});
},
url: function() {
return '/api/kase?id=' + this.get("id");
},
validate: function(attrs) {
return "An error";
}
});
In this case the validate method does not get called:
var kase = new Case();
kase.save();
In this case the validate method does not get called either:
var kase = new Case({subject: null});
kase.save();
In this case the validate method does get called, but the POST request is still made on save:
var kase = new Case();
kase.set("subject",null);
// An error
kase.save();
// POST http://localhost.local/api/kase?id=undefined 404 (Not Found)
Is this the expected behaviour? Am I missing something with regard to 'cancelling' the POST/PUT request when client side validation fails? Or should I be checking for a valid model before hitting the save method? (think the penny may have just dropped).
Any guidance would be most appreciated.
A set that fails won't update the model data while a call to save without parameters will post/put the current state of the model to the server (empty in your case). On the other hand, if you call your save method with the data to be validated, it will stop if the validation fails:
var kase = new Case();
kase.save({subject:null});
should log an error and stop before posting to the server.
Do you have code elsewhere that is calling save on the model?
Backbone does not call the server when setting a model's attributes; even if the validation fails.
Using a form in a dialog box I am using Dojo in jsp to save the form in my database. After that request is completed using dojo.xhrPost() I am sending in another request to update a dropdown box that should include the added form object that was just saved, but for some reason the request to update the dropdown is executed before saving the form in the database even though the form save is called first. Using Firebug I can see that the getLocations() request is completed before the sendForm() request. This is the code:
<button type="button" id="submitAddTeamButton" dojoType="dijit.form.Button">Add Team
<script type="dojo/method" event="onClick" args="evt">
sendForm("ajaxResult1", "addTeamForm");
dijit.byId("addTeamDialog").hide();
getLocations("locationsTeam");
</script>
function sendForm(target, form){
var targetNode = dojo.byId(target);
var xhrArgs = {
form: form,
url: "ajax",
handleAs: "text",
load: function(data) {
targetNode.innerHTML = data;
},
error: function(error) {
targetNode.innerHTML = "An unexpected error occurred: " + error;
}
}
//Call the asynchronous xhrGet
var deferred = dojo.xhrPost(xhrArgs);
}
function getLocations(id) {
var targetNode = dojo.byId(id);
var xhrArgs = {
url: "ajax",
handleAs: "text",
content: {
location: "yes"
},
load: function(data) {
targetNode.innerHTML = data;
},
error: function(error) {
targetNode.innerHTML = "An unexpected error occurred: " + error;
}
}
//Call the asynchronous xhrGet
var deferred = dojo.xhrGet(xhrArgs);
}
Why is this happening? Is there way to make the first request complete first before the second executes?
To reduce the possibilities of why this is happening I tried setting the cache property in xhrGet to false but the result is still the same.
Please help!
As Alex said, asynchronous requests are just that - their order is not guaranteed. If you want to guarantee their order, you can make them synchronous if you like. There is an option sync: true I think that you can send with the request args. This causes the browser to freeze up until the request gets back, so it's not recommended unless you have no other option, and the request is very quick.
You can also submit whatever data you need along with the data of the current request. For example, suppose dropdown A's value determines the list choices available in dropdown B. Rather than submitting a change when dropdown A is changed, then refreshing dropdown B's choices, what you can do is submit A's value at the time when dropdown B is opened, and process it in the server logic that determine's B's choices. (This assumes you have a drop-down widget with choices generated by the server, rather than a standard tag.)
The first A in Ajax stands for "asynchronous", which means things occur "at their own pace": most likely the requests are sent in the order you expect, but they complete the other way around simply because the second one is faster. Yes, of course you can wait to even start (send) the second request until the first one completes -- most simply, you can just put the starting of the second request in the callback function of the first.