Reputation: 109
I'm trying to display image in HTML from MySql and PHP.
My ajax request
$.ajax({
type : "POST",
url : "jsonajax.php",
data : { id: id },
success : function(data){
alert(data);
$('#dialog').dialog('open');
$('#dialog').html('<img src='+ data + '" />');
}
});
My jsonajax.php
$id = $_REQUEST['id'];
$sql = "SELECT img_url FROM table_name WHERE id = $id";
$res=$obj->_executeQuery($sql);
$res=$obj->getAll($res);
echo json_encode($res);
Now the alert(data)
looks like
[{"img_url":"images\/Jellyfish.jpg"}]
I need to remove '\' and append the image src to display.
Upvotes: 0
Views: 2712
Reputation: 783
Make the ajax block like this (In your case):
$.ajax({
type : "POST",
url : "jsonajax.php",
data : { id: id },
dataType: 'json',
success : function(data){
console.log(data);
$('#dialog').dialog('open');
$('#dialog').html('<img src=' + data[0].img_url + '" />');
}
});
Hope this helps.
Note: Please do make sure that the image is located in the images
folder from the the current Script.
Upvotes: 0
Reputation: 1004
Add dataType:"json"
$.ajax({
type : "POST",
dataType: "json",
url : "jsonajax.php",
data : { id: id },
success : function(data){
alert(data);
$('#dialog').dialog('open');
$('#dialog').html('<img src='+ data + '" />');
}
});
And then do data.img_url
Upvotes: 0
Reputation: 657
You need to convert the string response to an object - which will automagically remove the slashes :)
Option 1: Parse the data with JSON.parse(data)
Option 2: You can specify the dataType: 'json'
option in your $.ajax
request.
$.ajax({
type : "POST",
url : "jsonajax.php",
data : { id: id },
dataType: 'json', // This is what you're missing
success : function(data){
$('#dialog').html('<img src='+ data.image_url + '" />');
$('#dialog').dialog('open');
}
});
Checkout the dataType option on the docs: http://api.jquery.com/jquery.ajax/
Upvotes: 0