I have the problem with my request. Look at this code
logInWithFacebook = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', {fields: 'name,email,location,picture'},function(userInfo) {
FB.api('/me/picture?type=normal', function (response) {
userInfo.photo = response.data.url; // what's wrong with that?
});
if(userInfo.location)
{
var location = userInfo.location.name.split(",");
userInfo.location = location[0];
}
$.ajax({
data:userInfo,
type:"POST",
url:"/login/facebook-loginexecute",
dataType: "json",
beforeSend: function() {
console.log(userInfo); // everything is showing
},
success: function(result) {
}
});
});
}
},{scope: 'public_profile,email,user_location'});
return false;
};
So, after the send data (in this case "userinfo") through ajax, PHP function print_r - return everything without element's $_POST - photo. I don't know why?
'
My guess is that FB.api call is asynchronous, so you fire it in the background and then fire your own ajax call before FB.api success callback is executed.
Move your ajax call inside of the FB.api callback:
logInWithFacebook = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', {
fields: 'name,email,location,picture'
}, function(userInfo) {
FB.api('/me/picture?type=normal', function(response) {
userInfo.photo = response.data.url; // what's wrong with that?
if (userInfo.location) {
var location = userInfo.location.name.split(",");
userInfo.location = location[0];
}
$.ajax({
data: userInfo,
type: "POST",
url: "/login/facebook-loginexecute",
dataType: "json",
beforeSend: function() {
console.log(userInfo); // everything is showing
},
success: function(result) {
}
});
});
});
}
}, {
scope: 'public_profile,email,user_location'
});
return false;
};
As to why is it showing in the console, the console probably maintains a reference to the object, and by the time you look at it, the initial request has been completed.
Related
Currently I have a javascript file structure which seems deprecated to me, inside this function there's an ajax call, and after the ajax call giving response I want to add ajax function, but if I have to define it 1 by 1 for every ajax response type, it will consume a lot of space so I need to make a function which will call this ajax function, but I don't know where to place this function that I will make. here's my code
return Component.extend({
defaults: {
template: 'Icube_Snap/payment/snap'
},
redirectAfterPlaceOrder: false,
afterPlaceOrder: function() {
$.getScript(js, function() {
$.ajax({
type: 'post',
url: url.build('snap/payment/redirect'),
cache: false,
success: function(data) {
var token = data;
var methods = [];
var methodSnap = $('input[name=snap-method]:checked').val();
snap.pay(token, {
enabledPayments: methods,
onSuccess: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onPending: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onError: function(result) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
},
onClose: function() {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: resut.id,
message: result.message
}
success: function(data) {
}
});
}
});
}
});
});
}
});
I just added a successcallback and an errorcallback to the POST function. But if you want you can ignore those functions and implement the success and error functionality inside the function itself without using callbacks.
return Component.extend({
defaults: {
template: 'Icube_Snap/payment/snap'
},
redirectAfterPlaceOrder: false,
afterPlaceOrder: function() {
$.getScript(js, function() {
$.ajax({
type: 'post',
url: url.build('snap/payment/redirect'),
cache: false,
success: function(data) {
var token = data;
var methods = [];
var methodSnap = $('input[name=snap-method]:checked').val();
//Define a function to send the POST request here.
//////////////////////////////////////////////////
var sendPayment = function(param, successcallback, errorcallback) {
$.ajax({ // <-- this ajax needs to be inside function with parameter
type: 'post',
url: url.build('custom/message/post'),
cache: false,
param: {
id: param.id,
message: param.message
}
success: function(data) {
successcallback(data);
},
error: function(error) {
errorcallback(error);
}
});
};
snap.pay(token, {
enabledPayments: methods,
onSuccess: function(result) {
//Call sendPayment method and you can
//pass whatever you want.
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onPending: function(result) {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onError: function(result) {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
},
onClose: function() {
sendPayment(result, function() {
//Call when success
}, function() {
//Call when error
});
}
});
}
});
});
}
});
I have following jquery code in my Razor viewpage
$(document).ready(function () {
var grouplistvalues = #Html.Raw(Json.Encode(Session["grouplist"]));
$("#nsline").click(function () {
alert(grouplistvalues)
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
alert(response)
},
error: function ()
{
}
});
});
$("#ewline").click(function () {
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
},
error: function ()
{
}
});
});
in above grouplistvalues its taking session as html raw
when I alert it on #nsline click function I can see it,
in above function I'm calling to ajax function and above grouplistvalues value updating
once I alert it on #nsline click function success response I can see a alert like folllowing
since this(grouplistvalues value) 1,2,.. changing as [1,2..] I cannot call to other ajax function in #ewline click function since parameter difference,
this is the above common ajax call
[HttpPost]
public JsonResult SetupGroups(long[] grouplist)
{
Session["grouplist"] = null;
List<long> groupList = new List<long>();
foreach (var groupitem in grouplist)
{
groupList.Add(groupitem);
}
long[] grouparray = groupList.ToArray();
Session["grouplist"] = grouparray;
return Json(grouparray);
}
}
Though I have two click functions its work with only the first click(ewline or nsline only the first time)
How to solve this
It was the dataType in your ajax request. It should be json:
dataType: "json"
I have gone through many topics on stack overflow for jquery asynchronous AJAX requests. Here is my code.
funciton ajaxCall(path, method, params, obj, alerter) {
var resp = '';
$.ajax({
url: path,
type: method,
data: params,
async: false,
beforeSend: function() {
$('.black_overlay').show();
},
success: function(data){
console.log(data);
resp = callbackFunction(data, obj);
if(alerter==0){
if(obj==null) {
resp=data;
} else {
obj.innerHTML=data;
}
} else {
alert(data);
}
},
error : function(error) {
console.log(error);
},
complete: function() {
removeOverlay();
},
dataType: "html"
});
return resp;
}
The problem is, when I use asyn is false, then I get the proper value of resp. But beforeSend doesn't work.
In case, I put async is true, then its beforeSend works properly, but the resp value will not return properly, Its always blank.
Is there any way to solve both problems? I would get beforeSend function and resp value both.
Thanks
Use async:false and run the function you assigned to beforeSend manually before the $.ajax call:
var resp = '';
$('.black_overlay').show();
$.ajax({
...
Either that or learn how to use callback functions with asynchronous tasks. There are many nice tutorials on the web.
Take the resp variable out from the function
Create one extra function respHasChanged()
when you get the data successfully, use the code
resp = data;respHasChanged();
You can restructure on this way, (why no use it in async way?)
function ajaxCall(path, method, params) {
return $.ajax({
url: path,
type: method,
data: params,
beforeSend: function() {
$('.black_overlay').show();
},
dataType: "html"
});
}
Call in your javascript file
ajaxCall(YOUR_PATH, YOUR_METHOD, YOUR_PARAMS)
.done(function(data) {
console.log(data);
// DO WHAT YOU WANT TO DO
if (alerter == 0 && obj !== null) {
obj.innerHTML = data;
} else {
alert(data);
}
}).fail(function(error) {
console.log(error);
}).always(function() {
removeOverlay();
});
i'm trying to make infinite scrolling so when scrolling i make an ajax request to the server to get data but when scrolling a multiple ajax request is made and return the same data so how can i cancel ajax request before sending if there one already exist i tried like this
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
all my code
var lock_load = '1';
var activeAjaxConnections = 1;
var PageNumber = 2;
$(window).scroll(function () {
if ((Math.ceil($(window).scrollTop() - $(window).height()) * -1) <= getHeight() + 550) {
if (lock_load === '1') {
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
alert(errorThrown);
n }
});
}
}
});
but it give an error xhr is undefined pleas any help and many thanks in advance.
Try flags
Before making ajax call set flag to true and after ajax call is made set flag to false, finally on completion of ajax request again set flag to ture
var ready = true;
$(window).scroll(function(){
if(ready == true){
ready = false;
$.ajax({
url: "/pagination",
cache: false,
success: function (response){
//response
}
}).always(function () {
ready = true; //Reset the flag here
});
}
});
use the below code, use a simple flag variable that will be set to false by the defualt, that is to say that ajax call is not occuring once if condition is met then it will set to true to say that ajax call has started, once the success: or error: call back fires the variable will be set to false so that another ajax call can be made.
startedAjax = false;
if (lock_load === '1') {
startedAjax = true;
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
startedAjax = false //set is false
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
startedAjax = false;
alert(errorThrown);
}
});
}
}
});
I have a javascript function that calls a generic function to make an ajax call to the server. I need to retrieve a result (true/false) from the callback function of the ajax call, but the result I get is always 'undefined'.
A super-simplified version of the generic function without all my logic would be:
function CallServer(urlController) {
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic)
return true;
else
return false;
},
error:
function(errorThrown) {
return false;
}
});
}
And the function calling it would be something like:
function Next() {
var result = CallServer("/Signum/TrySave");
if (result == true) {
document.forms[0].submit();
}
}
The "result" variable is always 'undefined', and debugging it I can see that the "return true" line of the callback function is being executed.
Any ideas of why this is happening? How could I bubble the return value from the callback function to the CallServer function?
Thanks
Just in case you want to go the asynchronous way (which is a better solution because it will not freeze your browser while doing the request), here is the code:
function CallServer(urlController, callback) {
$.ajax({
type: "POST",
url: urlController,
async: true,
data: $("form").serialize(),
success:
function(result) {
var ret = ( someLogic );
callback(ret);
},
error:
function(errorThrown) {
return false;
}
});
}
function Next() {
CallServer("/Signum/TrySave", function(result) {
if (result == true) {
document.forms[0].submit();
}
});
}
I usually put any code to be executed on success inside the callback function itself. I don't think CallServer() actually receives the return values from the callbacks themselves.
Try something like:
function CallServer(urlController) {
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic)
document.forms[0].submit();
else
// do something else
},
error:
function(errorThrown) {
// handle error
}
});
}
Edit: I'm not too familiar with jQuery, so I might be completely wrong (I'm basing this on the behavior of other frameworks, like YUI, and AJAX calls made without any framework). If so, just downvote this answer and leave a comment, and I will delete this answer.
Just found how to do it :) Declaring a variable and updating it accordingly from the callback function. Afterwards I can return that variable. I place the code for future readers:
function CallServer(urlController) {
var returnValue = false;
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic){
returnValue = true;
return;
}
},
error:
function(errorThrown) {
alert("Error occured: " + errorThrown);
}
});
return returnValue;
}