Deleting Row by Object ID in Parse - javascript

I don't know what is wrong with my code. I am trying to delete a specific row by the object ID in Parse. Right now, it's giving me a "error" in the console. I am not sure how to fix it. Thanks!
var rowId = Parse.Object.extend("Assignment");
var queryRemove = new Parse.Query(rowId);
var obj = $(elem).parent();
queryRemove.get("$(elem).parent().attr('id')", {
success: function(obj) {
console.log(obj + " got it");
obj.destroy({
success: function() {
console.log("Deleted!");
},
error: function () {
console.log("Deleted fail!");
}
});
},
error: function(obj ,error) {
console.log("error");
}
});

From the console log it is obvious that queryRemove.get is failing as you see error handler processed.
According to Parse Api reference you should be passing a string id to query.get(), so I suppose you've mistaken in the parameter. JQuery should be evaluated and .get should receive id of an element not a string "$(elem).parent().attr('id')" which is obviously not a good id
queryRemove.get($(elem).parent().attr('id'), {
Also doesn't look like you can delete an item with .get()... Have analysed parse.com api before using it?

Related

jQuery ajax post Uncaught RangeError: Maximum call stack size exceeded

I have a problem with jQuery ajax.
I have javascript
<script type="text/javascript">
$(function() {
$('body').on("click", "#pager a", function(e) {
e.stopPropagation();
e.preventDefault();
var a = $(this);
var model = $('#searchForm').serialize();
$.ajax({
url: '/Product/Products',
type: 'POST',
data: {
model: model, page: a
},
success: function (data) {
alert('success');
$('#productsList').html(data);
}
});
});
});
</script>
This code produce error "Uncaught RangeError: Maximum call stack size exceeded" and I don't understand why. I have no trigger, I used preventDefault and stopPropagation, but I still have this error. Can anyone help me?
This error can also come if you are passing something in data which is not defined in that scope.
Another reason is passing in data with val() directly.
Instead of using var a = $(this) to get the page, use one hidden field and give page value to the field.
<input type="hidden" value="xyzpage" id="pageValue">
var pageVal = $("#pageValue").val();
data: {
model: model, page:pageVal
},
This will solve the issue I guess
I want to share my experience,
in my case, it was only a wrong parameter name and exactly the same error message :
instead of confID, I put the configID and got this error.
function openNameEditor() {
var confID = $("#configStatusList").attr("data-id");
debugger;
$.ajax({
url: '#Url.Action("GetModelNameToChange", "Admin")',
type: "GET",
dataType: "HTML",
data: { configID: configID},//Here, instead of confID, I put configID which doesn't exist in the function.
success: function (response) {
$("#name-editor").html(response);
},
error: function (er) {
alert(er.error);
}
});
}
You need to take off the var a = $(this);. I don't know what you try to achieve there but using a the jQuery wrapped clicked element as request data is a non-sense.
Endless loop can also cause this kind of error. View that you don't call same function inside function.
I ran into such a problem when parsing a large piece of JSON using jquery.tmpl.js. This error appears when handling large arrays with the concat() function. Here is a link to the problem: https://bugs.chromium.org/p/chromium/issues/detail?id=103583
The problem has not been solved since 2011. To solve it, I had to edit the jquery-3.3.1.js javascript library file. For those who want to repeat this decision, do the following: find the following line in the library file return concat.apply ([], ret); and replace it with the code below.
// Flatten any nested arrays
if ([].flat) return ret.flat();
var ret2 = [];
ret.forEach(function (i) {
if (i instanceof Array) {
i.forEach(function (i2) {
ret2.push(i2);
});
} else {
ret2.push(i);
}
});
return ret2;
// original code:
// return concat.apply([], ret);
// chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=103583
We check if there is a flat() function in the browser's arsenal, for example, it has a chrome browser, and if there is - simply merge the data arrays - nothing more is needed. If not, the browser will go a slower path, but at least there will be no error.

Backbone model not sending data on SAVE

This is the way I'm populating the attribute of my model:
this.model.set('questionAnswers', arrQuestions);
Now on submit, I check if model is valid:
if (this.model.isValid()) {
this.model.save(null, { success: this.gradingQuestionsSuccess, error: this.gradingQuestionsFailed });
}
Validations works like this:
validate: function (attr, options) {
var error = null;
if (attr.questionAnswers.length < this.cntQues) {
this.trigger('empty:answers');
error = 'Please answer all the questions.';
}
return error;
}
And service call is:
url: function () {
var url = Application.getConfig("url") + "/";
url += Application.getConfig("v2path3") + "/account/submitGradingQuestions";
}
return url;
}
The model is valid and the values are set in it on Submit, but it's not sending it in the Request Payload.
Can anyone please help me understand why this is happening? Thanks in advance!
Backbone does not observe the changed attributes and sync on save(null) automatically. What you need is pass attributes to Model.save method that makes set under the hood here or here depending on wait option's property. So you just need the following:
var data = {questionAnswers: arrQuestions};
this.model.save(data, {
success: this.gradingQuestionsSuccess,
error: this.gradingQuestionsFailed
});
You also don't need invoke validation manually because it's get invoked in save method also.

Retrieving a JSON.parse() string from a server

I will start by saying that I am learning how to program in jquery/javascript, and am running into an issue using JSON.parse(). I understand the format, and why people use it... but have not been able to get it to work in any of my code projects.
I have read in books/online on here in how to use it, but I think I read too much on it. I am now confused and second guessing what I know about it.
With that said, my jquery/javascript class I am taking is asking me to use it for an assignment, through AJAX using MAMP/localhost as the server.
The two codes below are for the section that I need to fill in the //TODO information. One is javascript (client-side), the other is php (server-side). I think that I've set the other //TODO information correctly, but I keep getting a token error for the JSON part.
I looked on here for a solution, but again, I think I've confused myself badly and need help. Appreciate any feedback, insight, or information.
-Javascript-
var calculateMpg = function () {
// These lines are commented out since the server will perform these checks
// if (!checkNumber("miles") || !checkNumber("gallons")) {
// return;
// }
var miles = $("#miles").val();
var gallons = $("#gallons").val();
console.log("ajax request issued.");
var result;
$.ajax({
url: "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons,
cache: false,
dataType: "text",
success: function(msg) {
console.log("ajax response received.");
// TODO: parse the JSON string returned from the server (see JSON.parse())
JSON.parse("result");
if (result.status === 'success') {
// TODO: get the mpg value returned from the server and display it to the user.
$("#mpg").val($_GET("result"));
console.log("JSON Working!");
}
else {
// TODO: get the name of the variable with the error. Hint: look at the 'fail' result from service.php
$_GET[fail(id)];
// TODO: report the error to the user using invalidNumber() function.
alert("{status: 'failure', variable: <variable name>}");
}
}
});
};
$(document).ready( function () {
$("#miles").blur(function () {
checkNumber("miles");
});
$("#gallons").blur(function() {
checkNumber("gallons");
});
$("#calculate").click(calculateMpg);
$("#miles").focus();
});
-PHP-
<?php
if ($_GET) {
if ($_GET['action'] == 'calculateMPG') {
$miles = htmlspecialchars($_GET['miles']);
$gallons = htmlspecialchars($_GET['gallons']);
// validate miles
if (strlen($miles) == 0) {
fail("miles");
}
$miles_chars = str_split($miles);
for ($i=0; $i< count($miles_chars); $i++) {
if ($miles_chars[$i] < "0" || $miles_chars[$i] > "9") {
//error_log("miles_chars check failed at: " + $i);
fail("miles");
}
}
// validate gallons
if (strlen($gallons) == 0) {
fail("gallons");
}
$gallons_chars = str_split($gallons);
for ($i=0; $i< count($gallons_chars); $i++) {
if ($gallons_chars[$i] < "0" || $gallons_chars[$i] > "9") {
fail("gallons");
}
}
// validate $miles and $gallons calling $fail along the way
$result = $miles/$gallons;
if ($result) {
success($result);
} else {
fail("mpg");
}
exit ;
}
}
function fail($variable) {
die(json_encode(array('status' => 'fail', 'variable' => $variable)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
Edited Additional 1
I have made changes to the JSON information in regard to 'var result' (thanks to several of the responses here). I'm starting to understand JSON a bit better.
Another question I have (now) is how to isolate a part of the JSON message from the whole being transmitted?
A piece of the 'JSON.parse(msg)' returned DOES include the answer to the equation miles/gallons, but I don't know how to... extract it from the JSON.
The solution to the equation miles/gallons appears in the 'msg' output.
Thanks.
Edited Additional 2
This question has been solved! While perusing around stackoverflow for a solution to the question in my previous edited section, I found my answer here: JSON response parsing in Javascript to get key/value pair.
The answer is this: under the //TODO section asking for the mpg value, I put the following code - $("#mpg").val(result.message); - which says that in the JSON section of the variable result, take the part of the JSON marked 'message', the value being the equation solution.
Thank you to all who responded with their solutions to my problem. I appreciate the fast responses, the great suggestions, and the information in understanding JSON.
-ECP03
JSON.parse() requires that you send it a valid JSON string.
"result" is not a valid JSON string. In your success function you have defined a parameter msg - what does this contain? Try console.log(msg) at the beginning of your success function and look at the console output.
You have two options:
Option 1: -- Parse the string returned.
Change JSON.parse("result"); to:
var result = JSON.parse( msg );
Option 2: -- Request JSON instead of plain text - no need to parse
Use $.getJSON() which is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Instead of parsing the JSON yourself, jQuery already provides you with a convenient function that will parse JSON:
var path = "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons;
$.getJSON(path, function (data) {
if (data.status == 'success') {
console.log('Success! Message:', data.message);
} else {
console.log('Failed :( Variable:', data.variable);
}
});
For your original code, what you would need to do is call JSON.parse(msg) in your success callback, which would return a JavaScript object with the values you sent from your PHP script. By specifying dataType: 'json' in the $.ajax call, jQuery does this for you. The $.getJSON method does this and some other things for you.
You need to use the result returned by the success function:
var result = JSON.parse(msg);
Then, you could do stuff like result.status.
When you put JSON.parse("result") you're saying "parse the string 'result'," which doesn't make any sense. However, if you say JSON.parse(msg) you're saying "Parse the variable that was returned from the ajax action," which makes sense.
JSON.parse() is used to convert your json data to object, then you can manipulate it easly.JSON.parse(msg); instead of JSON.parse("result").
For example:
var json = '{"value1": "img", "value2":"img2"}'
var obj = JSON.parse(json);
for ( k in obj ) {
console.log(obj[k])
}
This is totally wrong: JSON.parse("result");. .parse() expects a JSON string, e.g. the string that came back from you ajax request. You're not providing that string. you're providing the word result, which is NOT valid JSON.
JSON is essentially the right-hand side of an assignment expression.e.g.
var foo = 'bar';
^^^^^---this is json
var baz = 42;
^^---also json
var qux = ['a', 'b', 'c'];
^^^^^^^^^^^^^^^---even more json
var x = 1+2;
^^^---**NOT** json... it's an expression.
What you're doing is basically:
var x = parse;
^^^^^^---unknown/undefined variable: not JSON, it's an expression

Undefined parameter when returning data from jQuery.post to PHP

I am trying to return data from a database and populate a text field after the user enters an ID in the first text box. Currently I had the code working as long as the user did not enter a space in the ID number. Now I am attempting to allow that use case. My PHP code returns a json encoded array with three fields: first_name, last_name, and full_name.
When I use console.log(data) to view the data being returned I receive the following:
{"first_name":"Test","last_name":"Test","full_name":"Test Test"}
However in my code, I try to write data.full_name in a .val() nothing is populated, and when use the console.log I get an error saying "undefined".
Here is the whole jQuery Code:
$("#ID").blur(function () {
var params = {};
params.ID = encodeURIComponent($(this).val());
$.post("getter.php", params, function ( data ) {
if (!data) {
$("input[name=username]").val("User Not Found");
} else {
$("input[name=username]").val(data.full_name);
$("input[name=username]").attr("readonly", true);
}
});
});
Any help you can offer would be much appreciated.
Force jQuery to read the returned data as json:
$("#ID").blur(function () {
var params = {};
params.ID = encodeURIComponent($(this).val());
$.post("getter.php", params, function ( data ) {
if (!data) {
$("input[name=username]").val("User Not Found");
} else {
$("input[name=username]").val(data.full_name);
$("input[name=username]").attr("readonly", true);
}
}, "json"); // <- json forced
});
and then make sure your returned data is in proper json format (for example with json_encode in php)
Use trim() to remove spaces.
Then you can check if the parameter value is_numeric(), and if false, set a default value.

Return String From XHRGet

I'm creating a tree using Dojo and two seperate sets of data. One set of data makes up the main tree structure. The second set of data is dependent on a value from the first set. I'm using xhrGet and Dojo 1.7.3 to get the data.
Once the second set of data has been returned, I'm looking at the values of the JSON to determine a value of a variable, that's then passed into the tree. The variable displays a "!" if an "alert" value is present in the JSON returned and blank if there isn't.
var theAlert = dojo.xhrGet({
url: proxy + serviceurl + targetId,
handleAs: 'json',
load: function(data){
if(typeof data.alerts[0] != 'undefined'){
var hello = "!";
return hello;
}
else{
console.log("There is nothing there");
},
error: function(error){
console.log(error)
}
});
The problem I'm having is that when I write "theAlert" variable where I need to, it appears as "[object Object]" and not as "!".
I feel like I'm doing something wrong, but I can't figure out what.
I have already tried using theAlert.valueOf(); to no success. Help?
The data is received correctly as well, I can view it via console log.
dojo.xhrGet() returns a Deferred - http://dojotoolkit.org/reference-guide/1.9/dojo/Deferred.html
You need to do something like:
var deferred = dojo.xhrGet({
url: proxy + serviceurl + targetId,
handleAs: 'json'
});
deferred.then(
function(data){
if(typeof data.alerts[0] != 'undefined'){
processAlert("!");
} else{
console.log("There is nothing there");
}
},
function(error){
console.log(error)
}
);
function processAlert(a) {
alert(a);
}
Look at the docs.
You need to return data, not hello.

Categories