function foo(dataString){
var jqXHR = $.ajax({
type: "POST",
url: "<?php echo site_url('c_device/check_empId'); ?>",
data: dataString,
dataType: 'json',
cache: false,
success: function(data){
console.log(data);
if(data.length == 0){
return 0;
}
else{
$("#error_"+tr_id).html("Emp id exists");
$("#"+tr_id).css("background-color","red");
return 1;
}
}
});
return jqXHR.responseText;
}
how can I get the returned responseText of foo?
using
(in another jQuery event)
var result = foo(dataString);
doesn't work.
result will still be undefined.
It is best to use callbacks for what you're wanting to do.
var uiHelper = function () {
var cachedText= {};
var getText = function (options) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="options" type="object">options{url:The url to the file with the HTML,successCallback:function,errorCallback:function,isAsync:true||false,cache:true|false}</param>
function xhrSuccess() {
if (this.cache) { cachedText[this.url] = this.responseText; };
if (this.successCallback) {
this.successCallback.apply(this.responseText, this.arguments);
} else {
return cachedText[this.url];
};
};
function xhrError() {
if (this.errorCallback) {
this.errorCallback.apply(this.statusText);
} else {
return this.statusText;
};
};
if (!cachedText[options.url]) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", options.url, options.isAsync);
xmlhttp.cache = options.cache || false;
xmlhttp.url = options.url;
xmlhttp.onload = xhrSuccess;
xmlhttp.onerror = xhrError;
xmlhttp.successCallback = options.successCallback || undefined;
xmlhttp.errorCallback = options.errorCallback || undefined;
xmlhttp.send();
} else {
if (options.successCallback) {
options.successCallback.apply(cachedText[options.url], this.arguments);
} else {
return cachedText[options.url];
};
};
};
return {
getText: getText
};
}();
-----Usage-----
var successCallBack = function () {
}
var errorCallBack= function () {
}
uiHelper.getText(
{
url: 'url',
successCallBack: successCallBack,
errorCallBack: errorCallBack,
isAsync: true,
cache: false
})
This is because ajax is asynchronous, therefore you cant simply do like that.
This issue can be solved in two ways
Passing a callback function
Using jquery's when
passing callback
function foo(dataString, callback){
var jqXHR = $.ajax({
type: "POST",
url: "<?php echo site_url('c_device/check_empId'); ?>",
data: dataString,
dataType: 'json',
cache: false,
success: function(data){
console.log(data);
if(data.length == 0){
return 0;
}
else{
$("#error_"+tr_id).html("Emp id exists");
$("#"+tr_id).css("background-color","red");
return 1;
}
callback (data);
}
});
}
using when
function foo(dataString){
return $.ajax({
type: "POST",
url: "<?php echo site_url('c_device/check_empId'); ?>",
data: dataString,
dataType: 'json',
cache: false
});
}
$.when (foo (dataString)).done (function(data){
console.log(data);
if(data.length == 0){
return 0;
}
else{
$("#error_"+tr_id).html("Emp id exists");
$("#"+tr_id).css("background-color","red");
}
secondMethod (data);
});
Hope this helps
I just added
async: false
in AJAX so it will be SJAX.
Related
How can I pass true or false outside of this Ajax function? I need to return false on something and I cannot do that within Ajax
var zip = $('#order-zip').val();
var zipvalidated;
$.ajax({
type: 'POST',
url: 'checkzip.php',
data: {post:zip},
dataType: 'json',
success: function(data) {
zipvalidated = true;
if (data.response !== "success"){
console.log(data);
console.log ("sorry, we are not delivering in your area right now");
zipvalidated = false;
}
}
});
console.log (zipvalidated);
if (zipvalidated == false) {
return false;
}else{
console.log ("pass!")
}
You can force your request to be syncronous with async: false , but that's not recommended because it will cause the browser to lock up while waiting for results.
You can use callback function instead
const zip = $('#order-zip').val()
var zipvalidated = true
function getZip(zip,callback) {
$.ajax({
type: 'POST',
url: 'checkzip.php',
data: {post:zip},
dataType: 'json',
success: function(data) {
callback(data)
}
})
}
getZip(zip,function(data) {
if (data.response !== "success"){
console.log(data);
console.log ("sorry, we are not delivering in your area right now");
zipvalidated = false;
}
})
console.log (zipvalidated)
Ajax is by default async,
So your if statement runs before zipvalidated variable is updated.
Use async/await or try setting async: false on your ajax request.
Just put the checking in your callback function
$.ajax({
type: 'POST',
url: 'checkzip.php',
data: {post:zip},
dataType: 'json',
success: function(data) {
zipvalidated = true;
if (data.response !== "success"){
console.log(data);
console.log ("sorry, we are not delivering in your area right now");
zipvalidated = false;
console.log (zipvalidated);
if (zipvalidated == false) {
return false;
}else{
console.log ("pass!")
}
}
}
});
I have multiple values, I am trying pass all values in url to controller class at one time.
But last value passed in url.
function submitFormData(formData) {
var x = [];
for(var i = 0;i < formData.length ;i++ ){
alert(i);
x = [];
x.push(formData[i].name);
x.push(formData[i].email);
x.push(formData[i].message);
}
var url= '/userrecords?x='+x;
alert(url);
$.ajax({
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
beforeSend: beforeSendHandler,
url: url,
success: function(result){
if(result.success == true) {
$('.alert-success').show();
$('.alert-danger').hide();
$("#successmsg").html(result.msg);
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
} else {
$('.alert-danger').show();
$('.alert-success').hide();
$("#error").html(result.msg);
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
}
});
}
controller class
#RequestMapping(value = "/userrecords")
public #ResponseBody StatusResponse saveList(#RequestParam(required = false) String x,Model model)
throws ParseException, SQLIntegrityConstraintViolationException {
//read all values here
}
What is wrong in my code. And how to read all values in controller.
Convert your array output in JSON and send it to using AJAX and also you have to define content type is JSON.
you can also use jquery ajax it is very simple for request response.
$.ajax({
type: "POST",
dataType: 'json',
url:"URL here",
success: function(data) // response
{}
});
I think you should post your formdata as ajax data as below.
Pass your x veriable as a ajax data.
function submitFormData(formData) {
var x = [];
for(var i = 0;i < formData.length ;i++ ){
alert(i);
x.push(formData[i].name);
x.push(formData[i].email);
x.push(formData[i].message);
}
var url= '/userrecords';
alert(url);
$.ajax({
type: 'POST',
data: x,
cache: false,
processData: false,
contentType: false,
beforeSend: beforeSendHandler,
url: url,
success: function(result){
if(result.success == true) {
$('.alert-success').show();
$('.alert-danger').hide();
$("#successmsg").html(result.msg);
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
} else {
$('.alert-danger').show();
$('.alert-success').hide();
$("#error").html(result.msg);
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
}
});
}
I have an object with function foo containing a jQuery ajax call
foo: function() {
...
jQuery.ajax({
contentType : "application/json",
type: "POST",
async: true,
...,
success: function(data) {
globalVariable = 1;
},
error: function(error) {
}
});
}
My test code:
var pass = true;
myObj.foo();
if (globalVariable !== 1) {
pass = false;
}
I want statement myObj.foo() finish with ajax finish too. If ajax does not finish, the globalVariable is not equal to 1.
I cannot set async to false in ajax because that is production code.
Your function is running. It's just that it's running asychrounously. If you want to halt your other processes while foo() runs, set async to false.
foo: function() {
...
jQuery.ajax({
contentType : "application/json",
type: "POST",
async: false,
...,
success: function(data) {
globalVariable = 1;
},
error: function(error) {
}
});
}
If that's the case add a function parameter to foo instead. That function will be called after the ajax call has finished.
var bar = function(){
pass=true;
}
Then foo will become
foo: function(func) {
...
jQuery.ajax({
contentType : "application/json",
type: "POST",
async: false,
...,
success: function(data) {
globalVariable = 1;
func();
},
error: function(error) {
}
});
}
Call foo
var pass = false;
myObj.foo(bar);
A code snippet follows promise approach:
var pass = true;
var myObj = {
foo: function () {
return $.Deferred(function (deferred) {
jQuery.ajax({
type: "POST",
url: 'https://httpbin.org/post'
}).done(function () {
deferred.resolve(1);
}).fail(function () {
deferred.reject();
});
}).promise();
}
};
myObj.foo().done(function (globalVariable) {
if (globalVariable !== 1) {
pass = false;
}
});
I have a JSON from a PHP file and I want to send that output to another PHP file. This is my JavaScript:
var data_1;
$.ajax({
type:"POST",
url:"sd.php",
success:function(result){
data_1 = result;
test(data_1);
var st = JSON.stringify(data_1);
$.post('get.php',{q:st},function(data){
window.location = "get.php";
});
}
});
And my PHP file to store the JSON:
<?php
$obj = json_decode($_POST['q']);
echo $obj;
?>
But it outputs nothing. What should I do? Please help.
You may try this i wrote for you, but its not tested
/**
* Created by vladimirnikolic on 3/24/14.
*/
$('#submit').click(function(e){
e.preventDefault();
var form_data = $('#your_form').serializeArray();
var submit_data = serializedFormToDTO(form_data);
$.ajax({
url: 'sd.php',
type: 'POST',
dataType: 'json',
data: submit_data
})
.done(function(xhr) {
$.post("get.php", {
q: submit_data
},
function (data) {
// handle data here
// console.log(data);
}, 'json');
}
)
.fail(function(xhr) {
var response_text = $.parseJSON(xhr.responseText)
console.log(response_text);
})
});
function serializedFormToDTO (data, json) {
json = (typeof json !== 'undefined') ? json : false;
if ((json !== true) && (json !== false) ) {
console.log('invalid value of second parameter (should be true/false for json output)');
return false;
}
var result = {};
for (var i = data.length - 1; i >= 0; i--) {
result[data[i].name] = data[i].value;
}
if (json === true) {
result = JSON.stringify(result);
}
return result;
}
$.ajax({
url: 'sd.php',
type: 'POST',
data: JSON.stringify(data_1), // data_1 is a javascript object here
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(returned_data) {
alert(returned_data);
}
});
My code looks like this. The problem is, PHP side does it job and returns right value. But ajax doesn't execute things inside success: function. What am I missing?
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
$(this).removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" + $(this).data("id") + "]").toggleClass("SelectedDiv");
}
}
});
return false;
});
Try to cache $(this) before ajax call
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
thisElem=$(this),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
thisElem.removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" +thisElem.data("id")+ "]").toggleClass("SelectedDiv");
return false;
}
}
});
});