How to test my Parse CouldCode Function? - javascript

I just started to work with parse.com CloudCode. I am really new to Parse development and I managed to deploy their code trough the command line tool.
there is a main.js file that contain this function:
Parse.Cloud.define("hello", function(request, response) {
response.success("Hello world!");
});
now, I want to test and call this function, from the examples they told to run this function:
Parse.initialize('hQZZmu2UGiwr2QTHXrPSjG3ywAkFZccKQu12fD1S', 'IfaJZksyu21fKdITE0W8z9O2SWHpiLKlgUolfuRh');
Parse.Cloud.run('hello', {}, {
success: function(result) {
window.alert('success');
},
error: function(error) {
window.alert('error');
}
});
so, I am trying to call it from html file inside a
<script> //call to function here </script>
but nothing is happening.
I also try to add :
Parse.initialize('parse_id', 'js_key');
and still nothing.
can you please help?

I'm assuming those are your correct application id and javascript parse keys. You can check these in your parse application's settings.
Make sure you are including parse.js before you call that script.
<script src="//www.parsecdn.com/js/parse-1.4.2.min.js"></script>
Finally you can check your parse application's logs in the dashboard to check if the function even got called on the backend.
Take a look at these links to help get started:
https://parse.com/apps/quickstart#parse_data/web/existing
https://parse.com/docs/js/guide

Related

422 goes to console even with handler [duplicate]

I'm trying to load json files on page load. Those json are located inside a folder and constitute the basis on which the application is then built (each json file represents a page). The problem is that I want the script to be able to handle a random number of json file.
For now, I have the following recursive function which do exactly what I need, it loads each page and when an error occurs, it launches the application initialization. The problem is that my browser displays a 404 error, which is to be expected obviously. I want to know if there is a way to catch the 404 error (which indicates that no more json files are to be loaded) but prevent the error to be displayed in the browser's console?
$(document).ready(function() {
let pageArray = [];
loadPages(1, pageArray);
function loadPages(nb, array) {
$.ajax({
url: 'configuration/pages/page' + nb + '.json',
dataType: 'json',
error: function() {
initialize(array);
},
success: function(data) {
array.push(data);
loadPages(nb + 1, array);
}
});
}
function initialize(pages) {
console.log(pages);
}
});
EDIT
I ended up handling the configuration files with python (django on the server). So python is actually looping through the directory before sending the pages to the client. This doesn't answer the question but rather offers an alternative which is probably the best practice.
In order to prevent error from showing, you'll have to surround the piece of code which encounters the error in try/catch block... Something like this:
function() {
try {
openPage();
} catch (error) {
// do nothing
}
}
but I think this is not possible to do in your case, since those types of errors are logged by the browser...
look at: Hide 401 console.error in chrome dev tools getting 401 on fetch() call

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

Uncaught ReferenceError: set_metadata is not defined

I'm using the Yummly API (https://developer.yummly.com/documentation) and I am trying to parse a JSONP list of courses to use in a drop-down box. The format of the file I am requesting (located at http://api.yummly.com/v1/api/metadata/course?_app_id=[My App ID]&_app_key=[My App Key]) is:
set_metadata('course', [{"id":"course-Main Dishes","type":"course","description":"Main Dishes","searchValue":"course^course-Main Dishes"},....................}])
The request seems to work fine, and I can view the results in the Network tab in Chrome. However, in the console I get the error "Uncaught ReferenceError: set_metadata is not defined" I've done a lot of looking around, and have found people with similar but different errors, but I have not understood the cause or why the fixes for their errors work. I am fairly new to jQuery, so I'm guessing I'm doing something wrong with my request, which is:
var coursesURL = 'http://api.yummly.com/v1/api/metadata/course?_app_id=' + appID + '&_app_key=' + appKey;
var courses = [];
//Query for the list
$.getJSON(coursesURL + '?callback=?', null, function(data) {
console.log(data);
//Go through each result object found
$.each(data.course, function(i, course) {
courses.push(course.description);
});
console.log(courses);
});
Any help is greatly appreciated. I would also really appreciate an explanation of what I am missing, not just the fix. Thank you.
The reasons I'm adding this as an answer and not a comment are because i don't have enough reputation to comment and this is the only thing i can find on the yummly api returning jsonp.
I was able to get past the "uncaught referenceError" problem but now its only returning the word 'allergy', which is in the response, and I'm not getting the rest of the data.
here is my code:
$.ajax({
url:"//api.yummly.com/v1/api/metadata/allergy?_app_id=[APP_ID]&_app_key=[APP_KEY]?callback=",
dataType:"jsonp",
jsonpCallback:"set_metadata",
beforeSend:function(){
console.log("sending");
},
success: function (data){
console.log(data);
},
error: function(data){
console.log("send error and returned:");
console.log(data);
}
});
here is the response:
set_metadata('allergy', [
{"id":"392","shortDescription":"Wheat-Free","longDescription":"Wheat-Free","searchValue":"392^Wheat-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"393","shortDescription":"Gluten-Free","longDescription":"Gluten-Free","searchValue":"393^Gluten-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"394","shortDescription":"Peanut-Free","longDescription":"Peanut-Free","searchValue":"394^Peanut-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"395","shortDescription":"Tree Nut-Free","longDescription":"Tree Nut-Free","searchValue":"395^Tree Nut-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"396","shortDescription":"Dairy-Free","longDescription":"Dairy-Free","searchValue":"396^Dairy-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"397","shortDescription":"Egg-Free","longDescription":"Egg-Free","searchValue":"397^Egg-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"398","shortDescription":"Seafood-Free","longDescription":"Seafood-Free","searchValue":"398^Seafood-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"399","shortDescription":"Sesame-Free","longDescription":"Sesame-Free","searchValue":"399^Sesame-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"400","shortDescription":"Soy-Free","longDescription":"Soy-Free","searchValue":"400^Soy-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]},
{"id":"401","shortDescription":"Sulfite-Free","longDescription":"Sulfite-Free","searchValue":"401^Sulfite-Free","type":"allergy","localesAvailableIn":["en-US","en-GB"]}
]);
the line of code that says:
jsonpCallback:"set_metadata",
in the ajax call gets me past the reference error but im not getting the rest of the data that's in the response.
please help?
Finbar
I figured out the problem.
JSONP is returning not JSON text, but a function to the callback. Thus, I needed a function in my code called "set_metadata" that is used upon success of the json/ajax call.
Specifically, I defined function
function set_metadata(course, data) {
//Do stuff here
};
I tested it and that correctly captures the data I am trying to get.

Fire a .js file with jquery click event

I am attempting to load a .js file hosted online after a jquery click event. First, am I doing this right? Will all the javascript be applied only after a link is clicked?
$(document).ready(function() {
var clickHandler ="file.js";
$('a').click(function() {
$.getScript(clickHandler, function(data, textStatus, jqxhr) {
console.log(data);
console.log(textStatus);
console.log(jqxhr.status);
});
});
Edit: I just checked the console and it is loading the file but giving me a 403 Forbidden message. Why is this happening? Do I need to have some text in my header to refer to?
EDIT 1:
Misread the jQuery code -- this part of the answer doesn't apply:
There are ways to add Javascript file to an existing document, but it isn't as simple as you are trying to do.
This discussion can explain that: How to dynamically insert a <script> tag via jQuery after page load?
The other solution is to put the contents of the Javascript into its own function, include that on the page normally and then run that function in your click handler.
Edit: Expanded answer
Lets say that you have some fairly simple code in your file.js like this:
var el = document.getElementById("fooz");
if (el) {
el.className += " example";
}
This code will, since it is not wrapped up in a function, will run (or try to run) as soon as it is loaded. It will only run once every time it is loaded.
However, if you wrap it up in a function, like this:
function colorFooz() {
var el = document.getElementById("fooz");
if (el) {
el.className += " example";
}
}
Then the code will not run until the function is called. It will load and be ready to be called later.
Error 403
The first thing to do is figure out why are getting the error 403.
At this stage, that has nothing to do with Javascript, jQuery or AJAX. Simply the problem by trying to load that Javascript file directly in your browser, by typing something like this utnil your URL:
http://example.com/file.js
Changing the URL to your website and path of course. At this point, you should still be getting the 403 error, but you can now check your server logs to see what error is written there.
I found a page that gives a guide to tracking down 403 errors here: http://www.checkupdown.com/status/E403.html
((PS: If I had to randomly guess at the reason why you are getting the 403 error, I'd say that you don't have the path file file.js correct. Depending on your structure and various includes, it may be calculating the relative path incorrectly.))
The function you pass to click() is a callback and is only executed when the element is clicked. So yes, you've got that part right.

Load .txt file using JQuery or Ajax

How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php

Categories

Resources