jquery array push not working properly inside ajax success - ajax

I am trying to push a div id into an array.Array push is working good bofore ajax call.But when i use push inside ajax success first push is taken place when i click on the second element.that is
array operation when with below code( array push inside success)
first click on id="1" --- resuting array []
second click on id="2" --- resulting array [1]
second click on id="3" --- resulting array [1,2]
my code
$(document).ready(function() {
var count = 0;
var vPool = '';
arr = [];
seat = [];
var totalseat = '<?php echo $sumofseat; ?>';
var date = ' <?php echo $new_date; ?>';
$('.custom_checkbox').click(function() {
pressed = true;
var prev = $(this).attr('class');
var arrid = $(this).attr('id');
var seats = $(this).attr('title');
count = $('.selected').length;
if (prev == 'custom_checkbox') {
//arr.push(arrid);
//seat.push(seats);
$.ajax({
url: "seat_manipulation.php",
dataType: 'json',
data: '&operation=save&seat=' + arrid + '&guid=<?php echo $guid; ?>&date=' + date,
type: "POST",
context: this,
success: function(data) {
if (data.status == 'SAVED') {
$(this).toggleClass('selected');
$('#count').slideDown();
$('#selecte_seat').show();
$('#count').html(count + ' Seats selected');
alert(arrid);
//if(jQuery.inArray(arrid,arr) == -1) {
arr.push(arrid);
//}
//if(jQuery.inArray(seats,seat) == -1) {
seat.push(seats);
//}
} else {
alert("Seat already been used.Please select another");
}
}
})
}
});
});
am i wrong..or this is how its suposed to work ?? Thanks in advance

You need to configure you're Ajax with "async:false" ,because there is a Race Condition thing ,so block the code while you're manipulating Array's.
Se this question.

The AJAX call you are making is asynchronous (by definition...), meaning that the actual function you are defining in $('.custom_checkbox').click is already finished before the success function is called...
When you click on the next div (e.g. div 2) then the success function of the first click may or may not have already been called...
Could this be the problem?

Related

Materialize autocomplete : Why AJAX called before entering any character?

I'm using autocomplete with materialize and i'm retrieving the data with ajax call, it works fine but when i want to call ajax only after entering caracters(using onkeyup event), the drop down list will not be showing correctly !!!!
Before i forget please help me to show a "NOT FOUND" in the drop down list if no data founded (because my else condition doesn't work). here is my code and thanks a lot in advance :
$(document).ready(function() {
var contents = $('#autocomplete-input')[0];
contents.onkeyup = function (e) {
$.ajax({
type: 'GET',
url: Routing.generate('crm_search_lead', {"search":
$(this).val()}),
success: function (response) {
var contacts = {};
if (true === response.success) {
var result = response.result;
for (var i = 0; i < result.length; i++) {
var lastName = result[i].lastName ?
result[i].lastName : '';
var firstName = result[i].firstName ?
result[i].firstName : '';
contacts[lastName + " " + firstName] = null;
}
$('input.autocomplete').autocomplete({
data: contacts,
minLength: 2,
});
} else {
$('input.autocomplete').autocomplete({
data: {
"NOT FOUND": null
}
});
}
}
});
}
});
Hi people :) i resolve it by changing onkeyup() with focus() and it's totally logical because with onkeyup() the droplist will appear and disappear very quickly on every key entered.

how to update one drop down list depending to another one

I have 2 drop down lists ,
firstly i used on load to fill the first list , and i didn't face proplems on it.
but when the first list's value change , i want to fill the second list depending on the new value.
but however i changed the options of the first list , the second list is still empty, what is the proplem in my code ?
in html file
<script>
$(document).ready(function() {
$('#select1').change(function(){
$.ajax({
type: 'GET',
url: 'SubmitHomework.php',
data: 'q='+$('#select1').val(),
success: function(msg[])
{ for(var i=0 ; i<msg.length ; i++)
$('#select2').append(msg[i]); }
});
});
});
</script>
in php file(fill the second drop down list part)
$connected = mysqli_connect("localhost", "root", "", "web");
$q = $_GET['q'];
if($q != "")
{
$sql2 = "SELECT homeworkTitle, homeworkID FROM homework, hwcourse WHERE cTitle='csc212' AND hwID = homeworkID";
$result2 = mysqli_query($connected,$sql2);
while ($row3 = mysqli_fetch_array($result2))
{ $array1[]= "<option value='$row3[homeworkID]'> $row3[homeworkTitle] </option>"; }
return $array1; }

JQueryMobile: page with data (from ajax) doesn't change

function returnQueryResultJson(url,callback) {
return $.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(response) {
callback(response);
}
});
}
function showCategory(url,hash, options) {
var cat = hash.replace(/.*category=/, "");
if (cat == '#page1') {
cat = '';
}
var a = returnQueryResultJson('http://www.placetowebservice.nl/categories.php?category=' + cat,function(res) {
var
category = res,
pageSelector = hash.replace(/\?.*$/, ""),
$page = $(pageSelector),
$header = $page.children(":jqmData(role=header)"),
$content = $page.children(":jqmData(role=content)"),
markup = '<ul data-role="listview" data-theme="c" data-dividertheme="b">';
var cItems = category;
var headername = category.name;
var numItems = cItems.length;
if (cat == '') {
markup = '<ul data-role="listview" data-theme="c" data-dividertheme="b" style="min-height:100%;">';
}
for (var i=0;i<numItems;i++) {
markup += '<li><h3>' + cItems[i].title + '</h3><p>' + cItems[i].description + '</p></li>';
}
markup += "</ul>";
$header.find("h1").html(headername);
$content.html(markup);
$page.page();
$content.find(":jqmData(role=listview)").listview();
options.dataUrl = url;
options.changeHash = true;
options.reloadPage = true;
console.log($page);
$.mobile.changePage($page, options);
//}
});
}
$(document).bind("pagebeforechange", function(e,data) {
if (typeof data.toPage === "string") {
var
uz = $.mobile.path.parseUrl(data.toPage),
re = /^#category-item/,
re2 = /^#page1/
;
if (uz.hash.search(re) !== -1 || uz.hash.search(re2) !== -1) {
showCategory(uz.href,uz.hash,data.options);
e.preventDefault();
}
}
});
I have got this code, and it works pretty good (first time). I first load a page with:
$(document).ready(function(){
$.mobile.changePage('index.html#page1',{ dataUrl: "index.html#page1?category=", transition: "fade" });
});
It works, it loads the ajax-data in the page with id="page1".
Then I click on a link (category 1) and it shows the second page (with id="category-item") and fills it with the right data (category 1: sub 1, category 1: sub 2). Then I go back and it shows the categories again.
Now the problem appears, when I click on the next category (category 2). When I go to that page, it gives the right data from ajax (I used console.log to check this), but the data on the screen remains the data from category 1.
So the content from the first category you click on remains, even though you afterwards went to another category. It will remain showing the category you first clicked on.
What am I doing wrong?
It worked When I did this:
$page.page();
$page.trigger('create'); // added this one
$content.find(":jqmData(role=listview)").listview();
$content.find(":jqmData(role=listview)").listview("refresh"); // added this one

AJAX loop for WordPress (posts from different categories)

I try to implement AJAX posts loop for WordPress from Tuts+
I want this loop to show under comments form in single post page in three columns (each for another category)
In single.php I have divs (numbers comes from category):
<div class="news_posts-6"></div>
<div class="news_posts-3"></div>
<div class="news_posts-2"></div>
My ajaxLoop:
jQuery(function($){
var page = 1;
var loading = true;
var $window = $(window);
var cat = [6,3,2];
var load_posts= jQuery.each(cat, function(){
var $content = $(".news_posts-" + this);
$.ajax({
type : "GET",
data : {numPosts: 2, pageNumber: page, cat: this},
dataType : "html",
url : "http://127.0.0.1:4001/wordpress/wp-content/themes/twentyeleven-child-theme/loopHandler.php",
beforeSend : function(){
if(page != 1){
$content.append('<div id="temp_load" style="text-align:center">\
<img src="/images/ajax-loader.gif" />\
</div>');
}
},
success : function(data){
$data = $(data);
if($data.length){
$data.hide();
$content.append($data);
$data.fadeIn(500, function(){
$("#temp_load").remove();
loading = false;
});
} else {
$("#temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
$window.scroll(function() {
var content_offset = $content.offset();
console.log(content_offset.top);
if(!loading && ($window.scrollTop() +
$window.height()) > ($content.scrollTop() + $content.height() + content_offset.top)) {
loading = true;
page++;
load_posts();
}
});
load_posts();
});
Part of loopHandler.php:
$numPosts = (isset($_GET['numPosts'])) ? $_GET['numPosts'] : 0;
$page = (isset($_GET['pageNumber'])) ? $_GET['pageNumber'] : 0;
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : 0;
echo $numPosts;
echo $page;
query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'cat' => $cat
));
I tried use simple array containing categories numbers but it doesn't work. Depends on
data : {numPosts: X, pageNumber: page, cat: this},
there is X post displaying in each column (same posts from first category).
I guess I need to use JSON, which I tried, but it was total disaster (I don't know how to put it together). I just need to call AJAX for three different arguments.
Thanks for any help
Well, there are various ways you can go about this.
One way is looping over your categories client side first, and make separate request per category. This is what you are essentially doing in your code. You are iterating over an array of categories and making a request for each.
Another way is to pass that array of categories to your handler. All you need to do is modify your handler to accept an array of integers or categories. Then you can return a JSON object. But this involves a lot more editing and on top of that it does not solve the issue of having different sizes and heights for each section.
Thus, below, I have modified the code a little bit to also keep track of multiple sections. There are just a few small edits we need:
Each section needs to have a category number, pagination number, content section, and a flag whether its loading or not. Each needs to be stored in a single list for tracking.
We need to iterate over each category to initialize it.
We need to iterate over each category on window scroll and check if the next item should be loaded
We need to make sure that each request relates to the requested category
Start by modifying your divs a little (this is just a matter of preference, i prefer storing metadata like this in an attribute instead of a class):
<div class="news_posts" data-category="6"></div>
<div class="news_posts" data-category="3"></div>
<div class="news_posts" data-category="2"></div>
Here's a modified JS (please be aware that I changed up some variable and function names):
jQuery(function($){
var $window = $(window);
var cats = [];
var contentDivs = $(".news_posts");
var initializeCats = function(){
// adds category objects to a list for tracking
for(var i = 0; i < contentDivs.length; i++){
var catNum = $(contentDivs[i]).attr("data-category");
var cat = {
catNum : catNum,
catPage : 1,
loading : true,
catDiv : $(contentDivs[i]);
};
cats.push(cat);
load_post(cat);
}
};
var load_post = function(cat) {
$.ajax({
type : "GET",
data : {
numPosts : 2,
pageNumber : cat.catPage,
cat : cat.catNum
},
dataType : "html",
url : "http://127.0.0.1:4001/wordpress/wp-content/themes/twentyeleven-child-theme/loopHandler.php",
beforeSend : function(){
if(page != 1){
// this was a bad idea when i wrote the article originally
// never concatenate strings on multiple lines by escaping
// the carriage return
// $content.append('<div id="temp_load" style="text-align:center">\
// <img src="/images/ajax-loader.gif" />\
// </div>');
cat.catDiv.append("<div class='temp_load' style='text-align:center'>" +
"<img src='/images/ajax-loader.gif' />" +
"</div>");
}
},
success : function(data){
$data = $(data);
if($data.length){
$data.hide();
cat.catDiv.append($data);
$data.fadeIn(500, function(){
cat.catDiv.find(".temp_load").remove();
cat.loading = false;
});
} else {
cat.catDiv.find(".temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
cat.catDiv.find(".temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
var onWindowScroll = function(){
for(var i = 0; i < cats.length; i++){
var cat = cats[i];
var contentDiv = cat.catDiv;
var content_offset = contentDiv.offset();
if( !cat.loading &&
($window.scrollTop() + $window.height()) >
(contentDiv.scrollTop() + contentDiv.outerHeight() + content_offset.top)
) {
cat.loading = true;
cat.catPage++;
load_post(cat);
}
}
}
initializeCats();
$window.scroll(onWindowScroll);
});
The PHP file is pretty much the same, just comment out the echo $numPosts line:
$numPosts = (isset($_GET['numPosts'])) ? $_GET['numPosts'] : 0;
$page = (isset($_GET['pageNumber'])) ? $_GET['pageNumber'] : 0;
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : 0;
// echo $numPosts;
echo $page;
query_posts(array(
'posts_per_page' => $numPosts,
'paged' => $page,
'cat' => $cat
));
This is just something quick I whipped up. I HAVE NOT TESTED IT. Try it out, watch out for syntax errors, and cross your fingers :). I hope this will work for you and if it does not, we can look into modifying it so that it does.

listview('refresh') not working

In my application listView('refresh') doesn't work. Here is my code
I create listView dynamically
var str = "<ul data-role='listview' data-inset='true' id='mylist'>";
for(var i = 0; i<data.length; i++ ){
str += "<li>"+data[i].note.text+"</li>";
}
str += "</ul>"
$('#content').append(str);
function addnote(){
var note_text = $('#note_text').val();
var note_lat = $('#lat').val();
var note_lng = $('#lng').val();
$.ajax({
type: "POST",
beforeSend: function (jqXHR) {
jqXHR.setRequestHeader(KEY1, _key1);
jqXHR.setRequestHeader(KEY2, _key2);
},
url:SERVER_URL+"api/addNotes/",
data: {type: 'text',note_text: note_text, note_lat: note_lat , note_lng: note_lng},
success: function(data, textStatus, jqXHR) {
if (data.status == "ok"){
$.mobile.changePage("file:///android_asset/www/index.html?"+_key1+"|"+_key2+"|");
}
else{
alert("Something wrong");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error=" + errorThrown);
},
complete: function() {
$('#mylist').listview('refresh');
}
});
}
I read many reports and forums there said I have to call listview('refresh') in ajax's complete function. But in my code it doesn't work, could anyone tell me what is the problem here?
Refresh is for when you are adding elements to an existing, enhanced listview. If you are creating the entire listview dynamically you need to trigger a "create" on the parent div.
So if you had <div id="container><ul></ul></div>, you would need to call $("#container").trigger("create").
You probably want to see your data after adding some values. If you want to do this listview.refresh doesn't help you after adding some values you have to call you data again, i.e you have to call getNote() again.
I think it helps.
Try this for you complete function instead
complete: function() {
$('#mylist').listview();
}
As someone else mentions the refresh method is for when you are adding listitems to a listview that JQM has already created.
First of all , You must understand how does the refresh work, it will just refresh the listview's css when you add a new LI so that the new LI will have a right css,
function createItem(tx,results){
var len = results.rows.length;
console.log("lisitem len "+len);
for(var i = 0;i<len;i++){
var content = results.rows.item(i).content;
var id = results.rows.item(i).id;
var string = '<li>'+content+' ['+results.rows.item(i).date+']</li>';
$("#all_list").append(string);
};
freshList("all_list");
}
freshList("all_list"); it will refresh the listview ,if you don't do it, all of the LI will display like below.
<li> 测试成功 [2013-10-02]</li>
the LI doesn't have a css description
that's why your ajax operation doesn't work

Resources