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

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

Related

Trouble accessing the property of a class in Ajax

In index.cshtml I am using Ajax. In click event of .removelink to get changes from action controller as follows:
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '' || recordToDelete != null) {
// Perform the ajax post
$.ajax({
//contentType: 'application/json',
//dataType: 'text',
type: 'post',
dataType: 'JSON',
url: '/ShoppingCart/RemoveFromCart/',
data: { id: recordToDelete },
success: function (data) {
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
}
else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
});
}
});
And in controller:
//AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public IActionResult RemoveFromCart(int id)
{
//Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
//string albumName = _context.Carts
//.Single(item => item.RecordId == id).Album.Title;
Cart cartt = ShoppingCart.getCartForGetalbumName(id);
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = HtmlEncoder.Default.Encode(cartt.Album.Title) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
//CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
}
However, it does not work. Additionally, the text of the tags does not change and fadeOut() does not work.
When I send a unit field (eg, a string or an integer) Jason reads it well.
However, when I send a class containing some properties (like the example above), its value in the data parameter is problematic.
Please modify your property to lowercase , try to use :
success: function (data)
{
if (data.itemCount == 0) {
$('#row-' + data.deleteId).fadeOut('slow');
}
else {
$('#item-count-' + data.deleteId).text(data.itemCount);
}
$('#cart-total').text(data.cartTotal);
$('#update-message').text(data.message);
$('#cart-status').text('Cart (' + data.cartCount + ')');
}
i add The following code to convert data to json in RemoveFromCart controller action:
var resulTtoJson = Newtonsoft.Json.JsonConvert.SerializeObject(results);
and return json type :
[HttpPost]
public IActionResult RemoveFromCart(int id)
{
//Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
//string albumName = _context.Carts
//.Single(item => item.RecordId == id).Album.Title;
Cart cartt = ShoppingCart.getCartForGetalbumName(id);
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message ="محصول"+ cartt.Album.Title +
"از سبد خریدتان حذف گردید.",
CartTotal = cart.GetTotal(),
//CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
var resulTtoJson = Newtonsoft.Json.JsonConvert.SerializeObject(results);
return Json(resulTtoJson);
also add the following code in view to convert data to javascript type:
var data =JSON.parse(dataa);
and use it:
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
// alert(recordToDelete);
if (recordToDelete != '' || recordToDelete != null) {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart/", { id: recordToDelete},
function (dataa) {
// Successful requests get here
// Update the page elements
var data =JSON.parse(dataa);
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
});
}
});

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 do I add html tags in jquery plugins?

I am doing the live search using the jquery plugins. When I tried to search that doesn't exist, it only shows the table. I would like to put some message "No result found" if it doesnt exist. The question is how can I add message "No result found"
Note: In my codes I add some validation, the user need input minimum of 3 characters
/**
**options to have following keys:
**searchText: this should hold the value of search text
**searchPlaceHolder: this should hold the value of search input box placeholder
**/
(function($)
{
$.fn.tableSearch = function(options)
{
if(!$(this).is('table'))
{
return;
}
var tableObj = $(this),
searchText = (options.searchText)?options.searchText:'Search: ',
searchPlaceHolder = (options.searchPlaceHolder)?options.searchPlaceHolder:'',
divObj = $('<div style="font-size:20px;">'+searchText+'</div><br /><br />'),
inputObj = $('<input style="min-width:25%;max-width:50%;margin-left:1%" type="text" placeholder="'+searchPlaceHolder+'" />'),
caseSensitive = (options.caseSensitive===true)?true:false,
searchFieldVal = '',
pattern = '';
inputObj.off('keyup').on('keyup', function(){
searchFieldVal = $(this).val();
if(searchFieldVal.length == 0)
{
tableObj.find('tbody tr').show();
}
else if(searchFieldVal.length >= 3)
{
pattern = (caseSensitive)?RegExp(searchFieldVal):RegExp(searchFieldVal, 'i');
tableObj.find('tbody tr').hide().each(function()
{
var currentRow = $(this);
currentRow.find('td').each(function()
{
var result = "No result";
$("tbody tr").append(result);
if(pattern.test($(this).html()))
{
currentRow.show();
return false;
}
});
});
}
});
tableObj.before(divObj.append(inputObj));
return tableObj;
}
}(jQuery));
Here into JQ plugin(Posted at your question), the handler for empty result is exist. See piece of code from it.
else if(searchFieldVal.length >= 3)
{
pattern = (caseSensitive)?RegExp(searchFieldVal):RegExp(searchFieldVal, 'i');
tableObj.find('tbody tr').hide().each(function()
{
var currentRow = $(this);
currentRow.find('td').each(function()
{
var result = "No result";
$("tbody tr").append(result);
if(pattern.test($(this).html()))
{
currentRow.show();
return false;
}
});
});
}
Paraphrase you mistaken at your end. Re check it.

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.

Magento Add to cart ajax buttons not working with secure(https) cart

I have enabled secure cart in our magento. After that, add to cart buttons were not working. My theme has custom ajax add-to-cart buttons. Then I added following code in my template js code and add to cart button of product list page started working. But, i could not figure out how i should change the add-to-cart button code of product view(detail) page as it's not working too. I need them with my secure cart. My product detail page is under http protocol. If I manually enter product detail page with https, the add to cart button works. But, I need it working under http product detail page and works functional with secure cart page. How should I change the javascript code or any other code?
My code
if (window.location.protocol == "https:") {
url=url;
}else{
url=url.replace("https://","http://");
}
My theme: http://demo.galathemes.com/#gala-gearbox
Here is theme javascript code that's doing this job:
var test;
Event.observe(window, 'load', function () {
var containerDiv = $('containerDiv');
if(containerDiv)
test = new LightboxAJC(containerDiv);
});
function cart_form(url)
{
data = $('product_addtocart_form').serialize();
ajax_add(url,data);
}
function ajax_add(url,param)
{
tam = url.search("checkout/");
tam2 = url.search("product/");
str1 = url.substr(0,tam)+'ajaxcart/index/add/';
str2 = url.substr(tam2,url.length);
link = str1+str2;
var check = url.search("options");
if(check > 0){
window.location.href = url;
}
else{
var tmp = url.search("in_cart");
test.open();
new Ajax.Request(link, {
parameters:param,
onSuccess: function(data) {
if(tmp > 0 ) {
var host = find_host(url);
window.location.href = host+'index.php/checkout/cart/';
}
else{
//result = data.responseText;alert(result);
$('ajax_content').innerHTML = data.responseText;
if($('ajax_content').down('.top-link-cart')){
var count_cart = $('ajax_content').down('.top-link-cart').innerHTML;
$$('.top-link-cart').each(function (el){
el.innerHTML = count_cart;
});
}
if($('ajax_content').down('.block-cart')){
var ajax_product = $('ajax_content').down('.block-cart').innerHTML;
$$('.block-cart').each(function (el){
el.innerHTML = ajax_product;
});
}
if($('ajax_content').down('.col-main')){
var ajax_result = $('ajax_content').down('.col-main').innerHTML;
$$('.ajaxcart_row1').each(function (el){
el.innerHTML = ajax_result;
});
}
$('ajax_loading').hide();
$('ajaxcart_conent').show();
Event.observe('closeLink', 'click', function () {
test.close();
$$('.ajaxcart_row1').each(function (el){
el.innerHTML = '';
});
$('ajax_loading').show();
});
}
}
});
}
}
function setLocation(url){
if (window.location.protocol == "https:") {
url=url;
}else{
url=url.replace("https://","http://");
}
var tam = url.search("checkout/cart/");
if(tam > 0) ajax_add(url);
else window.location.href = url;
}
document.observe("dom:loaded", function() {
var cartInt = setInterval(function(){
if (typeof productAddToCartForm != 'undefined'){
if(test){
var tam = $('product_addtocart_form').serialize();
var check = tam.search("ajaxcart");
if(check < 0){
productAddToCartForm.submit = function(url){
if(this.validator && this.validator.validate()){
cart_form($('product_addtocart_form').readAttribute('action'));
clearInterval(cartInt);
}
return false;
}
}
}
} else {
clearInterval(cartInt);
}
},500);
});
function find_host(url)
{
var tmp = url.search("index.php");
var str = url.substr(0,tmp)
return str;
}
This is the solution that works for all pages! It's very simple..
if (window.location.protocol == "http:") {
url=url.replace("https://","http://");
}

Resources