how to access variable - javascript

I'm hoping there is a straightforward solution to this one. I'm simply trying to get the 'net_price', from my append, to use in another function.
Can anyone help at all?
JSON
$.getJSON("{{{ url('api/get-price')}}}", { id: $productId },
function(data){
if(data.prices == true){
$('#prices span').empty();
$('#prices').fadeIn(2000);
$.each(data, function(key, value){
$('.cost').append('<div>Cost: ' + value.net_price +'</div>');
});
}
});
Function where I need to replace XXXX with price:
var calc = function(currentPrice){
if(currentPrice.getPrice()==100){
this.setOptions({
maxPrice:'XXXXX'
});
};

You could make a global variable for the net price and then update the variable within your JSON call.
// Declare variable globally
var netPrice = '';
$.getJSON("{{{ url('api/get-price')}}}", { id: $productId },
function(data){
// Update variable
netPrice = value.net_price;
if(data.prices == true){
$('#prices span').empty();
$('#prices').fadeIn(2000);
$.each(data, function(key, value){
$('.cost').append('<div>Cost: ' + netPrice +'</div>');
});
}
});

May be you can do
$.each(data, function(key, value){
$('.cost').append('<div>Cost: <span class="netPrice">' + value.net_price +'</span></div>');
});
and access it from calc function:
var calc = function(currentPrice){
if(currentPrice.getPrice()==100){ // if Saturday
this.setOptions({
maxPrice: $('.cost').find('.netPrice').text()
});
};
}

Related

.when .done function not running

I have a little script, that saves to json strings to var with the function getJSON. After that I want to create some divs with the content.
For that I create a each for the cat (categories). In the second each, when the repo fits into a cat it should be display too.
But the script never goes to the .when or .each functions.
But with console_log() I see the correct response from the getJSON function.
var repo;
var cat;
$.getJSON("api.php?get_repos&release_id=" + $("#release").find(":selected").data('id'), function (
json) {
repo = json;
});
$.getJSON("api.php?get_cat", function (json) {
cat = json;
});
$.when(repo, cat).done(function(){
$.each(cat, function (i, j) {
$(".tab").append('<button class="tablinks" onclick="openCAT(event, \'' + j.cat_name + '\'">' + j.cat_name + '</button>');
$(".repos").append('<div id="' + j.cat_name + '" class="tabcontent"></div>');
$.each(repo, function (k, v) {
if (v.repo_cat == j.cat_id) {
$("#"+ j.cat_name).append('<div class="repo"></div><p><label><input name="3rdparties[]" type="checkbox" value="' +v.repo_id + '"> ' + v.repo_name +'</label> <i class="icon ion-earth"> Homepage</i> <i class="icon ion-university"> Documentation</i>');
$("#"+ j.cat_name).append('<div class="inside">' + v.repo_desc + '');
$("#"+ j.cat_name).append('<i class="icon ion-flash-off"> Broken Repo</i></div></p></div><br />');
}
});
});
});
There are two issues:
repo,cat are JSON values, not promise or deferred objects, so $.when will not have any effect
repo,cat are only set after the $.getJSON has completed, so will not be available at the time of the $.when
You need to record the jquery promise returned from $.getJSON to be used with $.when:
var repo;
var cat;
var repoPromise = $.getJSON("api.php?get_repos&release_id=" + $("#release").find(":selected").data('id'), function(json) {
repo = json;
});
var catPromise = $.getJSON("api.php?get_cat", function(json) {
cat = json;
});
$.when(repoPromise, catPromise).done(function() {
$.each(cat, function(i, j) {
...
$.each(repo, function(k, v) {
if (v.repo_cat == j.cat_id) {
...
}
});
});
});

JQuery-How to call external function with parameter in side onchange method in jquery

How to call method inside onchange method in jquery.
snippet below :
$("#age").change(function(){
var age=document.appform.age;
if(age.value > 125){
return false;
}
//i have some conditions same as above if condition
filtercustmerdata(age.value);
}
Method is :
function filtercustmerdata(ageval){
alert("Age: "+ageval);// i got this value
//But its not working
$.getJSON("getCustDetails",{dateOfBirth: ageval}, function(data){
alert("data: "+data);
var data2=JSON.stringify(data);
alert("Stringfy data: "+data2);
var str = "";
$.each(data.custdetails, function(key, value) {
var custid=value[0];
var custname=value[1];
str = str+ "<option value="+custid+ ">"+ custname+ "</option>";
});
$("#CustDetails").html(str);//Dropdown
});
}
The filtercustmerdata method is called but
$.getJSON
is not working?
I didn't get error/exception?
Please help me!

AJAX list update, get new elements and count

I have this HTML list
<ul id='usernameList'>
<li class='username'>John</li>
<li class='username'>Mark</li>
</ul>
and a form to add new names via AJAX, multiple add separated by commas. The response is a list with the names
[{name:David, newUser:yes}, {name:Sara, newUser:yes}, {name:Mark, newUser:no}]
I'm trying to insert this names sorted alphabetically in the list, like this example https://jsfiddle.net/VQu3S/7/
This is my AJAX submit
var form = $('#formUsername');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType: "json",
beforeSend: function () {
//
},
success: function (data) {
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});
}
});
return false;
});
My question is, how I can update the value of listUsernames and numUsernames after adding an item?
You just need to update numUsernames at that point.
Add this where your comments are:
numUsernames = listUsernames.children().length;
listUsernames already has the updated children, as it's a reference to the parent element.
Edit: Re: your comment below:
This should probably work:
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
return false; // stop `.each` loop.
}
});
First you don't need a double jQuery wrapping:
$(htmlUser).appendTo($(listUsernames));
listUsernames is already a jQuery object, so try:
$(htmlUser).appendTo(listUsernames);
And after every adding, you can update the numUsernames variable with:
numUsernames = listUsernames.children().length;
but this is not necessary because you can always access listUsernames.children().length in the success handler.
I update your JSFiddle
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
var data = [{name:'David', newUser:'yes'}, {name:'Sara', newUser:'yes'}, {name:'Mark', newUser:'no'}]
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".ingredient", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});

jQuery document ready call sequence

I have a following problem with jQuery. I use this code:
function populate_select_from_json(select, json_url) {
select.empty();
$.getJSON(json_url, function(data) {
$.each(data, function(key, value) {
$("<option></option>")
.attr("value", value.name)
.text(value.title)
.appendTo(select);
});
});
select.children(":first").attr("selected", true);
}
$(document).ready(function() {
var value_type = $("#value_type");
populate_select_from_json(value_type, SOME_URL);
var unit = $("#unit");
populate_select_from_json(unit, ANOTHER_URL + value_type.val());
});
I wanted to:
Load the document
Get some JSON data from an associated database
Put the data in #value_type <select> item
Get the value of #value_type select, and query the database once again to populate another select item.
The problem is, when I call value_type.val(), it always outputs null, even though the #value_type <select> is correctly populated. What am I doing wrong here?
I suppose something like this may work better with promises.
Along these lines (untested):
var populate_select_from_json = function($select, json_url) {
$select.empty();
return $.getJSON(json_url, function(data) {
$.each(data, function(key, value) {
$("<option></option>")
.attr("value", value.name)
.text(value.title)
.appendTo($select);
});
$select.children(":first").attr("selected", true);
});
};
$(document).ready(function() {
var $value_type = $("#value_type");
var $unit = $("#unit");
populate_select_from_json($value_type, SOME_URL).done(function(){
populate_select_from_json($unit, ANOTHER_URL + $value_type.val());
});
});

What is a better way to rewrite this JSON to jQuery data()?

For some reason I have this huge brain fart today. >.<
I have a JSON data that I am attaching to using jQuery .data() that looks like this:
$.getJSON("names.php", function(data) {
//generate html string and append to DOM
$.each(data, function(i,item) {
var strHtml;
strHtml += '<img src="' +item.PIC + '.jpg" id="' + item.ID + '" />';
})
$('body').html(strHtml);
//attach data to image ID
$.each(data, function(i,item) {
$('#' + item.ID).data(item.ID, {
NAME: item.NAME,
PHONE: item.PHONE,
EMAIL: item.EMAIL,
ADDRESS: item.ADDRESS,
...
...
...
});
}
}
This works fine; however, it looks a little ugly and I am trying to clean it up a little mainly on this part:
$.each(data, function(i,item) {
$('#' + item.ID).data(item.ID, {
NAME: item.NAME,
PHONE: item.PHONE,
EMAIL: item.EMAIL,
ADDRESS: item.ADDRESS,
...
...
...
});
}
I am adding an array of object to the key value.
Example from http://api.jquery.com/data/
$('body').data('bar', { myType: 'test', count: 40 });
Here is my attempt to rewrite it:
$.each(data, function(i,item) {
$('#' + item.ID).data(item.ID, function(){
$.each(item) {
return i + ':' item[i];
}
})
}
Is there a cleaner way to write this?
I've also tried $('#' + item.ID).data(item.ID, JSON.stringify(data));
If you just want the full item added, with all it's properties, you can just do this:
$.each(data, function(i,item) {
$('#' + item.ID).data(item.ID, item);
});
.data() takes any value, including an object, so you might as well use the original. Also, it's more likely that you want this:
$.each(data, function(i, item) {
$('#' + item.ID).data("someKey", item);
});
Then you can use a consistent .data("someKey") to get the data back out as well, rather than using the element's own .id as the data key as well.
You can just do:
$('#' + item.ID).data(item.ID, item);
You'll still be able to access the values as expected:
$('#' + someId).data(someId).NAME;
By the way, JSON.stringify isn't a good idea because in order to read the values back again, you'll have to convert it back from a string into an object.
Try:
$('#' + item.ID).data("info", item);

Categories

Resources