jquery addition in ajax result value not working - php

I want to add the result value plus already exists value in that textbox. but addition is not working concatenation is working
$.post('includes/ajax_timesheet.php', {
'action': 'add_kitamount',
'jobnumber': jobno,
'invoiceno': inv_no
}, function (data) {
var tot1 = $('#tot_dayrate').val();
var tot2 = $.trim(data);
var tot = tot1 + tot2;
alert(tot);
$("#tot_dayrate").val(tot);
});

Concatenation is happening because the values are being treated as string by + operator . Parse the values to number using any of the availaible javascript functions and then you will get correct total.
Ofcourse you need to handle for invalid inputs . Below is only showing an example for parse to number function.
var tot = parseInt(tot1) + parseInt(tot2);
Check here for string to number conversion and good explanation of difference between Number() and parseInt() , parseFloat() functions.

var tot = parseFloat(tot1) + parseFloat(tot2);

Convert to number
var tot = Number(tot1) + Number(tot2);
Or
var tot = parseInt(tot1) + tot2;

.val() returns the value of the element in String. You will first need to convert to to Number for performing arithmetic operations.
You can use Number() to convert the string into numbered format.
So your code would look something like this,
var tot1 = $('#tot_dayrate').val();
if(tot1!='') {
tot1=Number(tot1);
}
var tot2 = $.trim(data);
if(tot2!='') {
tot2=Number(tot2);
}
var tot = tot1 + tot2;
Make sure to check for blank value before converting String into int.

Related

Processing json where the number of json array is dynamic

I have a json response from php to ajax. The thing is depending on the value entered in a text box the number of json arrays vary. Example: sometimes it may return {"count1":10, "ccc1":30} and sometimes like this {"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}. I extract the value in jquery this way:
success: function(response){
var count = response.count1;
//do something
}
But now since the number of counts are different I used a loop. Question is I can figure out how many of them I am receiving but how can I process them? The var count = response.count needs to be specific right? I cannot just concate any strings like this:
var count = 0;
while(something){
count = count + 1;
var str = "count"+count;
var whatever = response.str;
}
So, can someone please help me with a suitable solution in this case?
You are on the right track there. Something like this should work for you.
var i = 1;
while(response['count' + i]) {
var count = response['count' + i++];
}
You can access the properties as if they were array indices. so response['count'+i] works.
Loop through all properties and add them in a variable like following.
var response = { "count1": 10, "ccc1": 32, "count2": 40, "ccc2": 123, "count3": 32, "ccc3": 21 };
var count = 0;
for (var prop in response) {
if (prop.startsWith('count'))
count += response[prop];
}
console.log(count);
To retrieve all values use jQuery $.each function.
var data_tmp = '{"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}';
var data = $.parseJSON(data_tmp);
$.each(data, function(k,val){
if(k.toLowerCase().indexOf("count") >= 0){
$('.wr').append('<div>' + val + '</div>')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wr"></div>
success: function(response){
var count = response.count1;
var object = JSON.parse(response);
alert(object.length);
for (i = 0; i < object.length; i++) {
console.log(object[i]);
}
}

Need help to access data between json string and object using jquery

I have a problem with jQuery to obtain each value from jSon string and modify a div or span or other id with value obtained from a jSon string.
At the start of each PHP file i have an SQL request generate an hidden input with a jSon string as value. This is for multilanguage for example in english the generated string is
<input type="hidden" id="page_json_language_home" value='{
"label_title":"My WebSite",
"label_settings":"Settings",
"label_subscription":"Subscription"
}' />
for french :
<input type="hidden" id="page_json_language_home" value='{
"label_title":"Mon site web",
"label_settings":"Parametres",
"label_subscription":"Abonnement"
}' />
this is work fine !
After that i have a javascript using jquery to match each label_xxx with value
i have many html code like this
<title id="label_title></title>
<div id="label_settings"></div>
or
<span id="label_subscription"></span>
This is my (partial) code in my javascript file i called to obtain the json string from hidden input :
var _getPageJsonLanguage = function(id) {
if (!id)
id = "page_json_language";
else
id = "page_json_language_" + id;
var json = $("#" + id).val();
var data = bsc.data.jsonParse(json);
return data;
};
This is work fine too !
The code in problem is :
data_language = bsc.page.getPageJsonLanguage("home");
var j = 0;
var language = [];
for (i in data_language) {
console.log("i in language = " + i);
language[j] = i;
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
The result can i obtain in browser 1) undefined for each label or 2) label_xxx for each label_xxx
I need help to access each value of each label_xxx .
I can't obtain the value, this is my last try....
I believe the problem is in your for in loop, you never actually grab the value, only the key:
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i]; //changed this line to actually grab the value
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
If you are receiving undefined, it may be due to the JSON not being parsed correctly. Since your using jQuery, you can always run $.parseJSON(json) to be sure.
Fiddle accessing your JSON in a for in loop and logging: http://jsfiddle.net/tymeJV/CKBLc/1/
I hope this will work -
var data_language = JSON.parse($("#page_json_language_home").val());
var language = [];
var j = 0;
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i];
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}

Finding the attr values of input or span after they are loaded via .load()

I have a form that does a lookup on a database the lookup is done using load(). This is fine.
What I've like to do is to read the value of an input which is returned via the php.
I was thinking that I needed to use the .live() method but I'm not certain how.
My current code is:
var recordCount = $("input[name=noOfCusts]").val();
console.log("Number is " + recordCount)
So input[name=noOfCusts] is loaded from PHP so I can't get at it. I just get a value of undefined.
How do I roll live() into var recordCount = $("input[name=noOfCusts]").val();
Thanks
My load code is
$("input[name=findCust]").keyup(function(){
var key = $(this).val();
var type = 1;
$("div#CustomerResults").html("<img src='../images/loading.gif' alt='loading'/>").delay('500').load("../../ajax/customerFinder.php",{"key":key,"type":type}).fadeIn(300);
//#############################################
// Extra bit to make the search form work with a return
$("input[name=findCust]").live('keyup',function(){
var recordCount = $("input[name=noOfCusts]").val();
console.log("Number is " + recordCount)
});
//var recordCount = $("input[name=noOfCusts]").find("input[name=noOfCusts]").val();
//
//$('input[name="noOfCusts"]').val(data);
//console.log("Number is " + data)
//#############################################
});
Instead of returning an HTML input tag, return just the value for that input that is already present within HTML DOM.
Then in load call on success set the obtained value to that input:
// success
$('input[name="noOfCusts"]').val(data);
alert(data);

Add two numbers in ajax function

Hi i am new to ajax and trying to add two numbers in ajax function here is the code:
$("#next_btn").click(function(){
Display_Load();
var page = this.title;
var subtract = 1;
$("#content").load("pagination_brand.php?page=" + page, Hide_Load());
this.title = parseInt(page + 1);
});
in this function i am calling the div's title value and on click i want to add 1 value in to that number just like if title is having 1 so onclick it will become 2 but here its taking as string add when i see the output it disply 11 apart of 2.
It must be:
this.title = parseInt(page) + 1;
you need to do it like
for integers
parseInt(number1,10) + parseInt(1,10)
for floats/decimals
parseFloat(number1) + parseFloat(1,10)
Just parse the number then it will treat it like integer rather than string
this.title = parseInt(page)+1;

json/jquery to second div returns NaN

I'm fetching a row of data from a mysql-server using php, then encode it to a json array. I then pull the information using the following PHP. The strange part is that if I send "vname" to it's own div, I get "NaN" as a result. If I display it in the first div, everything turns out fine. Any idea why? Btw, is it right of me to use .html to send to the div? I've tried .appendTo and .text with the same result.
<h3>Output: </h3>
<div id="output">Content1</div>
<div id="username">content2</div>
<script id="source" language="javascript" type="text/javascript">
$(function() {
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data) {
var id = data[0];
var vname = data[1];
var message = data[2];
var timestamp = data[3];
$('#output').html(+id + timestamp + message);
$('#username').html(+vname);
}
});
});
</script>
I;m going to guess its because of the first +. Javascript is trying to add nothing to all of the other stuff, which would output a NaN
$('#output').html(id +timestamp +message );
$('#username').html( vname );
In this case text() might be a better to use because there aren't any html elements in your strings, but it really doesn't matter.
+variable is shorthand for casting a variable to a number: Unary plus/minus (MDN)
var x = "5";
+x; //Gives you 5 as a number
x = "Hello";
+x; //Gives you NaN
You can use regular append.
$('#output').append(id + timestamp + message);
$('#username').append(vname);
$('#output').html(+id + timestamp + message);
$('#username').html(+vname);
These are probably your problem. The plus sign in front of the variables would throw an error. If you are trying to concatenate (add together) the existing the value and your response from the ajax change it to some thing like this:
$('#output').html($('#output').html() + id + timestamp + message);
$('#username').html($('#username').html + vname);

Categories