Not refreshing data each time - javascript

I have weired problem in my project.I have 2 tabs and in one tab i have chekboxes and submit button and user will select from checkboxes and on button click he will get what he has selected from checkboxes in another tab.It runs perfectly.But sometimes it does not refresh the data from ajax ,jquery and i have to complete refresh my page.I am not able to identify the problem as i am not getting any error. Atleast i have to click for more than 15 times then it will not refresh the data otherwise it works fine.
Here is my js code:
function getFahrzeuge() {
var opts = [];
$("#fahrzeuge input[type='checkbox']").each(function () {
if ($(this).is(':checked'))
{
opts.push($(this).attr("id"));
}
});
return opts;
}
function saveFahrzeugeWidget(opts){
if(opts.length == 0) return false;
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {'filterOpts' :opts, 'aktion' : 'save-widget-vehicle'},
success: function(data){
//getFahrzeugeWidget();
$('#fahrzeuge').html(data['html']);
},
error: function(data){
console.log(data);
}
});
}
function getFahrzeugeWidget(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts:opts, 'aktion' : 'get-widget-vehicle'},
success: function(data){
$('#fahrzeuge').html(data.html);
},
error: function(data){
console.log(data);
}
});
}
function getFahrzeugeWidgetEdit(opts){
if(!opts || !opts.length){
opts = allFahrzeuge;
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {filterOpts:opts, 'aktion' : 'get-widget-vehicle-edit'},
success: function(data){
$('#fahrzeuge').html(data.html);
},
error: function(data){
alert('error' + data);
}
});
}
$('#fahrzeuge .butt-rahmen').live('click', function(){
var opts = getFahrzeuge();
if($(this).attr('id') == 'saveId')
{
saveFahrzeugeWidget(opts);
if($('#fahrzeuge input[type="checkbox"]:checked').length <=0) {
alert('überprüfen Sie bitte atleast ein fahrzeuge');
//getFahrzeugeWidgetEdit(opts);
}
}
});

The answer is getting cached. And you are receiving the same answer. Try to add a new parameter to data as timestamp.
So your data should look like this.
data: {'filterOpts' :opts, 'aktion' : 'save-widget-vehicle', 'timestamp': new Date().getTime()},

Related

cart data not update in shopify using ajax

I have a Problem in Shopify.
I want update cart quantity on button click using ajax but it will give error like
{"status":404,"message":"Cart Error","description":"Cannot find variant"}
Here is my ajax code,
$('.adjust-plus').click(function(){
var qty = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').val();
var varient = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').attr('data-id');
jQuery.ajax({
type: 'POST',
async: false,
url: '/cart/update.js',
data: { updates: { varient : qty } },
dataType: 'json',
success: function() { location.href = '/cart'; }
});
});
currently in both variable value come so no any error in value.
but when id add code like:
$('.adjust-plus').click(function(){
var qty = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').val();
var varient = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity').attr('data-id');
jQuery.ajax({
type: 'POST',
async: false,
url: '/cart/update.js',
data: { updates: { 15082896588867 : 2 } },
dataType: 'json',
success: function() { location.href = '/cart'; }
});
});
then cart updated successfully.
Firstly, remove async: false as it's very bad practice and not needed here as you're using the success callback properly.
The issue itself is because you cannot use variables as the keys of an object with the syntax you're using. To get around this you can use bracket notation, like this:
$('.adjust-plus').click(function() {
var $quantity = $(this).parent('.button-wrapper').siblings('.input-wrapper').children('.quantity');
var qty = $quantity.val();
var varient = $quantity.data('id');
var data = { updates: {} };
data.updates[varient] = qty;
jQuery.ajax({
type: 'POST',
url: '/cart/update.js',
data: data,
dataType: 'json',
success: function() {
location.href = '/cart';
}
});
});

Getting data back from database as undefined in html but defined in the console

I am creating a slim project using CRUD. I am trying to get 1 user, by using GET. When I use .append it returns data like this: the name is the request getting data from the database.
undefined
name
undefined
name
Obviously I only want one user to be shown, however when I add .html instead of .append it just comes back undefined.
This is my code that is coming back undefined
$(document).ready(function showStaff(processResponse) {
$.ajax({
type: 'GET',
dataType: "json",
url: "borrower.php/borrowers",
success: showAllBorrowers,
error: showError
});
});
//shows borrowers in HTML
function showAllBorrowers(responsedata){
$.each(responsedata.borrower,function(index,borrower){
$("#borrower_list").append("<li type='square'> Borrower Id:"+borrower.borrower_id+",FullName:"+borrower.first_name+" "+borrower.last_name+", Email:"+borrower.email);
$("#borrower_list").append("</li>");
});
}
$(document).ready(function(){
$("#btnSaveBorrower").click(function(){
var borrower=new Borrower($("#firstName_add").val(),
$("#lastName_add").val(),$("#email_add").val());
$.ajax({
type: 'POST',
dataType: "json",
url: "borrower.php/borrowers",
data:JSON.stringify(borrower),
success:function(data){
console.log(data)
location.reload();
},
});
});
});
function Borrower(firstName, lastName, email){
this.firstname=firstName;
this.lastname=lastName;
this.email=email;
}
$("#btnSearch").click(function(){
var id = $("#StaffBorrower_Id").val();
$( "#update" ).show();
$( ".delete" ).show();
$("#btnUpdateBorrower").show();
$("#btnDeleteBorrower").show();
$.ajax({
type: 'GET',
dataType: "json",
url: "borrower.php/borrowers/" + id,
success: showResponse,
error: showError
});
});
function showResponse(responsedata){
var item = $("<li>"); item.text("Borrower Id:"+responsedata.borrower_id+",FullName:" +responsedata.first_name+" "+responsedata.last_name+", Email:"+ responsedata.email);
$("#search_borrower").html(item);
item.attr("type", "square");
item.attr("data-delete-id", responsedata.borrower_id); item.attr("data-update-id", responsedata.borrower_id);
console.dir(responsedata);
}
$("#btnDeleteBorrower").click(function(){
var result = confirm("Are you sure you want to delete?");
if (result) {
var staff= delete Borrower($("#borrower_Id").val(), $("#firstName").val(), $("#lastName").val(), $("#email").val());
$.ajax({
type: 'DELETE',
dataType: "json",
url: "borrower.php/borrowers/"+$("[data-delete-id]").data("delete-id"),
success: function(res){
console.log(res);
location.reload();
},
error: showError
});
}
});
$("#btnUpdateBorrower").click(function(){
var result = confirm("Are you sure you want to update?");
if (result) {
var borrower = new Borrower ($("#firstName").val(),
$("#lastName").val(),
$("#email").val());
$.ajax({
type:'PUT',
dataType:"json",
url:"borrower.php/borrowers/"+$("[data-update-id]").data("update-id"),
data:JSON.stringify(borrower),
success:function(data){
console.log(data);
location.reload();
},
error: function(){
console.log("There seems to be an error")
}
});
}
});
The console log is working, I am getting the data in the console but it isn't being returned in the html for some reason. Does anyone have any ideas why? Thanks

Jquery Ajax working on localhost (xammp) but not working on Server (cpanel)?

Jquery Ajax working fine on localhost (xammp) but not working on Server (cpanel) !
also ajax with Javascript working fine , but throught JQuery it has problem ! (on server)
i changed send method to POST but problem same.
this is my website :
concert20.ir
an this is js code:
var arr=[];
function func1(id,status){
var str;
var a=id.split('-');
// a[0] = chair number
// a[1] = singer id
// a[2] = place
length=arr.length;
if(status=='رزور شده')
{
// check that who resereved it?
var index=jQuery.inArray(parseInt(a[0]), arr);
if(index>=0)
{
// unreserved ...
//arr[index]=-1;
arr.splice(index, 1);
length=arr.length;
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({reservefunc:0,chairnum:a[0],singerid:a[1],place:a[2]}),
success: function(result){
$("#drawtable").html(result);
}
});
if(length==0)
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:0,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
else
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:1,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
}
}
else if(status=='قابل خرید')
{
// reserve ...
arr.push(parseInt(a[0]));
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({reservefunc:1,chairnum:a[0],singerid:a[1],place:a[2]}),
success: function(result){
$("#drawtable").html(result);
}
});
sts=$("input#checksts").val();
if(sts==-1)
{
var index=jQuery.inArray(parseInt(a[0]), arr);
arr.splice(index, 1);
alert('این صندلی قبلا خریداری شده است');
}
length=arr.length;
if(length==0)
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:0,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
else
{
$.ajax({
url: 'ServerReply.php',
type: "GET",
data: ({showdetails:1,chairnum:arr,singerid:a[1],place:a[2]}),
success: function(result){
$("#card").html(result);
}
});
}
}
}
UPDATE
i found the problem!
the server was context-sensitive and i did not observe it
i changed ServerReply.php to serverReply.php and it worked fine ...
try to write absolute url save to versions of ulr in var and comment , un comment respectively
var mainurl = "http://localhost/project/serverReply.php"
var mainurl = "http://xeample.com/project/serverReply.php"
try if it can solve the problem
Try this:
$.ajax({
type : "GET",
url : "ServerReply.php",
cache : false,
async : true,
global : false,
data : {
"showdetails":0,
"chairnum":arr
}
}).done(function(msg) {
//Do something
});

Run Javascript function as long as condition is true

I'm building a PhoneGap app where user press button which then sends data to server. On the success handler I have a new function that asks user some questions with prompt box and then sends them back to server. So I need to make the prompt box appear as long as the condition "status=ok" is true.
I don't know how many times the prompt box has to appear, it can be anything from 1 to 10 times, so I guess I need to make a some sort of loop, but how can I do it?
This is the code I've been using now:
function UpdateRecord(update_id)
{ var id = getUrlVars()["id"];
jQuery.ajax({ type: "POST",
url: serviceURL + "update.php",
data: 'id='+id ,
cache: false,
success: function(data) {
console.log(data)
if(data.key[0].status == "ok"){
var reply = prompt(data.key[0].QUESTION, "");
jQuery.ajax({ type: "POST",
url: serviceURL + "question.php",
data: 'id='+id+'&reply='+reply ,
cache: false,
success: function(data) {
window.location = "page.html" }
} else {
window.location = "page.html"
}
}
});
}
I think what your after is moving the response from the AJAX call into a method AskQuestion (or whatever you want to call it). This function would prompt and would query if the answer was correct or not and redirect them to another page:
function AskQuestion(data)
{
var id = getUrlVars()["id"];
console.log(data);
if(data.key[0].status == "ok") {
var reply = prompt(data.key[0].QUESTION, "");
jQuery.ajax({ type: "POST",
url: serviceURL + "question.php",
data: 'id='+id+'&reply='+reply,
cache: false,
success: AskQuestion});
} else {
window.location = "page.html";
}
}
function UpdateRecord(update_id)
{
var id = getUrlVars()["id"];
jQuery.ajax({ type: "POST",
url: serviceURL + "update.php",
data: 'id='+id,
cache: false,
success: AskQuestion});
}

Ajax on success of another ajax doesn't work in ie

I do an ajax call to get a list of all elements, say Products and populate them in a table with checkboxes. Then I make another ajax call to get which products were already selected and select them. This works in all browsers except ie. Am I doing something wrong?
$.ajax({
url : "${product_category_url}",
data : {"orgID":"${globalOrganisation.id}"},
dataType : "html",
statusCode: {
401: function() {
$('.ui-tabs-panel:visible').html("${ajax_session_expired}");
}
},
success : function(data) {
$("#productCategoryContainer").html(data);
$.ajax({
url: "${get_taggedProd_url}",
data: {"questionnaireId":_questionnaireId},
dataType: "json",
success: function(data){
var productIds = data.products;
$.each(productIds,function(index,value){
var obj = $('input[name="'+value+'"]');
obj[0].checked = true
selectRow(obj[0]);
});
}
});
}
});
This is due to caching by IE.
Please try this
$.ajax({
url : "${product_category_url}",
data : {"orgID":"${globalOrganisation.id}"},
dataType : "html",
statusCode: {
401: function() {
$('.ui-tabs-panel:visible').html("${ajax_session_expired}");
}
},
success : function(data) {
$("#productCategoryContainer").html(data);
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
$.ajax({
url: "${get_taggedProd_url}",
data: {"questionnaireId":_questionnaireId},
dataType: "json",
success: function(data){
var productIds = data.products;
$.each(productIds,function(index,value){
var obj = $('input[name="'+value+'"]');
obj[0].checked = true
selectRow(obj[0]);
});
}
});
}
});
and if you need more details please look into this
The thing in this code that always screws me up is trying to get the check box selected. Make sure obj[0].checked = true actually works.

Categories