Reputation: 13
I have some php and javascript, everythings work and I do not get any error message. I can post data without any error to database. And everythings looks good but I cannot use some function in php.
Example.
I have a textarea and I send its data with ajax to a php file. In php file a need to use str_replace function. I can insert data to database in same php file without any error but the function that I try to use like str_replace or mysqli_real_escape_string, etc. do not work.
What would be the reason?
Here codes.
$(".editBoxButton").click(function(){
var yazi = jQuery('#editInput').val();
$.ajax({
type: 'POST' ,
url : 'ajax/editEntry.php',
data: {
text: yazi,
},
success : function(d){
alert(d);
location.reload(); //refresh
}
});
});
ajax/editEntry.php
<?php
$yeniyazi=$_POST['text'];
$yeniyazi = str_replace("\n", "<br>", $yeniyazi);
$s=$yeniyazi;
echo json_encode($s);
?>
in the alert, I get still \n. it does not replaced.
I do not get any error. only str_replace do not work that is my problem. expect str_replace, it works properly.
Upvotes: 1
Views: 109
Reputation: 347
I also have problem with \n
using in javascript and PHP.
Current Env.:
PHP 5.3.10
Javascript
XHTML 1.0
The problem:
....
if (rowcount == 5) {
openShipments += '\n';
rowcount = 0;
}
....
It works when using \\n
bellow:
....
if (rowcount == 5) {
openShipments += '\\n';
rowcount = 0;
}
....
Upvotes: 0
Reputation: 942
i hope this example help you:
<?php
// Order of replacement
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = '<br />';
// Processes \r\n's first so they aren't converted twice.
$newstr = str_replace($order, $replace, $str);
// Outputs F because A is replaced with B, then B is replaced with C, and so on...
// Finally E is replaced with F, because of left to right replacements.
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
// Outputs: apearpearle pear
// For the same reason mentioned above
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
?>
Upvotes: 1
Reputation: 2319
Actually, you have to escape the \ with another one or use singlequotes instead.
$val = str_replace("\\n" , "<br>", $val);
Or you can do it in a single line like this :
<?php
echo json_encode(nl2br($_POST['text']));
Upvotes: 1
Reputation: 7243
You should probably just do:
$yeniyazi = nl2br($yeniyazi);
If you really want to manually replace, use regex.
$yeniyazi = preg_replace("/\r?\n/s", "<br />", $yeniyazi);
Upvotes: 1