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.
I'm trying to append a some HTML to a code in jquery, but chrome keeps throwing "unexpected string" at the append function, here's the code :
for (var i =0 ;i<resultArray.length;i++){
$.ajax({url:"getExpenseInfo.php",type:"POST",data : {
'expenseId' : resultArray[i]["expenseId"]
},success:function(expense){
expense = $.parseJSON(expense);
$("#mainDiv").append("<div class=\"row\">".expense["expenseName"]."</div>");
}});
}
I guess you're mixing up php and js syntax, string concatenation works with + in js and not ..
$("#mainDiv").append("<div class=\"row\">" + expense["expenseName"] + "</div>");
Your string concatenation in your append function is a little off. Try something like this:
for (var i =0 ;i<resultArray.length;i++){
$.ajax({url:"getExpenseInfo.php",type:"POST",data : {
'expenseId' : resultArray[i]["expenseId"]
},success:function(expense){
expense = $.parseJSON(expense);
$("#mainDiv").append("<div class=\"row\">"+expense[expenseName]+"</div>");
}});
}
I am saving table data to a json object. The table data is coming from txt inputs and textareas in the table cells.
I'm running into a problem with CR/LF characters in the JSON elements holding the textarea data. The JSON data gets saved to the database fine, but when I pass it back to the jQuery function that populates the table using that data, I get this:
SyntaxError: JSON.parse: bad control character in string literal at line 1 column 67 of the JSON data
var array = JSON.parse(notes),
in the console.
I put the JSON data in Notepad++ with Show All Characters on and the CR/LF was at column 67.
Here's a sample of JSON data that I'm working with:
[["","","",""],["","9/23/14","",""],["","30789 detail, x_vendor_no**CR/LF HERE**
20597 header","",""],["","99 del invalid x_vendor_no","",""],["","30780","",""],["","","",""],["","","",""],["","","",""]]
Is there a way to allow CR/LF in the data?
UPDATE
11684's suggestion to use replace to remove the \r part of the CRLF won't work. Here's why:
Here's the complete function that uses the JSON data:
(Updated to work with Update #2 code below)
function PopulateTaskTableWithNotes(tableID,notesArray) {
// JSON parse removed per answer suggestion
var r, c, note;
for (r = 0; r < notesArray.length; ++r) {
for (c = 0; c < notesArray[r].length; ++c) {
note = notesArray[r][c];
$('#' + tableID + ' tr:nth-child(' + (r + 1) + ') td:nth-child(' + (c + 1) + ')').children(':first-child').val(note);
}
}
}
I still get the error on the line that tries to parse the JSON data. The replace function apparently can't "find" characters within an array element.
UPDATE #2
Here's how I am creating the array:
var siteID = $('#ddlUserSites option:selected').val(),
numRows = $('#' + tableID + ' tr').length,
numCols = $('#' + tableID).find('tr:first th').length,
notesArray = new Array(numRows),
rowNum = 1,
note = '',
colNum;
while (rowNum <= numRows) {
notesArray[rowNum] = new Array(numCols);
// Reset colNum for next row iteration
colNum = 1;
while (colNum <= numCols) {
note = '';
if ($('#' + tableID + ' tr:nth-child(' + rowNum + ') td:nth-child(' + colNum + ')').children(':first-child').is('input,textarea')) {
note = $('#' + tableID + ' tr:nth-child(' + rowNum + ') td:nth-child(' + colNum + ')').children(':first-child').val();
}
notesArray[rowNum][colNum] = note;
//console.log('Note for rowNum ' + rowNum + ', colNum ' + colNum + ': ' + note);
colNum++;
}
// Remove first element in current row array
notesArray[rowNum].shift();
rowNum++;
}
// Remove first element in array
notesArray.shift();
JSON.stringify(notesArray); // Added per an answer here
console.log('Final notesArray: ' + $.toJSON(notesArray));
$.ajax({
data: {saveTaskNotes: 'true', userID:userID, siteID:siteID, taskTable:tableID, notes:notesArray},
success: function(data) {
console.log('Save task notes data: ' + data);
}
});
The "Final notesArray" console output looks fine, but now, with stringify added, the function above (PopulateTaskTableWithNotes) console output shows that it's reading through every character in the array as a separate element!
Maybe this will help too, as far as what's happening to the data between the creating and reading functions: the array is being saved to a single MySQL database field and then retrieved for the PopulateTable function via $.ajax() (on both ends).
Having said that, do I need to look at what I'm doing with/to the array in the PHP code?
UPDATE #3
Here's the PHP function that takes the data in and writes to the MySQL db:
function SaveTaskNotes($userID,$siteID,$taskTable,$notes) {
$notes = json_encode($notes);
$insertUpdateTaskNotesResult = '';
$insertTaskNotes = "INSERT INTO userProgress (userProgressUserID,userProgressSiteID,userProgressNotesTable,userProgressNotes) values ($userID,$siteID,'" . $taskTable . "','" . $notes . "')";
$log->lwrite('$insertTaskNotes: ' . $insertTaskNotes);
$resultInsertTaskNotes = #mysqli_query($dbc,$insertTaskNotes);
if ($resultInsertTaskNotes) {
$insertUpdateTaskNotesResult = 'insertTaskNotesSuccess';
} else {
if (mysqli_error($dbc) != '') {
$log->lwrite('INSERT TASK NOTES: An error occurred while attempting to add the task notes. Query: ' . $insertTaskNotes . ', mysqli_error: ' . mysqli_error($dbc));
}
$insertUpdateTaskNotesResult = 'insertTaskNotesFail';
}
echo $insertUpdateTaskNotesResult;
}
And here's the function that gets the data from the db and sends it to the above $.ajax function:
function GetUserTaskNotes($userID,$siteID,$taskTableID) {
$queryGetUserTaskNotes = "SELECT userProgressNotes FROM userProgress WHERE userProgressUserID = $userID AND userProgressSiteID = $siteID AND userProgressNotesTable = '" . $taskTableID . "'";
$log->lwrite('$queryGetUserTaskNotes: ' . $queryGetUserTaskNotes);
$resultGetUserTaskNotes = #mysqli_query($dbc,$queryGetUserTaskNotes);
if ($resultGetUserTaskNotes) {
$taskNotes = mysqli_fetch_assoc($resultGetUserTaskNotes);
$log->lwrite('Retrieved $taskNotes[\'userProgressNotes\']: ' . $taskNotes['userProgressNotes']);
echo $taskNotes['userProgressNotes'];
} else {
if (mysqli_error($dbc) != '') {
$log->lwrite('GET TASK NOTES: An error occurred while attempting to retrieve the task notes. Query: ' . $queryGetUserTaskNotes . ', mysqli_error: ' . mysqli_error($dbc));
}
echo 'getTaskNotesFail';
}
}
In both the save and get functions the $log output shows that the array never changes (with the above js/php code) and pasting the array in to notepad++ shows that the CR/LF is still there throughout.
Don't use JSON.parse, the data is already JSON and Javascript can work with it.
You only need it when passing a string, imagine JSON.parse() beeing like string2json().
I think this might already be a solution to your problem, I've never had issues with new line characters.
As Luis said, the problem is not your client (Javascript, jQuery), besides the JSON.parse, but the providing site is wrong.
Example for PHP:
<?php
echo json_encode(array("test" => "
x"));
PHP properly escapes the characters:
{"test":"\r\n\r\n\r\nx"}
But the source of your data is providing malformed JSON.
To fix the JSON issue, either use prepared statements or use:
$notes = str_replace('\', '\\', json_encode($notes)); // in SaveTaskNotes
Well, the error is on the input data (showed in question). You can't have an CR or LF inside a literal in a JSON string. What you can have are that chars escaped as \r \n. The problem is on other side, where escaped codes are replaced by actual chars and therefore the full JSON string becomes invalid.
I try to parse an XML string and have some problems. Here is my current state.
I have a Cordova app which reads QR-Codes (with the BarcodeScanner plugin). The QR-Code holds the XML information. When I read the code, I want to print out the XML code. Here is what I tried (the important part):
var app = {
output: null,
xmlDoc: null,
// this function is called when I click a button
scanCode: function(){
//first parameter is a callback, which is called when a barcode is detected
cordova.plugins.barcodeScanner.scan(
function (result) {
alert(result.text);
var parser = new DOMParser();
**app.xmlDoc = parser.parseFromString(result.text,"text/xml");**
app.output = document.getElementById("codeInfo");
app.traverse(app.xmlDoc.documentElement, "");
},
function (error) {
alert("Scanning failed: " + error);
}
);
},
traverse: function(node, offset){
if(node.nodeType == 3){
app.output.innerHTML += "<b>" + offset + node.nodeValue + "</b><br>";
}else{
app.output.innerHTML += offset + node.nodeName + "<br>";
var childs = node.childNodes;
for(var i=0; i<childs.length; i++){
app.traverse(childs[i], offset + " ");
}
}
}
};
My XML code looks something like this
<node><child1>text1</child1><child2>text2</child2></node>
So I expect an output like:
node
child1
text1
child2
text2
But I always get something like:
html
body
parsererror
h3
This page contains the following errors:
...
When I use a static text like
var xml = "<node><child1>text1</child1><child2>text2</child2></node>"
and use this instead of 'result.text' in the marked line, everything works as expected.
So maybe the 'result.text' is just a reference and not the value? Could this be the problem? I'm not an expert so how can I solve this problem?
P.S.: The XML code I get from the QR-Code is correct and well formed.
app.xmlDoc = parser.parseFromString(result.txt,"text/xml");
should actually be:
app.xmlDoc = parser.parseFromString(result.text,"text/xml");
There is an "e" missing in result.text
After reading Valencia's comment and the "wrong" output again and think about it, I figured out what's wrong. So the "wrong" output is just an error message in HTML format, where i print every tag. The message itself says:
This page contains the following errors:
error on line 1 at column 14: String not started expectin ' or "
The beginning should look like this
<?xml version="1.0" encoding="UTF-8"?>
but when creating the QR-Code backslashes are added
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
The first backslash is at column 14.
When I create a static XML string I insert backslashes to mask the ' " ', so my declaration and the XML code from the QR-Code look equal. But they aren't, cause the static XML string does not contain the backslashes. And these backslashes cause the error while parsing.
The easiest solution is to just not put the XML information in the QR-Code. So directly starting with the first node.
Thanks for your help.
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 />"?