parsing new lines in jquery - javascript

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 />"?

Related

Text with line breaks returns \r\n in text through Ajax/JavaScript

Code that works fine except for the issue of passing a value back and forth between JavaScript, Ajax, and PHP. Using TinyMCE as the editor, when I add a paragraph break in the text, save the data (passing it through JavaScript/Ajax and PHP to do so) the text appears to be okay. Here's the JavaScript and Ajax code -- this works, it passes the data correctly to the PHP program when the submit button is clicked:
// save the main who's who form data:
$("form#who_main").submit(function(e)
{
e.preventDefault();
// first thing, clear out the message div used for this (if there's anything there):
document.getElementById("who_message").innerHTML = "";
// because we're using TinyMCE, need to replace value in that into the textarea
// so that when JavaScript gathers the formData it is getting it from the textarea
// controls (it doesn't know what to do with TinyMCE):
var shortbio = tinymce.get('shortbio').getContent();
document.getElementById( "shortbio" ).value = shortbio;
var user_notes = tinymce.get('user_notes').getContent();
document.getElementById( "user_notes" ).value = user_notes;
var admin_notes = tinymce.get('admin_notes').getContent();
document.getElementById( "admin_notes" ).value = admin_notes;
// this loads all the controls of the form rather than doing one at a time and fumbling
// with the file object ...:
var formData = new FormData(this);
// ajax call to attempt to upload and save the image:
$.ajax
({
type: "POST",
url: "<?php echo $History_html_RootPath; ?>admin/AjaxCalls/who_update_main_save.php",
data: formData,
dataType: "json", // return value is json array
processData : false,
contentType: false,
success: function(data)
{
// need to see if we have an error, if so, display it, otherwise,
// we should hopefully have success ...
if ( data[0].toLowerCase().includes( "error" ) )
{
var errormsg = "<div class='alert alert-danger'>"+data+"</div>";
document.getElementById("who_message").innerHTML = errormsg;
return;
}
else
{
// success!
// update things on screen, so we don't get confused using the data array returned
// from PHP:
document.getElementById("namecode").value = data[0];
document.getElementById("region").value = data[1];
document.getElementById("local").value = data[2];
document.getElementById("preferredtitle").value = data[3];
document.getElementById("shortbio").value = data[4];
tinymce.get('shortbio').setContent( data[4] );
document.getElementById("headshotphoto").value = data[5];
document.getElementById("photographername").value = data[6];
document.getElementById("photographerlink").value = data[7];
document.getElementById("user_notes").value = data[8];
tinymce.get('user_notes').setContent( data[8] );
document.getElementById("admin_notes").value = data[9];
tinymce.get('admin_notes').setContent( data[9] );
// clear out the upload file control:
//document.getElementById("headshotphoto").value = "";
// change the message:
var message = "<div class='alert alert-success'>";
message += "<b>Success!</b> This data has been updated in the <i>holding</i> table.";
message += "</div>";
document.getElementById("who_message").innerHTML = message;
return;
}
} // end success
}); // end ajax call
}) // end of code associated with who_main submit
The PHP file receives the data via post, and I use the PHP function mysqli_real_escape_string() to deal with issues. The one problem with doing this is that it appears to insert backslashes for quotes (single and double), and so on. I just had a thought that might be the cause of the problem, and that is the use of this function, I am not sure. I will test it, but in the meantime. ... I save the data to the table and all is good. If there's a paragraph break, the proper tags are saved out into the table.
<p>Some text</p><p>More text 'quoted text'</p>
When I pass the data back using JSON encoding:
$returndata = array();
$returndata[0] = $namecode;
$returndata[1] = $region;
$returndata[2] = $local;
$returndata[3] = $preferredtitle;
$returndata[4] = $shortbio;
$returndata[5] = $photo_file;
$returndata[6] = $photographername;
$returndata[7] = $photographerlink;
$returndata[8] = $user_notes;
$returndata[9] = $admin_notes;
// done-done:
echo json_encode( $returndata );
return;
The code above (the javascript/Ajax code) comes back looking like:
<p>Some text</p>\r\n<p>More text \'quoted text\'</p>
I need to not have the \r\n and \' (or \") showing up in my text. If I were to save it again like that it gets weirder as the backslashes get duplicated and more. I am sure there's some thing I am missing, but I don't know what it is. This is making me crazy because everything else works exactly as I need it to.
NOTE Added code that I have attempted to use, in PHP, to deal with "escapes", it works for single and double quotes, but not for the \r\n characters -- instead it just strips out the backslash:
function remove_escapes( $string )
{
$string = str_replace ( "\'", "'", $string ); // convert single quote
$string = str_replace ( "\"", """, $string ); // convert double-quote
$string = str_replace ( "\r\n", "", $string ); // remove \r\n
$string = str_replace ( "\\", "", $string ); // remove slash
// anything else giving us heartburn?
return $string;
} // eof: remove_escapes()
If I use this with the json array, I get the letters rn inserted between paragraphs:
$returndata[8] = remove_escapes( $user_notes );
$returndata[9] = remove_escapes( $admin_notes );
maybe doing something like data.replace(/\n/g, '<br>') this will replace all newline markers with the html newline or data.replace(/\\n/g, '<br>') to look for the characters rather than a newline marker
I have done some testing to examine the data and it appears to be happening because of the mysqli_real_escape_string() function when I get the data from the $_POST() array. If I take that out, I am not getting the \r\n codes. So perhaps the jquery post is passing things in a way I don't need that function? Further testing on the three different text controls shows it working without the need to use mysqli_real_escape_string, and I have some extra functionality to deal with looking for JavaScript and such in the text, so I may be able to simplify the code. Unless someone can tell me a reason not to do this ...?
The mysqli_real_escape_string() is there so that special characters are escaped, this helps prevent hacking attacks like sql injection.
It appears that the only solution I can find is to continue with mysqli_real_escape_string(), but when passing the information back, after saving the changes, re-load the data from the table, which does not display the escape characters and therefore avoids the issue. It seems like a lot of extra data processing, but it's only ever (in my code) one row at a time that is being passed back and forth.

JSON string returns NAN

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.

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!'); }
});
}
}

Python csv.reader() to JS?

I have a python code such as :
import csv
reader = csv.reader(open('myText.txt', 'r'), delimiter=",")
for row in reader:
print row[0] + 'is' + row[1] + '</br>'
I look for a similar action/code[1] in JS or JQuery. The name of this action is welcome too. I'am exploring JS and wondering if there is a way do get an online/offline csv, parse it, iterate, inject some HTML in my website accordingly.
[1]: more precisely I look for a JS translation of reader = csv.reader(open('myText.txt', 'r'), delimiter=",") , I can manage the rest.
Note: myText.txt will be this online file
For the given CSV file, I think something like this should suffice (which uses only jquery):
$.get('/path/to/pinyinipamapping.csv')
.done(function(csvData) {
var body = $('body');
csvData.split(/\r\n|\n/).forEach(function (rowStr) {
if (rowStr[0] != '#') {
var row = rowStr.split(',');
body.append('<p>' + row[0] + 'is' + row[1] + '</p>');
}
});
});
However, this will not work for quoted commas, etc.
For a more complete CSV parsing look at Javascript code to parse CSV data which uses code from this blog post. Also, you can consider the jQuery-csv library, though it is in beta.
For a quick and simple file it could be something like this: (Code inspired by this answer)
// Put here the url to the file
url = "https://raw.github.com/cburgmer/cjklib/master/cjklib/data/pinyinipamapping.csv";
$.ajax({
type: "GET",
url: url,
dataType: "text",
success: function(data) {processData(data);}
});
function processData(allText) {
// Get an array of lines
var allTextLines = allText.split(/\r\n|\n/);
// Get the number of columns using the first row
var entries = allTextLines[0].split(',');
var lines = [];
// while there are elements in the row
while (entries.length>0) {
// remove that line, split it and store in our array
lines.push(entries.shift().split(','));
}
// Now do your stuff with the array lines
}

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});

Categories