Abhinav Konda Abhinav Konda - 5 months ago 23
jQuery Question

How to pass a string containing back slash and front slash from PHP query page back to JavaScript using AJAX

Here I am retrieving values of database using AJAX and PHP. I stored the path of images like photos/image1.jpg in database. While retrieving that data from database and sending them back that data is not getting printing back as it has backslashes or fronth slashes in them. So what is the process to send that data back to main pages which contain special characters while using AJAX?

My JavaScript code:

function getdata(eve)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{


document.getElementById("grayscreen").innerHTML=xmlhttp.responseText;
} }
xmlhttp.open("GET","picdetails.php?q="+eve,true);
xmlhttp.send();


My PHP code

<?php
include 'config.php';
$query2="select * from Sampletable where sublabel= '".$_GET['q']."'";
$query=mysql_query($query2);

if(mysql_num_rows($query)>0)
{
$count=0;
while($res= mysql_fetch_array($query))
{
if($count==0)
{
$ans= "<img src=". $res['image']."\>";
echo $ans;
}
else {
echo "<img src=".$res['image']." style='display:none'/>";
}
$count=$count+1;
}
}
?>


Here $res['image'] is the path of image which is like images/image1.jpg which will be retrived from database.

Output in the screen is

"<img src="\\">"<img src="style='display:none'/">


But output is supposed to be

<img src="images/images1.jpg"/> <img src="images/images2.jpg" style='display:none'/>


The problem is the data which is retrieved from are images/images1.jpg and images/images2.jpg which is not getting echoed back as it has front slash in it.

How to print that data?

Answer

Change:

$ans= "<img src=". $res['image']."\>";

To:

$ans= '<img src="'. $res['image'] .'"/>';

This should work.

Hope it helps!