Getting the result of jquery .post() function - javascript

I need to find out how to access "data" variable outside of the post function. It will return either valid or invalid so I can finish the main function logic.
Is this the right way to do it:
$('#form_choose_methods').submit(function(){
var voucher_code = $('#voucher_code').val();
var check = $.post(baseURL+"ajax.php", { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
function(data) {
});
alert(check);
return false;
});
check seems to be the object, but I want to know how to access result of it.

You can access the response in the success callback you use
$.post(baseURL+"ajax.php", { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
function(data) {
// you can access the response in here
alert(data);
});
Ajax calls are asynchronous, so you will only have access to the result from the callback whenever it completes..

$('#form_choose_methods').submit(function () {
var voucher_code = $('#voucher_code').val();
$.post(baseURL + "ajax.php", { tool: "vouchers", action: "check_voucher", voucher_code: voucher_code },
function (data) {
if (data == "valid") {
//do seomthing
}
else {
//do something else
}
});
});

Related

JQuery AJAX - Filter before .done()

My application has a lot of AJAX calls, each of them return a JSON response. Instead of validating the data in each of the the .done() calls, I'm trying compact the code.
What we have so far
$.ajax({
url: 'test',
type: 'GET',
data: {
_token: token
},
dataFilter: function(jsonResponse) {
return isValidJson(jsonResponse);
}
}).done(function(jsonResponse) {
// do things
});
isValidJson(jsonResponse) {
try {
var parsedJson = $.parseJSON(jsonResponse);
if (parsedJson.error == 1) {
notificationController.handleNotification(parsedJson.message, 'error');
return false;
}
} catch (err) {
notificationController.handleNotification('A server-side error occured. Try refreshing if the problem persists.', 'error');
return false;
}
return jsonResponse; // Have to return the original data not true
}
The expected behavior is that if dataFilter returns false, it will trigger .fail(), if it returns true then it will continue to .done(). Instead, it just continues to .done() with the result of isValidJson().
Is there also a way to make .fail() do something standard like send a notification to the user without having to put it under every AJAX call?
Easiest way is to create a shorthand for $.ajax, by extending it.
Extending the AJAX call
jQuery.extend({
myAjax: function(params){
// Here we can modify the parameters and override them e.g. making 'error:' do something different
// If we want to add a default 'error:' callback
params.error = function() {
console.log('its failed');
};
// or you can specify data parse here
if (params.success && typeof params.success == 'function') {
var successCallback = params.success;
var ourCallback = function(responseJson) {
if (isValidJson(responseJson)) { // Validate the data
console.log('The json is valid');
successCallback(responseJson); // Continue to function
} else {
console.log('The json is not valid');
}
}
params.success = ourCallback;
}
return $.ajax(params);
}
});
Now everytime you want to make an AJAX call in your application, you DO NOT use $.ajax({}). Instead, you use $.myAjax({});
Example
$.myAjax({
url: 'domain.com',
type: 'GET',
success: function(data) {
// Do what you'd do normally, the data here is definitely JSON.
},
error: function(data) {}
});
And this special function will handle all errors same way, no need to write those validators every time.
Try to do it like this (Not tested):
var jxhr = $.ajax({
url: 'test',
type: 'GET',
data: {
_token: token
},
dataFilter: function(jsonResponse) {
if (!isValidJson(jsonResponse)) {
jxhr.abort();
}
return jsonResponse;
}
}).done(function(jsonResponse) {
// do things
});
By using this strategy - you are violating "separation of concern" strategy.
Ajax should resolve or reject according to its action. Not according if response is JSON or not.
A possible solution : ( sure there are also another solutions)
function GetSanitized(d) {
return d.then(function(a) {
if (a.indexOf('{') > -1) //check if json ( just for example)
return $.Deferred().resolve(JSON.parse(a)); //return object
else
return $.Deferred().reject(a); //reject
},
function() {
return $.Deferred().reject("ajax error"); //ajax failed
}
);
}
var ajax = $.Deferred();
GetSanitized(ajax) .then(function (a){alert(" Json p's value is "+a["p"]);},function (a){alert("Error"+a);});
ajax.resolve("{\"p\":2}"); //simulate ajax ok , valid json
//ajax.resolve("\"p\":2}"); //simulate ajax ok , invalid json
//ajax.reject("\"p\":2}"); //simulate ajax bad , valid json
http://jsbin.com/vozoqonuda/2/edit

Ajax call showing error cant debug

this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?

use different parameter for a success callback

I'm working on someone else's code. I have this simple AJAX call in jQuery:
function getWSData (which, data, idVR)
{
if(which == 'verCandAll')
{
funcSuccess = verCandSuccess;
data = {'name' : 'val'};
}
else
{
funcSuccess = verElseSuccess;
data = {'name2' : 'val2'};
}
$.ajax({
type: 'POST',
url: wsURL,
data: data,
success: funcSuccess,
error:function ()
{
$("#msg").ajaxError(function()
{
popWaiting(false);
alert(verGenericCallError);
});
},
dataType: 'xml'
});
}
function verCandSuccess(xml){ ... }
function verElseSuccess(xml){ ... }
It's really simple. The only problem I have is the success callback. In case of verElseSuccess I would send a second parameter to that function, more precisely i would handle the idVR (an input parameter of getWSData). How can I accomplish this?
To achieve this, you can do:
...
if(which == 'verCandAll') {
...
}
else {
// create an anonymous function that calls verElseSuccess with a second argument
funcSuccess = function(xml) {
verElseSuccess(xml, idVR);
};
data = {'name2' : 'val2'};
}
...
Use Underscore.js partial function:
funcSuccess = _.partial(verElseSuccess, idVR);

how to stop one method execution untill another method completes in javascript with Linkedin API people search?

I am calling IN.API.PeopleSearch() from a for loop, and this for loop is in ajax success method, but before completing for loop execution, ajax method complete is getting called.
I want to stop until the for loop completes.
$.ajax({
type: 'GET',
dataType: 'json',
url: "get_data.htm",
async : false,
success: function(data, textStatus ){
for(i in data){
searchClick(data[i].firstName,data[i].lastName);
}
alert(resultArray);//here i want to send the response to server side
}
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
here is my searchClick function :
function searchClick(firstName, secondName) {
if (!IN.ENV.auth.oauth_token) {
alert("You must login w/ LinkedIn to use the Search functionality!");
return;
}
IN.API.PeopleSearch()
.fields("id", "firstName", "lastName","emailAddress","headline","industry","pictureUrl","positions",
"summary","numConnections")
.params({
"first-name": firstName,
"last-name": secondName
})
.result(function(result, metadata) {
for (i in result.people.values) {
try{
resultArray[i] = result.people.values[i];
}catch(err){
alert(err);
}
}
});
}
alert(resultArray) is getting called before completion of for loop, how to handle this.
I don't know if I get your question, but maybe something like that works for you: (not tested)
var Queue = function(callback) {
this.count = 0;
this.done = 0;
this.callback = callback;
};
Queue.prototype.oneDone = function() {
if (++this.done == this.count) {
this.callback();
}
}
Queue.prototype.process = function(data, callback) {
this.count = data.length;
for (i in data ) {
callback(data[i], this);
}
};
$.ajax({
type: 'GET',
dataType: 'json',
url: "get_data.htm",
async : false,
success: function(data, textStatus) {
var myQueue = new Queue(function() {
alert(resultArray); //here i want to send the response to server side
});
myQueue.process(data, function(item, queue) {
searchClick(item.firstName, item.lastName, queue);
});
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
});
function searchClick(firstName, secondName, queue) {
if (!IN.ENV.auth.oauth_token) {
alert("You must login w/ LinkedIn to use the Search functionality!");
return;
}
IN.API.PeopleSearch()
.fields("id", "firstName", "lastName","emailAddress","headline","industry","pictureUrl","positions",
"summary","numConnections")
.params({
"first-name": firstName,
"last-name": secondName
})
.result(function(result, metadata) {
for (i in result.people.values) {
try {
resultArray[i] = result.people.values[i];
} catch(err) {
alert(err);
}
}
if (queue) {
queue.oneDone();
}
});
}
I don't know what you are doing exactly, but can say we have one method, async
Function.prototype.async = function () {
setTimeout.bind(null, this, 0).apply(null, arguments);
};
This allows me to write code like this:
alert.async("This will be displayed later.");
alert("This will be displayed first.");
so the code with .async will called once the other event is completed.
Else in your case, use
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
for checking if the document is ready then send /fill /success. this is Raw AJAX method. :)
O hope this may help :)

Returning jQuery Ajax Post

I wish to use the jQuery.post class to return (not alert) the response within a function.
The following gives an alert with the appropriate value:
function test_func() {
$.post("test.php", { cmd: "testing" }, function (data) { alert(data); })
}
(displays alert with appropriate value)
I tried the following:
function test_func() {
return $.post("test.php", { cmd: "testing" }, function (data) { return data; })
}
(returned object)
function test_func() {
var tmp;
$.post("test.php", { cmd: "testing" }, function (data) { tmp=data; })
return tmp;
}
(returned undefined)
var tmp;
function setTmp(n) {
tmp=n;
}
function test_func() {
t=$.post("test.php", { cmd: "testing" }, function (data) { setTmp(data); })
}
(returned undefined)
function test_func() {
t=$.post("test.php", { cmd: "testing" })
return t.responseText;
}
(returned undefined)
So what's the deal? How can I make "test_func()" return the data response text?
Being an asynchronous request, you aren't able to get a response as soon as you call the function. Instead, the function that you pass to $.post is intended to be a callback that will perform some action as soon as the response is complete. Consider the following:
function myCallback(response) {
// do something with `response`...
}
function test_func() {
$.post("test.php", { cmd: "testing" }, myCallback)
}
Instead of directly returning a response, you can instead manipulate it as needed in the myCallback function.
The deal is ajax is asynchronous one possible solution is to set it as sync like
$.ajaxSetup({
async:false
});
and then
function test_func() {
var temp;
t=$.post("test.php", { cmd: "testing" })
return t.responseText;
}
the answer is only to make your current setup work else there are better ways to deal with it

Categories