Jquery Ajax call doesn't work fine in IE8 - javascript

I'm loading some data lively from the database and each row have some links that do some things over that.
They work flawlessly except for the last one I've implemented which seems not to be working on IE
$('.lockFile').click(function(){
var url = "functions/lock_call.php";
var unlock = 'assets/lock-unlock.png';
var lock = 'assets/lock.png';
var action = 'unlock';
var id = $(this).parent().parent().attr('id');
var image = $(this).children(0);
if (image.attr('src') == unlock)
action = 'lock';
var data = 'id='+id+'&action='+action;
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
success: function(){
alert (action);
if (action == 'lock')
image.attr('src', lock);
else
image.attr('src', unlock);
}
});
return false;
});
What could be wrong?
The alert is performer on "success" but nothing is made. That is, the script doesn't run.

IE 8 has some amazing variables reserved, try this one
$('.lockFile').click(function(){
var Aurl = "functions/lock_call.php";
var AunAlock = 'assets/lock-unlock.png';
var Alock = 'assets/lock.png';
var Aaction = 'AunAlock';
var Aid = $(this).parent().parent().attr('id');
var Aimage = $(this).children(0);
if (image.attr('src') == AunAlock)
Aaction = 'Alock';
var data = 'id='+Aid+'&action='+Aaction;
$.ajax({
type: "POST",
url: Aurl,
data: data,
cache: false,
success: function(){
alert (Aaction);
if (Aaction == 'lock')
Aimage.attr('src', Alock);
else
Aimage.attr('src', AunAlock);
}
});
return false;
});

try to declare data in JSON format
var data = {'id':id, 'action': action}

Related

Need to be able to run an ajax call with element loaded after document.ready()

I've got checkbox inputs on a page and am filtering the results using ajax.
One search option is type and the vendors option updates depending on the type selected. But this means that the change function used to update the actual results no longer works within the document.ready(). To rectify this, I also call the function within .ajaxComplete().
But as an ajax call is being called within the ajaxComplete(), it is causing an infinite loop and crashing the site.
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
How do I get the .change function to still work after the input checkbox has been called via ajax previously and without causing a loop with .ajaxComplete() ?
Any help would be greatly appreciated.
Thanks
Please try by change function as follow :
$(document.body).on("change",'input[type=radio]',function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});

page redirect is not working in jquery

<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.

Close the Chrome Extension automatically

I am trying to close the extension automatically after saving my data.
Here is the code which is used to save the data:
$(function(){
function displayMessage(string){
alert(string);
}
var submit = $('#submit');
$('#create').submit(function(){
$('#loading_image').html('<img src="images/wait.gif">');
var user_email = localStorage.getItem('email');
var api = localStorage.getItem("user_api_key");
var auth = "apikey" +' ' +(user_email+":"+api);
var favicon_key = localStorage.getItem("favicon_image_key");
var peoples = [];
var tags_peoples = $("#s2id_people .select2-choices .select2-search-choice");
for (i=0; i<tags_peoples.length; i++) {
peoples.push({"label": tags_peoples[i].childNodes[1].textContent})
}
var subjects = [];
var tags_subjects = $("#s2id_subjects .select2-choices .select2-search-choice");
for (i=0; i<tags_subjects.length;i++) {
subjects.push({"label": tags_subjects[i].childNodes[1].textContent})
}
var places = [];
var tags_places = $("#s2id_places .select2-choices .select2-search-choice");
for (i=0; i<tags_places.length; i++) {
places.push({"label": tags_places[i].childNodes[1].textContent})
}
var begin = $(".daterangepicker_start_input")[0].childNodes[1].value;
var end = $(".daterangepicker_end_input")[0].childNodes[1].value;
var data = {
'content': $('#title').val(),
'people': peoples,
'subjects': subjects,
'begin_date': begin,
'end_date': end,
'places': places
}
$.ajax({
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
url: "https://my_site_url/api/v3/data/",
dataType: "json",
data: JSON.stringify(data),
contentType: "application/json",
success: function(data) {
$('#loading_image').hide();
window.location.href = 'saved.html';
setTimeout(function(){
window.close();
}, 2000);
},
error: function(data) {
$('#div1').text("Error on saving the data");
$('#loading_image').hide();
},
complete: function() {
submit.removeAttr('disabled').text('Save');
}
});
return false;
});
});
I am using this to close the extension
setTimeout(function(){window.close();}, 3000);
But this doesn't work. Should I write any EventListener to close the extension automatically?
Appreciated the answers
Consider this snippet from your code:
window.location.href = 'saved.html';
setTimeout(function(){
window.close();
}, 2000);
This will not work. As soon as you change location, the page starts to navigate away, eventually wiping the window state and all timeouts set when the new page loads.
You need to set the timeout from saved.html for this to work.

ajax not working on mobile site

Hi everyone I have a script that has an ajax call within it.
$(document.body).on('click', '#postAppt', function (e) {
var serviceSelected = $("#selectServ option:selected").val();
var location = $('input[name="location"]:checked').val();
var price = $("#sessionPrice").val();
var date = $("#apptDate").val().replace(/\-/g, '');
var time = $("#time option:selected").val();
if(!$('input[name="location"]:checked').val()){
alert("Please select a location!");
return false;
}else{
$("#schedulePhaseOne").hide();
$("#schedulePhaseTwo").show();
$("#goBackSP").show();
var userid = $('div[id^="prfSchedule"').attr("id").replace("#", "").replace("prfSchedule","");
$.ajax({
type: "POST",
url: "../users/functions.php?id=" + userid,
data: {getServDetails: serviceSelected},
cache: false,
success: function(result){
alert("success");
}
});
}
return false;
});
the ajax call only seems to work on desktop devices and not on mobile. I've been conflicted for a couple of hours now. Any suggestions? Also i want to load the contents (which are html) into a bootstrap modal. Could this also be a problem?
I think it's the problem of cross-domain.

Trying to save the response of AJAX() call to a variable but that variable returns empty string [duplicate]

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
}
});

Categories

Resources