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.
Related
I have jQuery call to get the data and a dropdown list on the UI, which is not populating the data.
I have tried many ways, commented is the code I used.
Let me know if I did something wrong in the code.
var questionData;
var optionData;
$(document).ready(function () {
$.ajax({
url: 'coaching-assessment-tool.aspx/GetCATQuestionAndOptions',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
questionData = data.d[0];
optionData = data.d[1];
console.log(questionData[0].QuestionText);
console.log("Question Data", questionData);
console.log("Option Data", optionData);
//Questions
document.getElementById('firstQuestion').innerHTML = questionData[0].QuestionText;
document.getElementById('secondQuestion').innerHTML = questionData[1].QuestionText;
document.getElementById('thirdQuestion').innerHTML = questionData[2].QuestionText;
document.getElementById('fourthQuestion').innerHTML = questionData[3].QuestionText;
document.getElementById('fifthQuestion').innerHTML = questionData[4].QuestionText;
document.getElementById('sixthQuestion').innerHTML = questionData[5].QuestionText;
document.getElementById('seventhQuestion').innerHTML = questionData[6].QuestionText;
document.getElementById('eighthQuestion').innerHTML = questionData[7].QuestionText;
document.getElementById('ninthQuestion').innerHTML = questionData[8].QuestionText;
document.getElementById('tenthQuestion').innerHTML = questionData[9].QuestionText;
//Responses
//var ddlFirstResponse = document.getElementById('#ddlFirstResponse');
//ddlFirstResponse.empty();
$(function () {
$('#ddlFirstResponse').append($("<option></option>").val('').html(''));
$.each(optionData, function (key, value) {
//console.log('option: ' + value.OptionText + ' | id: ' + value.OptionId);
//$('#ddlFirstResponse').append($("<option></option>").val(value.OptionId).html(value.OptionText));
$("#ddlFirstResponse").append("<option value='" + value.OptionId + "'>" + value.OptionText + "</option>");
});
});
},
error: function (error) {
console.log(error);
alert('Error retrieving data. Please contact support.');
}
});
});
<asp:DropDownList ID="ddlFirstResponse" runat="server"></asp:DropDownList>
Your data return handler is a bit off when the returned data is acquired, you can do the following to alleviate that:
function (data, status) {
var json = data;
obj = JSON.parse(json);
var opt = null;
$("#targetIDOfControl").empty();
for (i = 0; i < obj.People.length; i++) {
if (i < obj.People.length) {
opt = null;
opt = document.createElement("option");
document.getElementById("targetIDOfControl").options.add(opt);
opt.text = obj.People[i].Name;
opt.value = obj.People[i].ID;
}
}
The above example creates an option then sets its text and values. Then replicates more options depending on the amount of indexes in the JSON array returned.
Since I received response a bit late, I did trial and error, and finally made it to work.
Here is the code changes I made to make it work.
var ddlFirstResponse = **$("[id*=ddlFirstResponse]");**
ddlFirstResponse.empty();
$(function () {
ddlFirstResponse.append($("<option></option>").val('').html('-- Select value --'));
$.each(industryOptionData, function (key, value) {
//console.log('option: ' + value.OptionText + ' | id: ' + value.OptionId);
ddlFirstResponse.append($("<option></option>").val(value.OptionId).html(value.OptionText));
//ddlFirstResponse.append("<option value='" + value.OptionId + "'>" + value.OptionText + "</option>");
});
});
//var ddlFirstResponse = document.getElementById('ddlFirstResponse'); --> Failed
var ddlFirstResponse = $("[id*=ddlFirstResponse]"); --> worked
I'm trying to show the Title field of a SharePoint list using a JavaScript Query but it just keeps returning the same result regardless of the link I click on. So as below, if I click on 'Lenovo T470' that's what its hould show above the image but it keeps showing 'Lenovo X1 Carbon'.
If I change the code:
var DeviceName = result.Title;
to:
var DeviceName = item.Title;
it comes back undefined. Any ideas? Full code below:
function getDevices() {
var txtTitle = "";
var txtTitleName = "";
//var txtDeviceType = "";
var query = "http://example.com/sites/it/ITInfrastructure/_vti_bin/listdata.svc/Devices?select=ID,Title";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function (i, result) {
var tempID = result.Id;
var tempTitle = result.Title;
var DeviceName = result.Title;
txtTitle = txtTitle + "<p><a href='/sites/it/ITInfrastructure/SitePages/Service%20Catalogue%20Devices.aspx?did=" + tempID + "'>" + tempTitle + "</a></p>";
txtTitleName ="<p>" + DeviceName + "</p>";
});
$('#devices').append($(txtTitle));
$('#devicetitle').append(txtTitleName);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}
I am not sure if this is due to the fact that getJSON is asynchronous or not. I think that would be the most obvious reason, but I don't have a clear understanding of how that works. In my js file, I call the healthCheck method on the body element. Nothing happens. Is my getJSON callback function even getting called? I don't know.
I have uploaded the script on JSFiddle.
The code is also below:
var baseURL = "http://someURL";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";
( function($) {
$.fn.healthCheck = function() {
var timestamp = new Date().toJSON().toString();
var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
var signature = CryptoJS.HmacSHA1(request, key);
request = baseURL + request + "&signature=" + signature;
$.getJSON(request, function(data) {
var result = new Object();
$.each(data, function(key, val) {
result.key = val;
if (val == false) {
this.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
} else {
this.append(key + " working. <br />");
}
});
});
return this;
};
}(jQuery));
Many thanks in advance. I hope my query is well placed. If anyone knows some good resources to get a better understanding of asynchronous methods in jQuery that would be greatly appreciated, also. I haven't found many that have been easy to follow yet.
Try 1) setting context of jQuery.ajax( url [, settings ] ) to this of $.fn.healthCheck ; 2) create reference to this object at $.each()
var baseURL = "http://someURL";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";
(function($) {
$.fn.healthCheck = function() {
// set `this` object within `$.getJSON`
var timestamp = new Date().toJSON().toString();
var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
var signature = CryptoJS.HmacSHA1(request, key);
request = baseURL + request + "&signature=" + signature;
$.ajax({
url:request
, type:"GET"
, contentType: false
, context: this
, processData:false
}).then(function(data) {
// reference to `this` within `$.each()`
var that = this;
var result = new Object();
$.each(JSON.parse(data), function(key, val) {
result.key = val;
if (val == false) {
// `that` : `this`
that.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
} else {
that.append(key + " working. <br />");
console.log("complete"); // notification
}
});
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown); // log errors
});
return this;
};
}(jQuery));
$("body").healthCheck();
See also How do I return the response from an asynchronous call?
var baseURL = "https://gist.githubusercontent.com/guest271314/23e61e522a14d45a35e1/raw/62775b7420f8df6b3d83244270d26495e40a1e9d/a.json";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";
(function($) {
$.fn.healthCheck = function() {
var timestamp = new Date().toJSON().toString();
var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
var signature = 123;// CryptoJS.HmacSHA1(request, key);
request = baseURL + request + "&signature=" + signature;
$.ajax({
url:request
, type:"GET"
, contentType: false
, context: this
, processData:false
}).then(function(data) {
var that = this;
var result = new Object();
$.each(JSON.parse(data), function(key, val) {
result.key = val;
if (val == false) {
that.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
} else {
that.append(key + " working. <br />");
console.log("complete"); // notification
}
});
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown); // log errors
});
return this;
};
}(jQuery));
$("body").healthCheck()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
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;
}
});
});
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":"#"});
}
});
});