This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have an ajax call and I want to use result of this ajax on another page.
//This is main.js file
function myFun(){
var my_user = "Stas";
var itemsUrl = "myxmlwithusers";
var user_found = false;
$.ajax({
url: itemsUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
cache: false,
async: false,
dataType: "text",
success: function(data){
var jsonObject = JSON.parse(data);
results = jsonObject.d.results;
$(results).each(function(){
if($(this)[0].user == my_user){
user_found = true;
}
});
},
error:function () {
console.log("Error");
}
}
);
}
// This is execute.js file
myFun();
if (user_found == true){cool}
I need true or false for // user_found. Let say I will put in the file execute.js my function myFun() and in main.js my user is fetch with "$(this)[0].user" and I need to receive "true" in execute.js
Thanks!
The problem is that $.ajax call is asynchronous, a.k.a you check for value of user_found before it is set. try this approach
function myFun(callback){
var my_user = "Stas";
var itemsUrl = "myxmlwithusers";
var user_found = false;
$.ajax({
url: itemsUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
cache: false,
async: false,
dataType: "text",
success: function(data){
var jsonObject = JSON.parse(data);
results = jsonObject.d.results;
$(results).each(function(){
if($(this)[0].user == my_user){
user_found = true;
}
});
if(typeof callback === "function"){
callback(user_found);
}
},
error:function () {
console.log("Error");
}
}
);
}
Then you can use it like
myFun(function(result){
if (result == true){
//cool
}
});
1st: simply in html before including any js files
<head>
<script>
var user_found = true; // or false if you like
</script>
// include main.js and execute.js
</head>
now you can call user_found anywhere in js files without var .. even it change in any js files functions it will change in others
Simple Example
2nd: If you include main.js before execute.js you can use it like
var user_found = false;
function myFun(){
var my_user = "Stas";
var itemsUrl = "myxmlwithusers";
$.ajax({
url: itemsUrl,
....................
Simple Example
Consider using HTML5 Local Storage. Stored values should be accessible by every page served on your domain.
// Store
localStorage.setItem("user_found", "true");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("user_found");
Related
I need to use the same if..else to deal with every AJAX data in my code.
$.ajax({
url: "api/aall.json",
dataType:'json',
type: 'GET',
data: "data",
cache: false,
ifModified: true,
success: function getData(data){
console.log(data);
for(var i=0;i<7;i++){
// if...else
}
});
There are several AJAX get differnt:
$.ajax({...});
$.ajax({...});
$.ajax({...});
$.ajax({...});
if...else code:
if(MainClass_Code=="PD" || MainClass_Code=="CD"){
newsKindRepalce = "aipl";//news
}else if(MainClass_Code=="PF" || MainClass_Code=="JF"){
newsKindRepalce = "aopl";//international
}else if(MainClass_Code=="CU"){
newsKindRepalce = "acul";//culture
}else{
newsKindRepalce = "acn";//artist
}
It's would be very heavy when I use if...else in my all AJAX to deal with data, how can I do to simplify this?
change your if else to this:
const code = { PD: "aipl", CD: "aipl", PF: "aopl", JF: "aopl", CU: "acul" };
newsKindRepalce = code.hasOwnProperty(MainClass_Code)
? code[MainClass_Code]
: "acn";
<script>
$(document).ready(function() {
$("#btnSubmit").live('click',function(){
var sum = '0';
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var required = $(this).attr("data-required");
var label = $(this).attr("data-label");
if(required == '1'){
if(c_data == ""){
sum += '1';
}
}
});
if(sum == "0"){
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var admin = $(this).attr("data-admin");
var form = $(this).attr("data-form");
var component = $(this).attr("date-component");
var unic = $(this).attr("data-unic");
var user = $(this).attr("data-user");
var url = "<?php echo Yii::app()->createUrl('formdata/admin&id='.$form_id);?>";
if(c_data == ""){
var site_url = "<?php echo Yii::app()->createUrl('/formdata/deleteDetail' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
} else {
var site_url = "<?php echo Yii::app()->createUrl('/formdata/updateDetailValue' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
}
});
window.location = "http://www.example.com";
}else {
if(sum != ""){
bootbox.dialog({
message: 'Please Fill All Required Field !',
title: 'Alert',
buttons: {
main: {
label: 'OK',
className: 'blue'
}
}
});
return false;
}
}
});
});
</script>
in this script window.location = "http://www.example.com"; is not working.
But I check alert message it is working fine. why its not working in if condition.
I need to redirect page when each function was completed.
please any one help me:-((((((((((((((((((((((((((((
Try this.,
window.location.href = 'http://www.google.com';
This may work for you.
Window.location.href and Window.open () methods in JavaScript
jQuery is not necessary, and window.location.replace(url) will best simulate an HTTP redirect.
still you want to do this with jQuery use this $(location).attr('href', 'url')
If I got your question correct, you want to redirect the user when all your ajax requests, within your each function, are completed. For this, you can create an array that will hold the success status of each ajax request, and depending on this array you may do your redirection task.
Add below few snippets to your existing code:
In your #btnSubmit click function (Though, I recommend you use .on() delegation method)
var ajax_succ_arr = []; // success status container
var this_ajax_succ = false; // flag
In you success function of both ajax calls (within your each function).
if(c_data == ""){
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
} else {
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
}
And finally your redirection. Put this just after each function ends.
if(ajax_succ_arr.indexOf(false)<0){ // if all statuses are ok
window.location="http://www.example.com";
}
Hope this helps.
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I am trying to save the reponse of an AJax() call in a javascript variable but this variable returns empty when I append the value to a div .
here is my script code
<script>
/*<![CDATA[*/
$(document).ready(function(){
$("#abusoForm #enviar").livequery("click",function(e){e.preventDefault();
console.log("Click is working");
var hidden = $('#mensajeAbuso').val();
var category = $('#opcmarcar').val();
var name=$('#nombre').val();
var phone=$('#telefono').val();
var mail=$('#email').val();
var cf_mail=$('#confirma_email').val();
var k="<?php echo $this->config->defaultLanguage?>";
var url="somedomain.com/index.php?param=value";
//url = 'proxy.php?url='+url;
var otro = $('#otro_email').val();
var E=$("#abusoForm #enviar").val();
var alto_height = $(window).height();
alto_height = alto_height/4;
//Ajax call happening here
var vajx =$.ajax({url:url,type:"POST",data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false}}).responseText;
//Now I have to use the variable vajx to post a message about the submition of the form ;
if(vajx!=""){
$("div.error_mensajeria").css("display","none");
$(".appendcontentAbuso").html(vajx);
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}
})
});
/*]]>*/</script>
As you can see in the above image I am getting the response in the console . But when i try to save the response in the var vajx like mentioned in the script above its empty may I know why .
I am very new to Ajax() so need help
UPDATE
After looking into some examples given below and trying my own here is how I could fix it .
Answer
<script>
/*<![CDATA[*/
$(document).ready(function(){
$("#abusoForm #enviar").livequery("click",function(e){e.preventDefault();
console.log("Click is working");
var hidden = $('#mensajeAbuso').val();
var category = $('#opcmarcar').val();
var name=$('#nombre').val();
var phone=$('#telefono').val();
var mail=$('#email').val();
var cf_mail=$('#confirma_email').val();
var k="<?php echo $this->config->defaultLanguage?>";
var url="http://wstation.inmotico.com/index.php?page=avisoajax&type=spam&im_action=reportAbuse&im_core=showAds";
//url = 'proxy.php?url='+url;
var otro = $('#otro_email').val();
var E=$("#abusoForm #enviar").val();
var alto_height = $(window).height();
alto_height = alto_height/4;
//Ajax call happening here
//var vajx =$.ajax({url:url,type:"POST",data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false}}).responseText;
var result = ''; // declare a var here
var vajx = $.ajax({
url: url,
type: "POST",
data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false},
success: function(data){
$(".appendcontentAbuso").html(data); // <-----------change here
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}
});
/*vajx.done(function (data) {
result = data; // <-----------change here
});
if(result != ""){ // <---------------change here
// $("div.error_mensajeria").css("display","none");
$(".appendcontentAbuso").html(result); // <-----------change here
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}*/
console.log(data);
//$('#ajxResponse').html(vajx);
})
});
/*]]>*/</script>
Please notice that now I am initiating the popup inside the success: function
Thank you in advance
var vajx;
$.ajax({
url: url,
type:"POST",
data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E,async:false}
)
.done(function( data ) {
vajx = data;
}
});
Try this:
//Ajax call happening here
var result = ''; // declare a var here
var vajx = $.ajax({
url: url,
type: "POST",
data: {
'h': hidden,
.....
async: false
}
});
vajx.done(function (data) {
result = data; // <-----------change here
});
if(result != ""){ // <---------------change here
$("div.error_mensajeria").css("display","none");
$(".appendcontentAbuso").html(result); // <-----------change here
$('#mDialogAbuso').css("height",alto_height);
$("#mDialogAbuso").popup();
$("#mDialogAbuso").popup("open");
}
and then you can change your if check little bit like this:
$.ajax has a success handler which handles the response received from the server. So you could do something like this:
$.ajax({
url:url,
type:"POST",
data:{ 'h':hidden,'c': category,'n':name,'p':phone ,'m':mail,'cm':cf_mail,'otro1':otro,"enviar":E},
async:false,
success:function(ret)
{
//the response received from url will be stored in "ret"
var vajx = ret;
// use your conditions here now
}
});
I am new to AJAX. Recently, I read a block of code that set url to the function itself. In this case, it is get Path. Normally, we will set url to other pages to get data or something. I do not know what it means to set url to the calling function itself. Could you help answer my question?
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
$.ajax({
type: "POST",
url: "getPath",
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>
function getPath() <-- function
url: "getPath", <-- string
They are not related. Only thing in common is the developer had the same name. The page will post to some location called getPath on the server.
It doesn't mean anything other than the fact that the url the POST request is being sent to happens to be "getPath". The function is probably named according to the route name on the server side, but renaming that function (and updating every place it is called accordingly) would have no effect, and you would have to leave the url: "getPath" as is. Changing that part would likely break something.
That getPath would be a relative url, so the request goes to something like: http://example.com/path/to/parent/of/current/page/getPath
suppose your HTML input URL
<input type="url" id="web_url" value=""></input>
Then you can get your URL
<script type="text/javascript">
function getPath()
{
var startLat = $('#startLat').val();
var startLng = $('#startLng').val();
var desLat = $('#desLat').val();
var desLng = $('#desLng').val();
var departure = $('#departure').val();
var url = $('#web_url').val(); // getting input URL by User
$.ajax({
type: "POST",
url:url ,
dataType: "json",
data: { "startLat": startLat, "startLng": startLng, "desLat": desLat, "desLng": desLng, "departure": departure},
success: function (response) {
if(response.success) {
$('#result').val(response.data);
console.log('Reponse.success is true');
}
else {
console.log('Response.success is false');
}
},
error: function(e) {
}
});
}
</script>
Ok, simple thing in javascript that I could not solve even searching on the web. I guess I even found the right thing but could not put on the right place.
This code tells me if a stream is online or offline. But how do I do to the status and keep updating every 5 seconds?
$(function () {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else {
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
});
Example :
var myAjaxCall = function() {
$.ajax({
type: "GET",
url: options.feedUrl,
dataType: "xml",
async:options.sync,
success: function(xml) {
// todo
}
};
var ResInterval = window.setInterval(myAjaxCall, 60000); // 60 seconds
To Stop:
window.clearInterval(ResInterval);
use set time out function
setTimeout(function(){
//your function
foo();
},1000);
Try this out:
function checkStatus() {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else{
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
}
$(function() {
setInterval(checkStatus, 5000);
});
This calls the function checkStatus every 5000 milliseconds (5 seconds).