Parse cloud code is not logging/alerting on success or failure - javascript

I am a newbie in Parse.com cloud code. I am trying to query a table which has a particular column having a request parameter which I am supplying. The query is:
Parse.Cloud.define("newPostNotification", function(request, response) {
Parse.Cloud.useMasterKey();
var userId = request.params.userid;
console.log("User Id "+userId);
var query = new Parse.Query(Parse.ViewCount);
query.equalTo('userId', userId);
query.first({
success: function(object) {
/* var userString = request.params.username;
response.success(userString); */
alert("Success!");
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
});
I am utterly confused as why I cannot see the the alert messages for success or failure! Please rectify me where I am wrong!

You need to pass a JSON string.
For example: console.log({"Log message":"My message!"});

You can use console.log, console.error, or console.warn. Check the guide.
query.first({
success: function(object) {
console.log("Success!");
response.success();
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
response.error("Error " + error.code + " : " + error.message + " ;
}
});

Related

404 in JQuery Ajax POST call while sending XML to server

I am recently working with adobe InDesign extension's and in that I want to upload an xml file to my server using jquery ajax POST call, so for that, I have to read the XML file from the file system store it into a variable and then pass that variable as body into the post request here is my code
function uploadDocument( onSuccess, onError, onComplete) {
var token = localStorage.getItem("token");
writeLogs("uploadDocument function \n " + token );
var result = window.cep.fs.readFile("/Users/mac41589/Downloads/test-xmls/post.xml");
var xmlStr = "";
if(result.err == 0){
writeLogs("file read complete " + ' ' + result.data)
xmlStr = result.data;
alert("type of xmlStr new" + ' ' + typeof(xmlStr));
$.ajax({
url : "https://xyz.abc.com/capi-demo/article?customerNumber=888",
method: "POST",
data: xmlStr,
beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader("Content-Type", "application/xml");
},
complete: function(xhr) {
alert("on complete with code" + ' ' + xhr.status + ' ' + xhr.statusText );
//onComplete();
},
success : function(response) {
alert("file upload success with response : " + ' ' +response);
},
error : function(jqXHR, textStatus, errorThrown) {
alert('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
}
});
}
}
and here exact is the XML file I want to send :
<document xmlns="http://pubpress.com/document">
<properties>
<magazineNumber>95100</magazineNumber>
</properties>
<article>
<pam:message xmlns:pam="http://xax.org/namespaces/pam/2.0/" xmlns:ppc="http://axa.com/content" xml:base="/article/content/39992.xml">
<pam:article>
<head xmlns="http://www.w3.org/1999/xhtml">
<dc:identifier xmlns:dc="http://purl.org/dc/elements/1.1/">888-create.xml</dc:identifier>
<pam:status/>
</head>
<body xmlns="http://www.w3.org/1999/xhtml"><p>Sample body text</p></body>
</pam:article>
</pam:message>
</article>
</document>
so whenever I execute this POST call it returns 404 error Not Found but when I send the wrong(undesired to server) XML file then it shows 400 bad request.
the wrong xml (undesired to server) is as follows :
<?xml version="1.0" encoding="UTF-8"?>
<variable type="NameValuePair[]">
<item type="NameValuePair">
<name type="String"><![CDATA[No Data Found]]></name>
<value type="String"><![CDATA[95990070]]></value>
</item>
</variable>
i am not able to find why this POST call is returning 404 from ajax call where the same call with same parameters runs well in PostMan.
thank you in advance..
Any help on this will be highly appreciated.
Aside from making sure the url accepts xml posted, you should add the ajax option for contentType: "text/xml", to your configuration.
Here I get stuff out of the global scope with myApp (not part of question but to me it is better in practice to do so). I refactored to the promise form of .ajax() again because I like it better and I could then replace the functions there with some name spaced error handler for all my ajax for example.(is that what those passed things are, callbacks?)
I also saw a couple of bugs like typeof() in there. This assumes ES6.
// create a namespace object
var myApp = myApp || {
url: "https://xyz.abc.com/capi-demo/article?customerNumber=888"
};
// borrow some code from https://stackoverflow.com/a/23861977/125981
myApp.isXHR = function(maybe) {
if (!maybe) {
return false;
}
if (!('readyState' in maybe)) {
return false;
}
if (!('responseText' in maybe)) {
return false;
}
if (!('status' in maybe)) {
return false;
}
if (!('statusText' in maybe)) {
return false;
}
return true;
};
myApp.writeLogs = function(logmessage) {
// just to act as placeholder for the answer
};
myApp.processMessage = function(message, silent = true) {
if (silent) {
alert(message);
} else { // or
console.log(message);
// or something else like send to server via ajax to log or some such
}
};
myApp.getDocumentContent = function() {
let result = window.cep.fs.readFile("/Users/mac41589/Downloads/test-xmls/post.xml");
//var xmlStr = "";
let getResult = {
xmlStr: "",
hasContent: false,
error: result.err
};
if (result.err == 0) {
myApp.writeLogs("file read complete " + ' ' + result.data)
myApp.processMessage("type of xmlStr new" + ' ' + (typeof result.data));
getResult.xmlStr = result.data;
getResult.hasContent = true;
}
return getResult;
};
myApp.sendContent = function(contentObj) {
let token = localStorage.getItem("token");
myApp.writeLogs("uploadDocument function \n " + token);
myApp.writeLogs("file read complete " + contentObj.xmlStr);
myApp.processMessage("type of xmlStr new " + (typeof contentObj.xmlStr));
$.ajax({
url: myApp.url,
method: "POST",
data: contentObj.xmlStr,
contentType: "text/xml",
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader("Content-Type", "application/xml");
}
})
.always(function(dataOrJqXHR, textStatus, jqXHROrErrorThrown) {
// determine which parameter is which when the .always() is called
let my_jqXHR = null;
let data = null;
let errorThrown = null;
if (myApp.isXHR(dataOrJqXHR)) {
my_jqXHR = dataOrJqXHR;
errorThrown = jqXHROrErrorThrown;
}
if (myApp.isXHR(jqXHROrErrorThrown)) {
my_jqXHR = jqXHROrErrorThrown;
data = dataOrJqXHR;
}
let status = my_jqXHR.status;
// do something with status
myApp.processMessage("on complete with code" + ' ' + status + ' ' + errorThrown);
})
.done(function(data, textStatus, jqXHR) {
myApp.processMessage("file upload success with response : " + ' ' + textStatus + ' ' + data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
myApp.processMessage('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
})
.then(function(data, textStatus, jqXHR) {
myApp.processMessage("file upload success with response : " + ' ' + textStatus + ' ' + data);
}, function(jqXHR, textStatus, errorThrown) {
myApp.processMessage('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
});
};
myApp.uploadDocument = function(onSuccess, onError, onComplete) {
let contentObj = myApp.getDocumentContent();
if (contentObj.hasContent && contentObj.err == 0) {
myApp.sendContent(contentObj);
} else {
myApp.processMessage("No Content" + contentObj.err);
}
};
// call it, not sure what these passed thing are, and seem unused
myApp.uploadDocument(onSuccess, onError, onComplete);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to properly try and Catch in jQuery

I have the following function, that get a response from a web service. The response should be displayed on one section of the website.
That's working fine, but the thing is, in case of error, I've trying to get the error message and display it in the same way as the succesful response does, but I can't get that.
$(document).ready(function(){
$('.button').click(function(){
try {
var $resp = $.get("service url here", function(resp){
$('.response').append(resp.response.greeting + ", " + resp.response.Welcome);
});
}
catch (err){
$('.response').append(err.name + ", "+ err.message);
}
});
});
Try using .always()
$(document).ready(function(){
$(".button").click(function() {
$.get("service url here")
.always(function(resp, textStatus, jqxhr) {
$(".response")
.append(textStatus === "success"
? resp.response.greeting + ", " + resp.response.Welcome
: textStatus + ", "+ jqxhr
);
});
});

How to add dynamic a javascript variable in jquery?

I add variable length list in a view with jquery.
$("#addItemday").click(function() {
$.get("/Course/AddDayNewRow", function(data) {
$("#DayEditorRows").append(data);
}).fail(function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
});
});
for every partialview, set a index value.for example
<input name="Days.index" autocomplete="off" value="96633b1d-9c0c-4760-9ca8-474ac28bd52a" type="hidden">
I want to add a script for every partialview.
var objCal1 = new AMIB.persianCalendar("objCal1", "dateid");
After append PartialView, i want to get last item added.
$("input[id*='Date']").last(function () {
var ??? = new AMIB.persianCalendar(???, $(this).attr('id'));});
How do i get last item addes, and set name for this variable?
Two questions, two answer:
1) To get the id of the last item that you added:
var last_id = $("input").last().attr("id");
Remember that you have to wait for your AJAX call to return before firing that, so add it within your AJAX function.
2) Name the variable whatever you like.
Here's an example of the total code:
$("#addItemday").click(function() {
$.get("/Course/AddDayNewRow", function(data) {
$("#DayEditorRows").append(data);
var last_id = $("input").last().attr("id");
var amib_var = new AMIB.persianCalendar(last_id);
// DO SOMETHING WITH THE AMIB_VAR
}).fail(function(xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
});
});

Display loading image in get method with knockout bindings

Simple function to get and load data from server:
function getdata(stepNumber){
return $.get("./api/data_count.php", {stepNumber: stepNumber})
.fail(function (textStatus, errorThrown){
console.error("Error ! Unable to get step " + number + " count." + "Error: " + errorThrown + ", Status: " + textStatus);
});
}
Using .done differed method to assign data to knockout observable:
getdata(1).done(function(data){
self.dataCount($.parseJSON(data));
});
through following html:
<td><span data-bind = "text: dataCount"></span></td>
All is working well with the code except that it takes around 15 seconds for query to return this count and I am not sure how to display a loading image or message with in following span while the response is awaited.
<span data-bind = "text: dataCount"></span>
It should be just a matter of toggling an observable to show and hide the loader.
something like:
var Vm = function() {
var self = this;
self.showLoader = ko.observable(false);
self.showResults = ko.pureComputed(function() {
return !self.showLoader();
})
self.getdata = function(stepNumber) {
self.showLoader(true);
return $.get("./api/data_count.php", {
stepNumber: stepNumber
})
.done(function(data) {
self.dataCount($.parseJSON(data));
self.showLoader(false);
})
.fail(function(textStatus, errorThrown) {
console.error("Error ! Unable to get step " + number + " count." + "Error: " + errorThrown + ", Status: " + textStatus);
self.showLoader(false);
});
}
return self;
}
<table>
<tr>
<td><span data-bind="text: dataCount, visible: showResults"><img src='path/to/loader' data-bind="visible: showLoader" /></span>
</td>
</tr>
</table>

converting Parse.com object to string

What I have is when a user enters a name into a textbox and clicks a button, the value in the textbox is saved to the Parse database.
What iI'm trying to do is get the name that was added and add it to a div.
On this Live Example, it's basically what I want, except it alerts [object Object] and not thomas in this case.
You need to use the specific part of the result you need. In your case, replace
query.first({
success: function (results) {
alert("Successfully retrieved " + results + " ");
divTag.innerHTML = results.toString();
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
with
query.first({
success: function (results) {
alert("Successfully retrieved " + results.attributes.FirstName + " ");
divTag.innerHTML = results.attributes.FirstName.toString();
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
Use this:
alert("Successfully retrieved " + results.get("FirstName") + " ");

Categories

Resources