Forum Moderators: open
I have a problem whereby I cannot get the response from my php script to parse in my Javascript.
It goes:
"Do php - make a response
e.g. $response = 'test<br /><a href="test.php">Test</a>';
Now I do:
echo 'doFunc(\''.$response.'\')';
In the ajax, the responseText is eval'd.
So it is now doing the function doFunc(e) {
}
However, I get the error "unterminated string literal". I have tried urlencoding the php variable and unescaping it in javascript, but that doesn't work.
Is there anyway I can encode the response in php and unencode it in my javascript?
I think.
This line:
echo 'doFunc(\''.$response.'\')';
Seems to have a strange collection of single/double quotes. Should it be like this?
echo 'doFunc("'.$response.'"');'; Assuming . is used for string concatenation, same as Perl?
It's because when you send, for example, form data to a URL via get, the space character is substituted with '+' and not escaped to %20. This would be much easier but hey I didn't invent it. You'll have to substitute the '+'s then unescape the string.
You can see this in action, go to Google and search for "escape my+string". Now look in the address bar and you'll see it's been escaped to "escape+my%2Bstring".
You have to put the spaces back before you unescape, if you didn't this example would be unescaped to "escape my string" and you've lost the '+' that was actually supposed to be there.
There's no other exceptions that I have ever encountered.
Hope this is helpful.
php does:
echo 'doShowOldNote(\''.$id.'\',\''.urlencode($response).'\',\''.$date.'\')';
Javascript does:
eval(obj.responseText);
Then:
function doShowOldNote(id,r,date) {
r=unescape(r);
// $('') gets the element
$('tNotes').value = r.replace(/\+/,' ');
// etc
Should I do the escaping etc at the eval?
function doShowOldNote(id,r,date) {
var val = r.replace(/\+/,' ');
// $('') gets the element
$('tNotes').value = unescape( val);
...
...
Otherwise if you have +'s in your text, these will be changed to ' '.
But apart from that it's fine.
Do this.....
function doShowOldNote(id,r,date) {
var val = r.replace(/\+/,' ');
$('tNotes').value = unescape( val);alert( "before: "+ r +"\nafter"+ $('tNotes').value);
...
...
That should give you a popup of the text before and after. Before you should see escape characters, like %20 is a space, %2C is a comma, etc.... After these should have been replaced with actual characters.
Please post the strings here so I can have a look.
var val = r.replace( /\+/g,' ');
The 'g' on the end makes it do it through the entire string, left to itself it only does it once.
Also, the %0A's are linebreaks, for these to work in HTML they'll need to be changed to <br>'s.
Use this regex in addition to the other one....
val = val.replace( /(%0D)?%0A/g, "<br>");
That will account for %0D's too as Win32 systems use %0D%0A for newlines.
Has that now sorted it?