Hey all I am working on a json call that will implement Drupal's services module with json. I am using jquery's ajax function to call the function but I am getting an error stating that no parameters are being passed. When I look at the query string being posted I notice that sessid is not being passed even though its with the parameters. Below is what Im running.
// JavaScript Document
$(document).ready(function() {
function drupalConnect(src) {
$.ajax({
url: src,
type: 'POST',
data: {
method: 'system.connect'
},
success: function(data) {
return data["result"]["sessid"];
}
});
}
function getTimestamp() {
return Math.round((new Date).getTime() / 1000);
}
function randString(length) {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var randomstring = '';
for (var i = 0; i < length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum, rnum + 1);
}
return randomstring;
}
var session_id = drupalConnect('http://localhost/drupal/services/json-rpc');
var nonce = randString(10);
var timestamp = getTimestamp();
var username = "markusgray";
var password = "Markus1990";
var key = '2ae0392e0aebbfeeddefcc962ea1924f';
var domain = 'localhost';
var hashObj = new jsSHA(timestamp + ";" + domain + ";" + nonce + ";user.login", "TEXT");
var hash = hashObj.getHMAC(key, "TEXT", "SHA-256", "HEX");
var parameters = {
hash: hash,
domain_name: domain,
domain_time_stamp: timestamp,
nonce: nonce,
sessid: session_id,
username: username,
password: password
};
var par = JSON.stringify(parameters);
$.ajax({
url: 'http://localhost/drupal/services/json-rpc',
type: 'POST',
dataType: 'json',
data: {
method: 'user.login',
params: par
},
success: function() {
}
});
});
drupalConnect doesn't return anything, also the return from the success callback is just thrown away. The best way to use the data returned from an ajax call is to use it in thee callback itself.
function drupalConnect(src){
$.ajax({
url: src,
type: 'POST',
data:{method:'system.connect'},
success: function(data){
var session_id = data["result"]["sessid"];
//use session_id here
}
});
}
It is because of the Asynchronous ajax, let me elaborate, to get the session_id you are making an ajax call. At the moment it will send the request, but it wont ensure that the session_id will be assigned at that moment. Hence when you making the second ajax call, the session_id may not be assigned for a value.
There are two workarounds for this,
One is, making the first ajax call with an option async:false and assign the value within the success call, something like
var session_id;
function drupalConnect(src) {
$.ajax({
url: src,
type: 'post',
async : false,
data: {
method: 'system.connect'
},
success: function(data) {
session_id = data["result"]["sessid"];
}
});
};
DEMO
The second one and preferred way is, use of deferred objects, something like
$.when(
// make your first ajax request
).then(function(data) {
session_id = data["result"]["sessid"];
// make your second ajax call
});
DEMO
Related
This code needs to 1) check if users are online 2) get their information from a slightly different URL and 3) output both to HTML. It works, but inconsistently. In some cases when running the function for outputting the HTML it says that the data from the first request (online or not) is undefined. Right now streamData and userData are globals. But I wish I could get it to work without that. Having issues getting both data sources to consistently be available in the same place at the same time.
var getOnline = function(){
for (var i = 0; i < twitchFaves.length; i++) {
userName = twitchFaves[i];
streamAjaxOnline(userName);
}
}
var streamAjaxOnline = function(userName){
$.ajax({
type : 'GET',
url : "https://wind-bow.gomix.me/twitch-api/streams/" + userName,
dataType : 'jsonp',
success : function(twitchData) {
streamData = twitchData;
if (streamData.stream){
userAjaxOnline(userName);
}
}
});
}
var userAjaxOnline = function(userName){
$.ajax({
type : 'GET',
url : "https://wind-bow.gomix.me/twitch-api/users/" + userName,
dataType : 'jsonp',
success : function(twitchData) {
userData = twitchData;
displayTwitchOnline(streamData, userData);
}
});
}
Right now streamData and userData are globals
That's really bad. It means that multiple calls to the functions will share the same variables and overwrite the results of each other.
But I wish I could get it to work without that.
That's relatively easy: Pass the data to the functions instead. A very simple solution would be:
var streamAjaxOnline = function(userName) {
$.ajax({
type: 'GET',
url: "https://wind-bow.gomix.me/twitch-api/streams/" + userName,
dataType: 'jsonp',
success: function(twitchData) {
if (streamData.stream) {
userAjaxOnline(userName, streamData); // pass streamData here
}
}
});
}
var userAjaxOnline = function(userName, streamData) { // accept streamData here
$.ajax({
type: 'GET',
url: "https://wind-bow.gomix.me/twitch-api/users/" + userName,
dataType: 'jsonp',
success: function(twitchData) {
// no need to store userData if you only use it here
displayTwitchOnline(streamData, twitchData);
}
});
}
Is there a possible way to send the variable, 'schedule_id[i]', with the result of the call. Also is it possible to add this variable in the data object?
My code:
for (var i = 0; i < schedule_id.length; i++) {
//Ajax call
$.ajax({
url: "http://api.viewer.zmags.com/schedules/" + schedule_id[i] + "?key=" + api_key
})
//
.done(function(data){
}
So you need asynchronies ajax call in synchronies manner right?
So you need to create one separate function which is call ajax request and return the result and use in subsequent request.
Like:-
for (var i = 0; i < schedule_id.length; i++) {
var result;
if (i == 0)
result = callfunction(0,schedule_id[i]);
else
result = callfunction(result,schedule_id[i]);
}
function callfunction(passresult,schedule_id) {
$.ajax({
url: "http://api.viewer.zmags.com/schedules/" + schedule_id + "?key=" + api_key
})
.done(function (data) {
return data;
});
}
construct the ajax call like this:
$.ajax({
url: 'http://api.viewer.zmags.com/schedules/',
type: 'POST' // or GET,
data: {
schedule_ids: schedule_id, //array
key: api_key
},
success: function (data) {
//success callback
}
});
Hello Fellow Developers,
I have a SSN textbox that onblur calls a function which does an ajax request to a Web Method to decide if an employee has been previously hired.
The Web Method returns a TermedEmployee Object to the success callback, but I'm unsure how to parse the object.
$('#<%=FormView1.FindControl("SSNField").ClientID%>').blur(hideValue);
hideValue = function (ev) {
var $this = $(this);
$this.data('value', $this.val());
$('#<%=FormView1.FindControl("hiddenSSN").ClientID%>').val($this.val());
var data2Send = '{"SSN": ' + $this.val() + ' }';
$.ajax({
type: "POST",
url: "AuthforHire.aspx/EmployeeisRehire",
data: data2Send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var obj = JSON.stringify(result.d);
if (obj.IsTermed) {
$('#%=RadWindowRehire.ContentContainer.FindControl("TextBoxTermID").ClientID%>').val(arg.d);
var wndWidth = 900;
var wndHeight = 500;
var wnd = window.radopen(null, "RadWindowRehire");
}
},
error: function (xhr) {
alert('Form update failed. '); //error occurred
}
});
Below is a minified version of my webMethod, which works correctly
[System.Web.Services.WebMethod]
public static TermedEmployee EmployeeisRehire(string SSN)
{
TermedEmployee termedEmp = new TermedEmployee();
// Db call to get necessary data.
termedEmp.Name = dr["name"];
termedEmp.TermDate = Convert.ToDateTime(dr["TermDate"].ToString());
......
}
So How Can I extract Name, TermDate,StartDate, ReasonforTerm, etc from the object returned to the callback function?
Thank you in advance!
The first line in your success callback is:
var obj = JSON.stringify(result.d);
Which is trying to serialize what ASP.Net will already have serialized for you.
Change this to:
var obj = result.d;
And you will then have access to obj.Name, obj.TermDate and all the other properties by name.
I am trying to get the string to order by how it is displayed (red,blue,orange,black). For some reason, it will append the order randomly. For Example: it would output (blue,orange,red,black). Any help would be great. Thanks.
var tCookie = "red,blue,orange,black";
var Cookies = tCookie.split(',');
if (Cookies) {
for (var i = 1; i <= Cookies.length; i++) {
var dataString = "TabId="+Cookies[i]+"";
$.ajax({
type: "POST",
url: "includes/tab.php",
data: dataString,
cache: false,
success: function(html){
$("#Dynamic_Tab").append(html).children(':last').hide().fadeIn("fast");
}
});
}
}
You could have a list of requests and responses, and start appending when all are done, so that the order is always correct:
var deferreds = [],
results = [];
for (var i = 1; i <= Cookies.length; i++) {
(function(i) { // to freeze i
var dataString = "TabId="+Cookies[i]+"";
deferreds.push($.ajax({
type: "POST",
url: "includes/tab.php",
data: dataString,
cache: false,
success: function(html){
results[i] = html; // insert at the synchronous position
}
}));
})(i);
}
$.when.apply($, deferreds).then(function() {
$.each(results, function(i, html) {
$("#Dynamic_Tab").append(html).children(':last').hide().fadeIn("fast");
});
});
You can use deferred objects here to only append the HTML after all of the AJAX requests come back:
//create array to store XHR objects that will resolve when the AJAX requests return
//also create an object to store the AJAX responses
var jqXHRs = [],
responses = {};
//iterate through each of the cookie indexes
$.each(cookies, function (index, value) {
//create the dataString and cache the value of this index so it can be used in the success callback for the AJAX request associated with this index
var dataString = "TabId=" + value,
thisValue = value;
//store an empty string in the output variable for the current index, this keeps it's place in-line
responses[thisValue] = '';
//do the AJAX request and store it's XHR object in the array with the rest
jqXHRs[jqXHRs.length] = $.ajax({
type : "POST",
url : "includes/tab.php",
data : dataString,
cache : false,
success : function (html) {
//now that the AJAX request has returned successfully, add the returned HTML to the output variable for this index
responses[thisValue] = html;
}
});
});
//wait for all of the XHR objects to resolve then add all the HTML to the DOM
$.when(jqXHRs).then(function () {
//all of the AJAX requests have come back and you can now add stuff to the DOM
var $element = $("#Dynamic_Tab");
$.each(responses, function (index, value) {
$element.append(value).children(':last').hide().delay(index * 250).fadeIn(250);
}
});
The .delay() is so that each new row will fade in, in order.
I want to create a separate function to get specific data from Facebook graph JSON.
For example, I have the load() and called getNextFeed() function.
The getNextFeed works correctly. Except that returning value of aString is not successful.
When I pop alert(thisUrl). It said undefined.
Note: I am new to Javascript and Jquery. Please give me more information where I did wrong. Thank you.
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
var thisUrl = getNextFeed(url);
alert(thisUrl); // return undefined
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
return aString;
}
});
}
The problem is that $.ajax() is an ansynchronous function, means, when called, it returns in the same instance, but an ajax call is done in a separate thread. So your return vaule of $.ajax() is always undefined.
You have to use the ajax callback function to do whatever you need to do: Basically you already did it correctly, just that return aString does not return to your original caller function. So what you can do is to call a function within the callback (success()), or implement the logic directly within the success() function.
Example:
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
getNextFeed(url);
alert('Please wait, loading...');
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
do_something_with(aString);
}
});
}