javascript frameworks prototype to jquery - javascript

I have found the following script which is apparently written using the javascript framework prototype.
Event.observe(window, 'load', function() {
Event.observe( 'btnSubmit', 'click', purchaseCD);
connectToServer();
});
function connectToServer()
{
new Ajax.Updater(
{ success: 'CD Count', failure: 'errors' },
'server_side.php',
{
method: 'get',
onSuccess: function(transport)
{
if (parseInt(transport.responseText)) connectToServer();
}
});
}
function purchaseCD()
{
new Ajax.Updater(
{ success: 'CD Count', failure: 'errors' },
'server_side.php',
{
method: 'get',
parameters: { num: $('txtQty').getValue() }
});
}
Is anyone here able to convert this script to use jQuery instead of prototype? I don't know prorotype at all so I don't understand it.

Ajax.Updater takes, as parameter 1, two containers into which it will update the successful or failed response of a request to the URL given in parameter 2.
What this script does is that upon page load (I translated it below to DOMReady which is not exactly the same, but jQuery convention) an AJAX request is sent to server_side.php. If it gets a response that it understands, it immediately sends off another request, in order to keep the session alive.
This looks like a terrible design. If you're going to do something like that, you definitely want a timeout between the requests.
Another thing that's not very neat with this script is that every AJAX request is handled by the same page - server_side.php - relying on different parameters for instructions on what action to perform. It would appear cleaner to simply request different pages for different actions.
$(function() {
$('#btnSubmit').click(purchaseCD);
connectToServer();
});
function connectToServer() {
$.ajax({
url: "server_side.php",
success: function(res) {
$('#CD Count').html(res);
if(parseInt(res))
connectToServer();
},
error: function(xhr) {
$('#errors').html(xhr.responseText);
}
});
}
function purchaseCD() {
$.ajax({
url: "server_side.php",
success: function(res) {
$('#CD Count').html(res);
},
data: { num: $('#txtQty').val() },
error: function(xhr) {
$('#errors').html(xhr.responseText);
}
});
}

Related

How to successfully use the callback on an javascript function with an http request

Note: I have limited exp with js so correct me if my I'm completely wrong in how I'm describing this scenario.
I have two javascript files. I am calling a function on the first file (client side) which calls a function on the second file and uses the callback from the second file's function for the purposes of response.success/.error on the first file.
If that doesn't make sense here is some code:
Note: this is being done temporarily using Parse's cloud functions. Let me know if more information is needed regarding those but not sure if it's important.
First file:
Parse.Cloud.define("methodName", function(request, response) {
...
secondFile.myFunction(param1, {
stuff: request.params.stuff,
}, function (err, res) {
if (err) {
response.error(err);
} else {
response.success(res);// I'm assuming this is going to the hardcoded "yes." from httpRequest on second file's function
}
});
});
Second File:
myFunction: function(param1, properties, callback) {
if (!param1) return callback(new Error("Helpful error message"));
var headersForReq = {
...
};
var bodyForReq = ...; // the properties properly parsed
Parse.Cloud.httpRequest({
method: 'PUT',
url: ...,
headers: headersForReq,
body: bodyForReq,
success: function (httpResponse) {
callback(null, 'yes'); // the hardcoded "yes" i referred to
},
error: function (httpResponse) {
callback(httpResponse.status + httpResponse.error);
}
});
}
On my the client, the code is treated as a success (errors aren't thrown or returned back) but when I print out the value it comes across as (null) not "yes".
What's going on here? (Side note, httpRequest is currently not doing anything, its hard to verify if the request is properly being sent because it's being sent to a third party API).
I do know the second file's method is properly being called though. So it's not a silly issue with the module.exports or var secondFile = require('\path\secondFile')
I think you are just mis-use the api
Rewrite it with the example style.
https://parse.com/docs/js/api/classes/Parse.Cloud.html#methods_httpRequest
Parse.Cloud.httpRequest({
method: 'PUT',
url: ...,
headers: headersForReq,
body: bodyForReq
}).then(function (httpResponse) {
callback(null, 'yes'); // the hardcoded "yes" i referred to
},
function (httpResponse) {
callback(httpResponse.status + httpResponse.error);
}
});
I think below will work, too.
Parse.Cloud.httpRequest({
method: 'PUT',
url: ...,
headers: headersForReq,
body: bodyForReq
}, {
success: function (httpResponse) {
callback(null, 'yes'); // the hardcoded "yes" i referred to
},
error: function (httpResponse) {
callback(httpResponse.status + httpResponse.error);
}
});
BTW, if you are using open source parse-server, you can use request or request-promise. These 2 npm package is used by many people. (Parse.Promise is not es6-like promise)

Synchronous AJAX (broken promises)

I'm attempting to coax JavaScript into synchronous behaviour, but I've so far failed.
I've tried 30 or more different methods, and here is the latest attempt, based on another answer, here on StackOverflow:
function fnc () {
$.ajax({
type: 'GET',
url: "libraries/resources/data.json",
dataType: 'json',
success: function (data) {
...
objSomething = {
...
};
},
error: function () {}
});
}
fnc().then(function(objSomething) {
google.maps.event.addDomListener(window, 'load', function(){ initialize(objSomething); });
}).catch(function(objSomething) {
...
});
However, I'm getting an error:
TypeError: undefined is not an object (evaluating
'fnc().then')
Most of the methods I've tried have resulted in similar errors.
As for the Google Maps code, it does work (although not always, due to the asynchronous nature of the code execution).
It's worth noting that while I'm able to write complex code from scratch, when it comes to the underlying mechanics, I'm not that proficient.
I'm using jQuery 2.2.2, via the Google API CDN.
This is a solution you are looking for.
function fnc () {
var dfd = jQuery.Deferred();
$.ajax({
type: 'GET',
url: "libraries/resources/data.json",
dataType: 'json',
success: function (data) {
...
objSomething = {
...
};
dfd.resolve(objSomething);
},
error: function (error) { dfd.reject(error); }
});
return dfd.promise();
}
$.when(fnc()).then(function(objSomething) {
google.maps.event.addDomListener(window, 'load', function(){
initialize(objSomething);
});
}, function(error){
//Handle Error
});
use $.ajax function you can use the then function. Refer the following link:
http://wildermuth.com/2013/8/3/JavaScript_Promises

ajax request not sending any data ASP.NET MVC project with jQuery

I'm fairly new to asp.net MVC but am baffled as to why my request isn't working.
I'm trying to send an ajax request with jquery as per:
jQuery(function ($) {
var total = 0,
share = $('div.share'),
googlePlusUrl = "https://plusone.google.com/_/+1/fastbutton?url=http://bookboon.com" + $(location).attr('pathname');
setTimeout(function() {
$.ajax({
type: 'GET',
data: "smelly",
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});
}, 4000);
And set a line in my RouteConfig as:
routes.MapRoute(null, "services/{site}/proxy", new { controller = "Recommendations", action = "Proxy" });
The markup has a data-attribute value as:
<div class="share" data-proxy="#Url.Action("Proxy", "Recommendations")">
And my Proxy action method starts with:
public ActionResult Proxy(string junk)
The problem is that the junk parameter is always null. I can see in the debug output that the route seems to correctly redirect to this method when the page loads (as per jQuery's document ready function), but I cannot seem to send any data.
I tried sending simple data ("smelly") but I don't receive that neither.
Any suggestions appreciated!
The model binder will be looking for a parameter in the request called junk, however you're sending only a plain string. Try this:
$.ajax({
type: 'GET',
data: { junk: "smelly" }, // <- note the object here
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});

Promise deferred ajax api jQuery

I don't understand promises/deferred very much... I have something like that :
function callAjax() {
return $.ajax({
type: 'post',
dataType: 'jsonp',
data: {status: status, name: name},
url: '/test',
xhrFields: {
withCredentials: true
}
});
}
function connectAjax() {
var msg = 'doesnt work';
var promise = callAjax();
promise.then(function(data, textStatus, xhr) {
msg = 'it worked !';
}, function(data, textStatus, xhr) {
msg = 'it failed !';
});
console.log(msg); // output 'doesnt work'
}
I have tried a lot of different things (always, done, etc..) but couldn't make it work.
I use jsonp but my request isn't cross domain. I expect a 500 error from the server for my request.
For your example to work, you have to put the 'console.log(...)' statment INSIDE the two callback functions you register on the promise with .then(.., ..).
You have to keep in mind that the promise callback functions get called, only when the ajax call is finished.
Your script however does not wait until this happens and 'console.log(msg);' is executed before the ajax call returns.
This is a great example for the non-blocking nature of JavaScript.
For more detailed understanding look up resources on the JS event loop:
https://thomashunter.name/blog/the-javascript-event-loop-presentation/
Understanding the Event Loop

fetch() not calling its Success and Error callback functions (backbone.js)

I have a fetch() in the callback function of $.post(). The fetch() grabs the data from the backend and updates the collection just fine, however when its time to run either its success or error callbacks, nothing happens! I placed console.log()s in both its callbacks and they never appear in the Javascript console.
Any idea what happened?
A method in a View
create_set: function() {
var self = this;
// Post data to server
$.post('api/create_set', {
user_id: $('#user_id').val(),
post_id: this.post_id,
set_name: $('#new_set_name').val()
}, function() {
// Update list of Sets
self.setList.fetch({
data: {
user_id: $('#user_id').val(),
post_id: this.post_id
},
processData: true
}, {
success: function() {
// Highlight the first class in list
$(self.setListView.el).children('div:first').addClass('active');
console.log('success'); // DOESNT RUN!
}
}, {
error: function() {
console.log('error'); // DOESNT RUN!
}
});
console.log('hello'); // RUNS!
});
}
success and error should be the properties of options object that you pass to fetch, you don't have to create separate objects for them:
self.setList.fetch({
data: {...},
processData: true,
success: function(){...},
error: function(){...}
})

Categories

Resources