I have a Ajax-Call inside a Ajax-Call, everything "seems" to work fine. In console I can see, both calls are executed and get a return.
But somehow, i can't use the returned result from the second call(?)
$.ajax({
type: "POST",
url: "register/checkEmail/"+email,
success: function(result){
if(result == "TRUE") {
$('#regMsg').html('Ein User mit dieser Email ist bereits registriert!');
$('#regMsg').slideDown();
// NO ERROR - REGISTER USER
} else {
$('#regMsg').slideUp();
var inputs = $('#regForm :input').serializeArray();
alert('ok');
$.ajax({
method: "POST",
url: "register/save",
data: inputs,
dataType: 'json',
success: function(result){
alert('ddok');
}
});
}
}
});
the first alert() is beeing displayed, the secont is not, although the second call is executed correctly(?) why is that?
Simple - the second call's response did not return back to the ajax i.e error/fail.
Add the error handling part after success to find the response.
After success add
,error: function(result){
alert('error');
console.log(result);
}
If this is not the reason, then dataType: 'json', should be the culprit as your response wouldn't be in json format !!
Related
I have written simple ajax code, in success callback I have written an alert but it does not work.
The code is:
$(".change_forex_transaction_status").click(function(){
$("#insufficient_funds").css("display","none");
var id = $(this).attr('data-transaction_id');
//var ttype = $(this).attr('data-ttype');
if (confirm("Are you sure you want to mark this transaction as complete?")) {
$(this).unbind("click");
$.ajax({
url:"<?php echo Yii::app()->getBaseUrl(true);?>/customer/changeForexTransactionStatus",
type:"POST",
dataType: "json",
//data:{id:id,tidentify:2,ttype:ttype},
data:{id:id,tidentify:2},
success:function(res){
if(res == "unauthorized"){
alert("You Are not authorize to perform this action.");
}else{
if(res == "success"){
location.reload();
} else if(res == "insufficient_fund"){
alert('Insufficient Fees');
$("#insufficient_funds").css("display","block");
} else if(res == 'invalid_fee_account'){
alert('Invalid Merchant Fees Account');
}
}
},
error:function(t) {
console.log(t);
}
});
}
});
Even though the response http status code is 200, it goes into error callback whereas it should have gone in success callback and opened an alert box.
Can anyone please help on this.
You are expecting json back not text so change the ajax dataType to text
dataType: "text",
Use JSON.stringify to post data on server, and when you post data to server in json so use content type "application/json". Now if you expect data in json from server then use dataType: "json". If data from server is html then you can use dataType: "html" or it is text then you can use dataType: "text".
data: JSON.stringify({ id: id, tidentify: 2 }),
contentType: "application/json",
dataType: "json"
I have this ajax request that is sent from javascript in my page
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
async: false,
success: function(data) {
alert(data);
}
});
This returns an array of items with some text and ...
Now if the user clicks on a certain button the data needs to be copied to another place on the page(div)
Is there any way I can get the data again from the file (in the network tab "chrome") without resending the request?
Put the response in global variable (dataArray) and every time check that variable has value or not. So that request will not send further time. Also, you can use that global variable (dataArray) in other methods.
var dataArray = "";
function getData(){
if(dataArray != ""){
$.ajax({
url: "/get.php",
data:{id:ids},
type: 'GET',
//async: false,
success: function(data) {
//alert(data);
dataArray = data;
}
});
}
}
this code is working fine but not showing records. in alert if i am getting record from file its working fine.
$j().ready(function(){
var result =$j.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8',
success:function(data)
{
$j.each(data, function(index,element){
alert("Successful here: "+element);
});
}
});
alert("result"+result);
});
Welcome to the wonderful world of asynchronous ...
First of all, jQuery get doesn't return the data, that needs to be handled by the callback (which is working as from your post)
var result = null;
$j(document).ready(function(){
$j.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8',
success:function(data)
{
result = data;
$j.each(data, function(index,element){
alert("Successful here: "+element);
});
}
});
alert("result"+result);
});
This might not work as well since jQuery ajax is asynchronous and the alert may pop up while the GET is still reading data and not yet ready !!!!
Check Jquery ajax doc:
$.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8'
}).done(function(data) {
console.log(data);
});
The javascript is not waiting AJAX to finish, it moves on. That is why its called asynchronous . If you need synchronous call, use async: false.
I have a form, with a text input and a submit button.
On submit, I want to hit the server first to see if the input is valid, then based on the response either show an error message or if valid, continue with the form submit.
Here is what I have:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
if (data.valid) {
return true
} else {
// Show error message
return false;
e.preventDefault();
}
}
});
});
Problem is the form is always submitting, given the use case, what's the right way to implement? Thanks
Try like this:
$('#new_user').submit(function(e) {
var $form = $(this);
// we send an AJAX request to verify something
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
// if the server said OK we trigger the form submission
// note that this will no longer call the .submit handler
// and cause infinite recursion
$form[0].submit();
} else {
// Show error message
alert('oops an error');
}
}
});
// we always cancel the submission of the form
return false;
});
Since you're already submitting via AJAX why not just submit the data then if it's valid rather than transmit the data twice?
That said, the function that makes the Ajax call needs to be the one that returns false. Then the successvfunction should end with:
$('#new_user').submit()
The fact that AJAX is asynchronous is what's throwing you off.
Please forgive any typos, I'm doing this on my cell phone.
Submitting the same post to the server twice seems quite unnecessary. I'm guessing you just want to stay on the same page if the form doesn't (or can't) be submitted successfully. If I understand your intention correctly, just do a redirect from your success handler:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
location.href = "success.htm";
},
// if not valid, return an error status code from the server
error: function () {
// display error/validation messaging
}
});
return false;
});
Another approach
EDIT: seems redundant submitting same data twice, not sure if this is what is intended. If server gets valid data on first attempt no point in resending
var isValid=false;
$('#new_user').submit(function(e) {
var $form = $(this);
/* only do ajax when isValid is false*/
if ( !isValid){
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
isValid=true;
/* submit again, will bypass ajax since flag is true*/
$form.submit();
} else {
// Show error message
alert('oops an error');
}
}
});
}
/* will return false until ajax changes this flag*/
return isValid;
});
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&json.wrf=?", function(result){
//$.each(result.response.docs, function(result){
if(result.response.numFound==0)
{
$.ajax({
url: "http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&spellcheck=true&json.wrf=?",
async:false,
success: function(result){
$.each(result.spellcheck.suggestions, function(i,item){
newquery=item.suggestion;
});
}
});
}
I posted question related to this problem previously: Problem in accessing a variable's changed value outside of if block in javascript code and i got that i have to make ajax call async. So i did like the above code, but still i am not getting updated newquery outside of if block. still it is showing the old value of newquery.
please suggest where i ma doing wrong
edit
$(document).ready(function(){
// This function get the search results from Solr server
$("#submit").click(function(){
var query=getquerystring() ; //get the query string entered by user
// get the JSON response from solr server
var newquery=query;
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&json.wrf=?", function(result){
//$.each(result.response.docs, function(result){
if(result.response.numFound==0)
{
$.ajax({
url: "http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&spellcheck=true&json.wrf=?",
async:false,
dataType: 'json',
success: function(json){
$.each(json.spellcheck.suggestions, function(i,item){
newquery=item.suggestion;
});
}
});
}
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=20&q="+newquery+"&sort=price asc&hl=true&hl.fl=description&hl.usePhraseHighlighter=true&json.wrf=?", function(result){
Now as i want to use this updated newquery in $getjosn() if result.response.numFound==0,otherwise newquery will hold the old value
Try this:
$(document).ready(function(){
// This function get the search results from Solr server
$("#submit").click(function(){
var query=getquerystring() ; //get the query string entered by user
var newquery=query;
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&json.wrf=?", function(result){
if(result.response.numFound==0)
{
$.ajax({
url: "http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&spellcheck=true&json.wrf=?",
async:false,
dataType: 'json',
success: function(json){
$.each(json.spellcheck.suggestions, function(i,item){
newquery=item.suggestion;
});
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=20&q="+newquery+"&sort=price asc&hl=true&hl.fl=description&hl.usePhraseHighlighter=true&json.wrf=?", function(result){
}
});
}
}else{
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=20&q="+newquery+"&sort=price asc&hl=true&hl.fl=description&hl.usePhraseHighlighter=true&json.wrf=?", function(result){
}
The $.ajax(...) call returns immediatly. The success function is a callback function which means that this function is called when the ajaxrequest completes. If you want to change something with the new values recieved you have to do that in the success function.
A second point is, you overwrite your value for newquery with each loop, so newquery will only hold the last element of your result.speelcheck.suggestions list. Not sure if that is what you want.
You are redefining 'result' in the ajax() success function. Change this, and then work on fixing your problem :)
You want to call the getJSON() function within the success function of the $.ajax() request. The success() event isn't called until the data has been returned, this won't happen straight away, and so the final getJSON() event will fire before this.
Moving the getJSON() function to the end of the $.ajax() success function will resolve your problem.
Ensure it's outside the $.each() statement.
new answer based on answer from michael wright:
$(document).ready(function(){
// This function get the search results from Solr server
$("#submit").click(function(){
var query=getquerystring() ; //get the query string entered by user
var newquery=query;
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&json.wrf=?", function(result){
if(result.response.numFound==0)
{
$.ajax({
url: "http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=100&q="+query+"&spellcheck=true&json.wrf=?",
async:false,
dataType: 'json',
success: commonSuccess});
}else{
$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=20&q="+newquery+"&sort=price asc&hl=true&hl.fl=description&hl.usePhraseHighlighter=true&json.wrf=?", commonSuccess);
}
//...
}); //End of $(document).ready(...)
function commonSuccess(json){
//do onSuccess for all queries
}