Defining a json parsing function outside `.ajax` - javascript

Fiddle Example
I'm working on a chained selectbox that populates options via Ajax and uses localStorage to save the returned data. The code is working but I want to simplify the code a little bit.
I want to know if it's possible to define the two $.each functions as a function outside the ajax code and call it back in the success function, like this example,but the tricky part is that the returned data is defined as data in the ajax success function while it's defined as key from the localStorage.
Failed Code:
function loop(){
$.each(data.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
$select.dynamicDropdown({"delimiter":"#"});
}
$('select').each(function(loop){
$(this).one("mouseenter",function(){
var name = $(this).data('name'),
key = JSON.parse(localStorage.getItem(name)),
$select = $('select');var $option="";
$(this).addClass('yellow');
if (!key) {
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fcheapgamessales.com%2F133.json%22&format=json&diagnostics=true&callback=",
success: function(data){
localStorage.setItem(name, JSON.stringify(data));
loop(data);
}
});
}
else{
loop(key);
}
});
});
Original Working Code:
$('select').each(function(){
$(this).one("mouseenter",function(){
var name = $(this).data('name');
var key = JSON.parse(localStorage.getItem(name));
var $select = $('select');var $option="";
$(this).addClass('yellow')
if (!key) {
$.ajax({
url: url,
success: function(data){
localStorage.setItem(name, JSON.stringify(data));
$.each(data.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
$select.dynamicDropdown({"delimiter":"#"});
}
});
}
else{
$.each(key.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
$select.dynamicDropdown({"delimiter":"#"});
}
}); // end one function
});

Like this?
function loop(data, $select){
$.each(data.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
}
$('select').each(function(){
$(this).one("mouseenter",function(){
var name = $(this).data('name');
var key = JSON.parse(localStorage.getItem(name));
var $select = $('select');var $option="";
if (!key) {
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fcheapgamessales.com%2F133.json%22&format=json&diagnostics=true&callback=",
success: function(data){
localStorage.setItem(name, JSON.stringify(data));
loop(data, $select);
$select.dynamicDropdown({"delimiter":"#"});
}
});
}
else{
loop(key, $select);
$select.dynamicDropdown({"delimiter":"#"});
}
});
});

Related

Jquery ajax - price not appearing

I have a jquery function that has an ajax call. I can't get the total price to come up even though it should be working. The class .cart-price is within .cart-body so I don't think its an issue with the template.
function refreshCart(){
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
// $(cartBody).empty()
//cartBody.html("<h1>Changed</h1>")
var productRows = cartBody.find(".cart-product")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data){
console.log("success")
console.log(data)
if (data.products.length > 1){
productRows.html(" ")
$(cartBody).empty()
$.each(data.products, function(index, value){
console.log(value)
cartBody.append("<tr><td>" + value.name + "</td><td>" + value.price + "</td></tr>")
})
// console.log(data.total)
cartBody.find(".cart-total").text(data.total)
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
})
$(cartBody).empty() was clearing everything in the table body. The solution was to create a new HTML table row outside of the table body.

delete from database with javascript

I added a delete function to a todo list app that i built. The delete function works; however, when I refresh the page all the items that i deleted come back. How can I remove the items permanently from the database?
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
//////this section works
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
///////this does not want to remove the item from the database
$.destroy("/tasks/" + itemId, {
_method: "destroy",
task: {
done: doneValue
}
});
});
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
// still dont understand this
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
var li_to_delete = $('.todo-list li.completed');
$.ajax({
type: 'DELETE',
url: "/tasks" + li_to_delete,
success: function(){
li_to_delete.remove();
}
});
});
});
i changed the code but im not sure how to properly extract the url.

jQuery ajax is calling infinily , showing too much recursion error in console

I am using jQuery.validationEngine plugin .I have a below ajax function to check duplicate unique value for a field.
function _is_unique(caller) {
var value = jQuery(caller).val();
var field_id = jQuery(caller).attr('id');
var field_name = jQuery(caller).attr('placeholder');
if (value != '') {
var uniqueObject = new Object();
uniqueObject.field_id = field_id;
uniqueObject.value = value;
var uniqueString = JSON.stringify(uniqueObject);
var getUrl = window.location;
//console.log(getUrl);
var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
jQuery.ajax({
type: "POST",
url: baseUrl + "/dashboard/check_unique",
data: uniqueObject,
async: false,
cache: false,
dataType: "text",
success: function(msg) {
if (msg == "exist") {
isError = true;
promptText += " This " + field_name + settings.allrules["is_unique"].alertText + "<br />";
}
}
});
}
}
if the field value is present in server then from server I am returnning "exist" else I am returning "notexist".
Now while running my ajax script is calling infinitely . Can any please tell me what should I do to stop infinite loop of my ajax call.
Edited
This is the form Submit function . its also showing
too much recursion
error in console. By any chance am I having problem here ?
$('#searchform').on('submit', function(e){
var validateError ='';
var id='';
var fieldError = [];
$('#searchform :input:text').each(function(){
id = $(this).attr('id');
validateError = jQuery.fn.validationEngine.loadValidation(document.getElementById(id));
if(validateError)
{ fieldError.push(id);
}
});
if(fieldError.length!=0)
{
return false;
}
else{
$("form#searchform" ).submit();
return true;
}
});
});

converting .live() to .on() or .click() functions jquery

I'm currently following a tutorial that uses an old version of jQuery to create an mvc with a built in todo list using ajax calls. The original code went as follows:
$(function() {
$.get('dashboard/xhrGetListings', function(o) {
for (var i = 0; i < o.length; i++)
{
$('#listInserts').append('<div>' + o[i].text + '<a class="del" rel="'+o[i].id+'" href="#">X</a></div>');
}
$('.del').live('click', function() {
delItem = $(this);
var id = $(this).attr('rel');
$.post('dashboard/xhrDeleteListing', {'id': id}, function(o) {
delItem.parent().remove();
}, 'json');
return false;
});
}, 'json');
$('#randomInsert').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.post(url, data, function(o) {
$('#listInserts').append('<div>' + o.text + '<a class="del" rel="'+ o.id +'" href="#">X</a></div>');
}, 'json');
return false;
});
});
When I updated the jQuery version it threw a hissy fit and wouldn't work so I looked up the error and it didn't like up the .live() function and so a suggestion was to use .on()
And so I changed the .live into
$(document).on("click", ".del", function()
Now the code does delete from the database but doesn't update until the page is refreshed . . . am I missing something?
You are binding the event to the document. So you do not need to do this more than once, and the elements in question do not need to be present when you bind the event. Move the on syntax outside of the ajax callback, inside the document ready.
$(function(){
$('#listInserts').on("click", ".del", function() {
});
})
Other option is to leave it inside the callback, and modify your code to be:
$.get('dashboard/xhrGetListings', function(o) {
$('.del').on('click',function(){
});
});
NOTE: As suggested below in the comment, the first option would be more suitable in this case since the .del elements are added in the subtmit, unless you want to bind the click event from there as well.
Here's how I would re-write the sample code. I've commented where I changed things.
$(function() {
var $listInserts = $('#listInserts'); // Store the element once so we don't have to do it again
// Function for re-usability
function addToList (text, id) {
$listInserts.append('<div>' + text + '<a class="del" rel="'+id+'" href="#">X</a></div>');
}
// Here I'm assuming that $('#listInserts') is a container for all those .del elements.
// If you use .on() on a containing element try to keep as close to those elements as you can.
// Keeping it close keeps the events from having to bubble up through every parent element on the page.
$listInserts.on('click', '.del', function(e) {
var $delItem = $(this);
e.preventDefault(); // Stops the normal link behavior. Sort of like 'return false;' would do.
$.post('dashboard/xhrDeleteListing', {'id': this.id}, function(o) {
$delItem.parent().remove();
}, 'json');
});
$.get('dashboard/xhrGetListings', function(o) {
for (var i = 0; i < o.length; i++)
{
addToList(o[i].text, o[i].id);
}
}, 'json');
// Changed to .on()
$('#randomInsert').on('submit', function(e) {
var url = $(this).attr('action');
var data = $(this).serialize();
e.preventDefault();
$.post(url, data, function(o) {
addToList(o.text, o.id);
}, 'json');
return false;
});
});
Move event handler for .del outside callback function
Change to reuse cached delItem
Remove delItem from global scope
Modified code:
$(document).ready(function () {
$(document).on("click", ".del", function () {
var delItem = $(this);
var id = delItem.attr('rel');
$.post('dashboard/xhrDeleteListing', {
'id': id
}, function (o) {
delItem.parent().remove();
}, 'json');
});
$.get('dashboard/xhrGetListings', function (o) {
for (var i = 0; i < o.length; i++) {
$('#listInserts').append('<div>' + o[i].text + '<a class="del" rel="' + o[i].id + '" href="#">X</a></div>');
}
}, 'json');
$('#randomInsert').submit(function () {
var url = $(this).attr('action');
var data = $(this).serialize();
$.post(url, data, function (o) {
$('#listInserts').append('<div>' + o.text + '<a class="del" rel="' + o.id + '" href="#">X</a></div>');
}, 'json');
return false;
});
});
EDIT Revised to only hit the DOM once on the insert, bind to the wrapper for the 'on() event handler:
$(document).ready(function () {
$('#listInserts').on("click", ".del", function () {
var delItem = $(this);
var id = delItem.attr('rel');
$.post('dashboard/xhrDeleteListing', {
'id': id
}, function (o) {
delItem.parent().remove();
}, 'json');
});
$.get('dashboard/xhrGetListings', function (o) {
var newlinks = ''
for (var i = 0; i < o.length; i++) {
newlinks = newlinks + '<div>' + o[i].text + '<a class="del" rel="' + o[i].id + '" href="#">X</a></div>';
}
$('#listInserts').append(newlinks);
}, 'json');
$('#randomInsert').submit(function () {
var url = $(this).attr('action');
var data = $(this).serialize();
$.post(url, data, function (o) {
$('#listInserts').append('<div>' + o.text + '<a class="del" rel="' + o.id + '" href="#">X</a></div>');
}, 'json');
return false;
});
});
this is my solution for this jquery script with the latest lib:
$(function() {
$('#listInserts').on('click', '.del', function() {
var delItem = $(this);
var id = $(this).attr('rel');
$.post('dashboard/xhrDeleteListing', {'id': id}, function() {
delItem.parent().remove();
});
});
$.get('dashboard/xhrGetListings', function(o) {
for (var i = 0; i < o.length; i++) {
$('#listInserts').append('<div>' + o[i].text + ' <a class="del" rel="' + o[i].id + '" href="#">elimina</a></div>');
}
}, 'json'); // JSON = JavaScript Object Notation
$('#randomInsert').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.post(url, data, function(o) {
$('#listInserts').append('<div>' + o.text + ' <a class="del" rel="' + o.id + '" href="#">elimina</a></div>');
}, 'json');
return false;
});});
Hope this help.

Defining jQuery variable from url

I have a jQuery search script that uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/. I need to somehow define the query terms in my window.location.hash.replace so I am just left with the search type from the URL. How can I go about changing the QUERYGOESHERE in my example below to the query the user has made? I hope people can understand my question.
My jQuery Script is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
if (window.location.hash != "") {
url = window.location.hash.replace('#', '').replace('/QUERYGOESHERE/', '');
$('#type_' + url).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
This should do it.
var full = window.location.hash.replace('#', '')
var queryType = full.substring(0,full.indexOf("/"))
var query = full.replace(queryType, '');
EDIT: Updated code
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0,full.indexOf("/"));
console.log('#type_' + queryType);
$('#type_' + queryType).click();
}

Categories

Resources