Is it possible to make multiple calls using Jsonp with deferred objects? - ajax

I'm trying to make two or more requests all at once if that's even possible? I'm concerned about speed since after the first request is made I want to display that info onto a web page and then do the same for each additional url.
I've been reading about deferred objects and trying some examples, and so far I've tried to do this,
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script >
$(document).ready(function($) {
// - 1st link in chain - var url = 'https://www.sciencebase.gov/
catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp';
// - 2nd link in chain - var url = 'https://www.sciencebase.gov/
catalog/itemLink/504216b6e4b04b508bfd333b?format=jsonp&max=10';
// - 3rd (and last) link in chain - var url = 'https://www.sciencebase.gov/
catalog/item/4f4e4b19e4b07f02db6a7f04?format=jsonp';
// parentId url
function parentId() {
//var url = 'https://www.sciencebase.gov/catalog/items?parentId=
504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp';
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=
504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {},
error: function(e) {
console.log(e.message);
}
});
}
// itemLink url
function itemLink() {
//var url = 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp&max=10';
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink
/504216b6e4b04b508bfd333b?format=jsonp&max=10',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {},
error: function(e) {
console.log(e.message);
}
});
}
// Multiple Ajax Requests
$.when( parentId(), itemLink()).done(function(parentId_data, itemLink_data) {
console.log("parentId_data.items[0].title");
});
});
But it doesn't seem like the functions are functioning. I was expecting to be able to put some stuff after the .when() method inside the function to tell my program what to do, but I'm not getting anything displayed??
Thanks for the help!

Part of the problem is that in the done handler for $.when, the arguments that are passed to the callback are the array of arguments for each request, not simply the data that you want to use. You can get around this by using .pipe as in the example below.
Also, don't specify jsonpCallback unless you have a very good reason, most of the time you want to let jQuery manage that internally for you.
Here's a working example tested on JSFiddle
jQuery(function($) {
function parentId() {
return $.ajax({
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=3&offset=0&format=jsonp',
dataType: 'jsonp',
error: function(e) {
console.log(e.message);
}
// We'll use pipe here so that rather than the value being passed to our $.when handler
// is simply our data rather than an array in the form of [ data, statusText, jqXHR ]
}).pipe(function( data, statusText, jqXHR ) {
return data;
});
}
function itemLink() {
return $.ajax({
url: 'https://www.sciencebase.gov/catalog/itemLink/504216b6e4b04b508bfd333b?format=jsonp&max=10',
dataType: 'jsonp',
error: function(e) {
console.log(e.message);
}
}).pipe(function(data) {
return data;
});
}
// Multiple Ajax Requests
$.when( parentId(), itemLink()).done(function(parentId_data, itemLink_data) {
console.log( parentId_data, itemLink_data );
});
});

Related

call server-side REST function from client-side

In the case, on the server side have some archive restApi.js with REST functions. My REST functions works fine, i test with Prompt Command.
In my client side have some archive index.ejs, And I want to call with this file.
My restApi.js: Server-side
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxxxxxxx","platform":"xxxx" },
headers: { "Content-Type": "application/json" }
};
var numberOrigin = 350;
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(sessionid, numberOrigin); // execute fine
}
});
function openRequest(sessionid, numberOrigin){
numberOrigin+=1;
var dataRequest = {
data: {"sessionID":sessionid,"synchronize":false,"sourceRequest":{"numberOrigin":numberOrigin,"type":"R","description":"Test - DHC","userID":"xxxxxxxxxx","contact":{"name":"Sayuri Mizuguchi","phoneNumber":"xxxxxxxxxx","email":"xxxxxxxxxxxxxxxxxx","department":"IT Bimodal"},"contractID":"1","service":{"code":"504","name":"Deve","category":{"name":"Developers"}}} },
headers: { "Content-Type": "application/json" }
};
client.post("xxxxxxxxxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
console.log(data);
});
}
My index.ejs: Client side
<html>
<head> ------------- some codes
</head>
<meta ------- />
<body>
<script>
function send() {
$.ajax({
type: "POST",
url: "restApi.js",
data: '{ sendData: "ok" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
</script>
<script src="restApi.js"></script>
</body>
</html>
I've try see others examples but does not work (Ajax).
And I need to know how to solved this, if have other Best practice for it, please let me knows.
In my console (Chrome) show if I call the ajax function:
SyntaxError: Unexpected token s in JSON at position 2 at JSON.parse (<anonymous>) at parse (C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\types\json.js:88:17) at C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\read.js:116:18
And if I click (BAD Request) show:
Obs.: Same error than app.js, but app.js works fine.
Cannot GET /restApi.js
In the case the file restApi.js Is a folder behind the index.
Folder:
Obs.: public folder have the index.ejs
Your problem is bad url. In case if you have fiule structure like this you have to point as shown in image
Based on the error I think the data you are posting via AJAX is not in correct syntax.
Change function send() as following.
function send() {
var obj = { "sendData" : "ok" };
$.ajax({
type: "POST",
url: "restApi.js",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
This should resolve the error you are facing.
Try this now...
function send() {
var obj = {
sendData : "ok"
};
$.ajax({
type: "POST",
url: "Your url",
data: obj,
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
},
error: function (error) {
console.log("error is", error); // let us know what error you wil get.
},
});
}
Your url is not pointing to js/restapi js.
and what code do you have in js/restapi js?
if your action page is app js you have to put it in url.
url:'js/restapi.js',

Bypass Ajax request within javascript promise in Unit Testing

I have a function called getStudentData(),returns resolved data.
Inside getStudentData(), I have an Ajax request.
I want to Bypass Ajax request in my unit test case using Mocha , so that when i make a call to getStudentData(), the data should be returned.
Please find the code below:
getStudentData: function() {
return studentData || (studentData = new Promise(function(resolve, reject) {
var request = {
//request data goes here
};
var url = "/student";
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
dataType: "json",
contentType: "application/json",
success: function(response, status, transport) {
//success data goes here
},
error: function(status, textStatus, errorThrown) {
reject(status);
}
});
}).then(function(data) {
return data;
})['catch'](function(error) {
throw error;
}));
}
Please let me know how to Bypass Ajax request By stubbing data using sinon.js .so that when i make a call to getStudentData() , data should be returned.
First of all doing:
then(function(data){ return data; })
Is a no-op. So is:
catch(function(err){ throw err; });
Now, your code uses the explicit construction anti-pattern which is also a shame, it can be minimized to:
getStudentData: function() {
var request = {
//request data goes here
};
var url = "/student";
return studentData ||
(studentData = Promise.resolve($.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
dataType: "json",
contentType: "application/json" })));
}
Now, that we're over that, let's talk about how you'd stub it. I'd do:
myObject.getStudentData = function() {
return Promise.resolve({}); // resolve with whatever data you want to test
};
Which would let you write tests that look like:
it("does something with data", function() { // note - no `done`
// note the `return` for promises:
return myObj.getStudentData().then(function(data){
// data available here, no ajax request made
});
});
Although in practice you'll test other objects that call that method and not the method itself.

Keep loading AJAX request

I have an AJAX request which gets data from the database and then populates the page with the data collected. The problem I am having is that currently the ajax request is in a setInterval which is being called every second.
setInterval(function () {
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
}
});
}, 1000);
This is fetching the data every second which is a huge strain on the server as it's making a request and then I am calling it again even when the data hasn't come through first time.
Is there a way that I can call the same AJAX request over and over but only after it's finished fetching the data first time and not keep going up?
There are better architectures to accomplish this type of scenario (websockets as mentioned in the comments would be one example), but to do strictly what you're asking, sure! Wrap it in a function that calls itself:
function getData(){
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
getData();
}
});
}
Replace the setInterval with a setTimeout only once you're done:
function fetchAjax() {
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
setTimeout(fetchAjax, 1000);
}
});
};
Add a variable to distunguish if ajax call is already underway. If it is, don't do anything. If not, go ahead.
var isAjaxInProgress = false;
setInterval(function () {
if (!isAjaxInProgress){
isAjaxInProgress = true;
$.ajax({
method: "POST",
url: "/PLM/FetchPageContent",
dataType: "json",
success: function (data) {
console.log(data);
isAjaxInProgress = false;
}
});
}
}, 1000);

Ajax request type POST returning GET

I'm currently trying to make an ajax POST request to send a testimonial simple form to a Django view. The problem is this request is returning a GET instead of a POST.
This is my ajax:
<script>
$(document).ready(function(){
$("form.testimonial-form").submit(function(e){
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
Any idea what could I be doing wrong?
replace type by method
method: 'post',
also you may need send headers:
headers: {
'X-CSRFToken': getCSRFToken()
},
where getCSRFToken is:
function getCSRFToken() {
return $('input[name="csrfmiddlewaretoken"]').val();
}
I am not really sure why this is happening, but i would write the function in a bit different way. since ajax();'s default type is "GET", i suspect somewhere it is being set to default.
first set the type="button" of submit button (whose id is e.g. "submit_button_id"), so it doesnot submits if you click on it. or put the button outside of <form>
then try this code
<script>
$(function(){ // same as "$(document).ready(function()"..
$("#submit_button_id").on('click',function(){
var dataString = $('form.testimonial-form').serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>

asp.net mvc ajax driving me mad

how come when I send ajax request like this everything works
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
But when I add the anonymous function to the success It always showes me the error message although the song is still deleted
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: function () { ShowMsg("Song deleted successfully"); },
error: function () {
ShowMsg("There was an error therefore song could not be deleted, please try again");
},
dataType: "json"
});
});
what if i wanted few things on success of the ajax call, I need to be able to use the anonymous function and I know that's how it should be done, but what am I doing wrong?
I want the success message to show not the error one.
function ShowMsg(parameter) {
$("#msg").find("span").replaceWith(parameter);
$("#msg").css("display", "inline");
$("#msg").fadeOut(2000);
return false;
}
Make sure your action is returning Json data.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
http://api.jquery.com/jQuery.ajax/
Your action method should surely return Json data. I have the similar code see if that helps.
public ActionResult GetAllByFilter(Student student)
{
return Json(new { data = this.RenderPartialViewToString("PartialStudentList", _studentViewModel.GetBySearchFilter(student).ToList()) });
}
$("#btnSearch").live('click',function () {
var student = {
Name: $("#txtSearchByName").val(),
CourseID: $("#txtSearchByCourseID").val()
};
$.ajax({
url: '/StudentRep/GetAllByFilter',
type: "POST",
data: JSON.stringify(student),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result) {
$("#dialog-modal").dialog("close");
RefreshPartialView(result.data);
}
, error: function() { alert('some error occured!!'); }
});
});
Above code is used to reload a partial view. in your case it should be straight forward.
Thanks,
Praveen

Resources