JSON string returns NAN - javascript

I have a web API that returns a JSON result, when I issue a GET request using the API URL, it works OK. But when I call my API from jQuery only one string field returns NAN.
Result:
$.ajax({
Type: 'GET',
url: 'api/controller1',
dataType: 'JSON',
success: function (data) {
var htmlString = '';
$(data).each(function (index, data) {
var myDate = new Date(data.date);
htmlString += '<h3>' + String(myDate) + '</h3><div>'
+ data.ID + "<br/>" +
+ data.stringvalue + '</div>';
});
$('#accordion').html(htmlString).accordion({
collapsible: true
});
I tried the JSON.Stringify() method but it returns the same result. I also tried to get the type of the specified value and its string so I don't think I need to parse it or what so on.
Can you please help?

After your <br> tag, you have an extra plus sign. JavaScript can no longer coalesce properly, and tries to use number addition instead of string concatenation, casting your string to NaN.

Related

Put decimal places on parse json data and display inside modal input

Why can't I display the product of subtotal and sum of amount due with two decimal places? When I add toFixed(2) at the end it gives me error like this:
Uncaught TypeError: modal.find(...).val(...).toFixed is not a function.
function view_sales(sales_id) {
var modal = $('#sales-modal');
$.ajax({
type: 'POST',
url: url + 'GetSalesById',
data: { sales_id : sales_id },
dataType: 'json',
success: function (data) {
modal.modal({ backdrop: 'static', keyboard: false});
modal.find($('#sales_id')).val(sales_id);
modal.find($('#sales_po')).val(data.sales_po);
modal.find($('#sales_so')).val(data.sales_so);
modal.find($('#sales_dr')).val(data.sales_dr);
modal.find($('#sales_si')).val(data.sales_si);
modal.find($('#sales_particulars')).val(data.sales_particular);
modal.find($('#sales_media')).val(data.sales_media);
modal.find($('#sales_width')).val(data.sales_width);
modal.find($('#sales_height')).val(data.sales_height);
modal.find($('#sales_unit')).val(data.sales_unit);
modal.find($('#sales_total_area')).val(data.sales_total_area);
modal.find($('#sales_price_unit')).val(data.sales_price_unit);
modal.find($('#sales_sub_total')).val(parseFloat(data.sales_total_area) * parseFloat(data.sales_price_unit)).toFixed(2);
modal.find($('#sales_qty')).val(data.sales_qty);
modal.find($('#sales_total')).val(data.sales_total);
modal.find($('#sales_vat')).val(data.sales_vat);
modal.find($('#sales_amount_due')).val(parseFloat(data.sales_total) + parseFloat(data.sales_vat)).toFixed(2);
modal.find($('#sales_discount')).val(data.sales_discount);
modal.find($('#sales_net_amount')).val(data.sales_net_amount);
$('#modal-title').html('<i class="icon-add-to-list mr-2"></i> UPDATE SALES DETAILS');
$('#btn-sales').html('Save Changes <i class="icon-arrow-right14 position-right"></i>').attr('disabled',false);
}
});
}
You're trying to call toFixed on string, because val method returns string.
You have to call toFixed on Number values like that:
modal.find($('#sales_sub_total')).val((parseFloat(data.sales_total_area) * parseFloat(data.sales_price_unit)).toFixed(2));
modal.find($('#sales_amount_due')).val((parseFloat(data.sales_total) + parseFloat(data.sales_vat)).toFixed(2));
Firstly note that you should provide a string selector to find(), not a jQuery object. The latter makes the find() operation redundant:
modal.find('#sales_id').val(sales_id);
modal.find('#sales_po').val(data.sales_po);
// and so on...
With regard to your actual issue, val() returns a string. You cannot call toFixed() on a string. Even if you could you'd need to call toFixed() on the argument you provide to the method, not the result of the function call.
Therefore to fix your issue wrap the calculation in parentheses to group it, then put toFixed() on that:
modal.find('#sales_sub_total').val((parseFloat(data.sales_total_area) * parseFloat(data.sales_price_unit).toFixed(2));
modal.find('#sales_amount_due').val((parseFloat(data.sales_total) + parseFloat(data.sales_vat).toFixed(2));

Sharepoint 2013 Rest API - oData $filter query is still remembering white space I eliminated in javascript

I'm trying to create a custom input field with autocomplete features in my Sharepoint page. I'm using the Rest API to $filter the input value using "substringof." So far it's working but now I'm trying to consider if people typed in spaces.
For example, if someone typed " Joe" instead of "Joe" then it will no longer find results. Hence, I tried to eliminate the blank spaces with Javascript but the query is still not providing results when there are blank spaces. Anyone have a clue why? Here is my function below:
function q_Names(term){
var termSplit = term.split(";");
var t = termSplit[termSplit.length-1].charAt(0).toUpperCase() + termSplit[termSplit.length-1].slice(1);
//var q = t.split(" ").join("");
var q = t.replace(/\s+/g, '');
if(q.length>1){
alert(path + "web/siteusers?$select=Id,Title&$filter=substringof('"+q+"',Title)");
$.ajax({
url: path + "web/siteusers?$select=Id,Title&$filter=substringof('"+q+"',Title)",
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function(data){
//alert( JSON.stringify(data) );
var str = ""
for(var i=0; i<data.d.results.length; i++){
str=str + "<div><a href='javascript:acf_author();'>";
str=str + data.d.results[i].Title + "</a></div>";
}
$("#ac_Author").html(str);
},
error: function(data){ alert('could not find user!'); }
});
}
}

JS Create A Date Object from value passed via AJAX Call

I have a Python script that returns me a calculated date time in XML format like below:
<prev><date>2012,07,16</date><time>22:00:00</time></prev>
Though I can change the format but my issue is that when I try creating a JS date object using the value returned - I get 'Invalid date':
$.ajax({
async: false,
type: "POST",
url: "/cgi-bin/prev_hour.py",
success: function(xml)
{
pdate = $(xml).find('date').text();
ptime = $(xml).find('time').text();
//alert prints correct date time ex 2012-07-16 22:00:00
},
error:function(xhr,err,html)
{
alert("Failed\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
}
var max_date = new Date("'" + pdate + ptime + "'");
alert(max_date);
I tried a couple of possibilities like Python script returning in various format:
<prev><date>2012/07/16 </date><time>22:00:00</time></prev>
<prev><date>2012,07,16 </date><time>22,00,00</time></prev>
But still I get invalid date when trying to create a JS date object?
Please let me know the correct way to implement it.
You don't need the extra set of quotes in your date string, and you will need a space between the date and time components, try:
new Date(pdate + " " + ptime);
Try using amazing lib for dates called Moment.js
moment("2012/07/16 22:00:00")
from there you can achieve everything with dates.
This:
var max_date = new Date("'" + pdate + ptime + "'");
Should be:
var max_date = new Date(pdate + ' ' + ptime);
Next time you run into such issues put an alert on the value you are sending to the function and see what it looks like.

JSON and Backslash

Can anyone shed any light as to why my JSON is coming out below, with the extra backslashes. I am using ASP.net MVC to serialise a datatable, when I debug in Visual studio it all looks ok but when I look with firebug with adds the extra characters?
Any ideas anyone?
JSON
[{\"uid\":\"516219026\",\"pic\":\"http://profile.ak.net/\",\"first_name\":\"Daniel\",\"last_name\":\"James\",\"fql_query_response_Id\":0,\"LIFEID\":null}
JAVASCRIPT
function GetFBFriends() {
FB.Connect.requireSession(function() {
$.ajax({
url: "/Facebook/GetFaceBookFriends",
type: 'POST',
data: null,
dataType: 'json',
success: function(result) {
data = "<table>";
alert(result.length);
for (i = 0; i < result.length; i++) {
data += "<tr><td><td><img src=" + result[i].pic + " alt=" + result[i].first_name + " /></td><input type='checkbox' value='" + result[i].uid + "' name='friends[]' id = 'friend" + result[i].uid + "' /></td><td>" + result[i].first_name + " " + result[i].last_name + "</td></tr>";
}
data += "</table>";;
}
});
})
};
Public Function GetFaceBookFriends() As JsonResult
Dim fbFriends As New DataTable
Try
fbFriends = FacebookModel.GetFriendsAndMatchToLife()
Return Json(JsonConvert.SerializeObject(fbFriends))
Catch ex As Exception
Finally
fbFriends.Dispose()
fbFriends = Nothing
End Try
End Function
That's Firebug showing the string containing JSON in it's string representation. Think of it as JSON-encoding a string containing JSON. Or rather, if your were to put the JSON in a string literal in your Javascript, it would look like that.
Your string does not actually contain those backslashes. They are just escapes for the double-quotes.
Looks like Firebug is adding escape characters. What if you enclosed your entire JSON in single quotes? That may correct the problem. Edit Can you provide the code that encodes your JSON?
I solved this question, I was returning JSON data which was then being changed into JSON by jquery as well, so I simply returned a string and jquery handled it correctly.
I would suggest doing injecting the following into the first line for the success function.
console.dir({'result':result});
This will show you what you are getting back, as opposed to just viewing the result from the network call.
The Firebug display is simply escaping the string, so you can copy/paste the entire result into the console for inspection/interrogation directly...
var temp = {pasted-string-here}
//var temp = "[{\"uid\":\"516219026\",\"pic\":\"http://profile.ak.net/\", ... }]"
var val = JSON.parse(temp);
console.debug({"val":val});

parsing new lines in jquery

I've recently asked and had answered this question and it's stopped the issue of the string literal error, however it's now caused another problem
$(document).ready(function()
{
$("#message-list .message").click(function()
{
var msg_id = 1;
msg_id = $(this).attr('id').split('-')[1];
$.ajax({
type: "GET",
url: "get_message.php",
data: "id=" + msg_id,
success: function(msg){
var converter = new Attacklab.showdown.converter();
json = eval("("+ msg +")");
var copy = converter.makeHtml(json.copy);
$("#message-details .subject").html(json.title);
$("#message-details .importance").html(json.importance);
$("#message-details .date").html(json.date);
$("#message-details .message").html(copy);
}
});
});
});
this is the jquery function that the string is parsed into (json.copy to be exact) and is where the problem occurs. On creating the json string as in my previous question we removed any \r as they were not parsing out and escaping \n with \n. However i now have the issue of the new lines printing \n on the screen and need a way within this function to unparse them without causing the unterminated string literal error again.
>_<
EDIT:
Message:
all\n\n \n\n advisers\n\n \n\n at\n\n newtown
json string for that coming in is :
{"title":"testing again","copy":"all\n\n\n\n\n\nadvisers\n\n\n\n\n\nat\n\n\nnewtown","importance":"read Now","date":"2009-09-22 13:12:22"}
It's a quick and dirty hack, but it would be fast as well: why don't you just replace "\n" with "<br />"?

Categories