I am using this bit of PHP to return a chunk of html:
if ($action = "update")
{
connect_db();
$query = mysql_query("SELECT * FROM convo ORDER BY date ASC") or die (mysql_error());
while($row = mysql_fetch_array($query))
{
$output = $output . '<p>';
$output = $output . '<b>From:</b> ' .$row['from'];
$output = $output . ' <b>To:</b> ' .$row['to'];
$output = $output . ' <b>Message:</b> ' .$row['content'];
$output = $output . "<br />";
$output = $output . '</p>';
}
//htmlentities($output);
header('Content-Type: application/json');
echo json_encode( $output );
}
And then insert it into a <div> with this bit of jQuery:
function update(){
$.ajax({
type: "GET",
url: "actions.php",
data: {
'action': 'update'
},
dataType: "json",
success: function(data)
{
console.log('update called');
console.log( data);
$('#history').text( data );
//$('#status').text('sent!');
}
});
setTimeout(update, 5000);
}
The ajax call works and returns the correct html however when inserted it is not formatted, I can see all the html code in the browser. See example picture:
Should be using something other than .text?
You are creating JSON in php, and using json dataType for no reason when you want html.
Just output the html string in php and remove the dataType:'json from AJAX.
echo $output ;
Then instert using html() method
$('#history').html( data );
The load() method is ideal for your case. It is a $.ajax shortcut method. You could replace all the AJAX you have with:
$('#history').load("actions.php", { 'action': 'update'},function(){
console.log('new content inserted now')
})
API reference: http://api.jquery.com/load/
change $('#history').text( data ); to $('#history').html( data );
Related
I am making a commenting reply system in PHP jquery and Ajax. So far I managed to make the commenting and reply to comment action with php and jquery ajax. When I reply to a comment, i receive back from the jquery ajax the number of replies to a comment and i print the number on the screen. Now what i want to do next is printing the reply to the screen after it was submitted. I made the jquery ajax function and wrote my php script. Then I echo the $output formated from the php back to the ajax. The problem is i am receiving blank response nevertheless i tested the php file directly and it is working perfectly and outputting to the screen the $output variable. Please help. Here is my ajax part that takes care of the output replies :
<script type="text/javascript">
load_replies();
function load_replies() {
$.ajax({
url: "widgets/board_reply_fetch.php?comment_id=<?php echo
$board_comment_id_number;?>",
method: "POST",
success: function(data){
$("#reply_comment").html(data);
console.log(data);
}
});
}
</script>
and here is my php file :
<?php
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
if (isset($_GET["comment_id"])) {
$comment_id = (int)$_GET["comment_id"];
$reply_data = find_board_replies_by_comment_id($comment_id);
$output = "";
$output_array = array();
while ($reply_assoc = mysqli_fetch_assoc($reply_data)) {
$reply_comment_id = $reply_assoc['comment_id'];
$reply_board_id = $reply_assoc['board_id'];
$reply_user_id = $reply_assoc['user_id'];
$reply_text = $reply_assoc['reply'];
$reply_timestamp = $reply_assoc['reply_timestamp'];
$reply_user_data = find_user_data_by_id($reply_user_id);
$profile_image = $reply_user_data['profile_picture'];
$profile_image_thumb = "../uploaded_pictures/profile/$reply_user_id/" . $reply_user_id . "small.png";
if ($profile_image == "") {
if ($comment_user_data['gender'] == "Male"){
$user_profile_picture = "../images/ProfilePicMale.png";
} else {
$user_profile_picture = "../images/ProfilePicFemale.png";
}
} else {
$user_profile_picture = $profile_image_thumb;
}
$full_name = ucfirst(htmlentities($reply_user_data['first_name'])) . " " . ucfirst(htmlentities($reply_user_data['last_name']));
$time_of_post = time_of_post($reply_timestamp);
$the_reply_text = nl2br($reply_text);
$output = "<div class=\"reply_comment_div\">";
$output .= "<a href=\"profile.php?user_id=$reply_user_id\" class=\"board_comments_div_picture\">";
$output .= "<img src=\"$user_profile_picture\" width=\"50px\" height=\"50px\" /></a>";
$output .= "$full_name";
if ($reply_user_id == $_SESSION['user_id']){
$output .= "Edit";
$output .= "Delete";
}
$output .= "<div class=\"board_comment_submited_on\">submitted $time_of_post</div>";
$output .= "<span class=\"comment_content_span\">$the_reply_text</span>";
$output .= "</div>";
$output_array[] = $output;
}
foreach ($output_array as $array) {
echo $array;
}
}
?>
try to store you data that is being sent to php page in data object
example:
<script type="text/javascript">
load_replies();
function load_replies() {
var commment_id = "<?php echo $board_comment_id_number;?>";
$.ajax({
url: "widgets/board_reply_fetch.php",
data:{commentId:commment_id },//commment_id store it here
method: "GET",
success: function(data){
$("#reply_comment").html(data);
console.log(data);
}
});
}
</script>
Use POST METHOD:
if (isset($_POST["comment_id"])) {
$comment_id = (int)$_POST["comment_id"];
I have a form that adds clients to a database clients/add_client. The add_client method has a parameter of $state which is passed to another method list_centers(). When someone is talking to a potential client, they have all of our centers in a sidebar. There is a <select> above the list of centers in which lists the states where we have centers. When they change the select to another state, it should list all of the centers in that state. Now, I have this working by passing the parameter in the URL like this: localhost/clients/add_clients/GA lists all of the centers in Georgia. The problem is that I want to do this with AJAX and not have the page refresh. I cannot figure out how to pass this data via ajax. I know that I have to reconstruct the list each time but I am stuck. Here is what I have tried:
$('#center_select').change(function(){
var data = $(this).val();
var url = 'add_client/' + data;
$.ajax({
type: 'POST',
dataType: 'html',
data: data,
url: url,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
return false;
});
Just in case you need the method:
public function add_client($state = false) {
$this->load->model('centers_model');
$data = array(
'page_title' => 'Add Client',
'client_status' => $this->clients_model->list_client_status(),
'centers' => $this->centers_model->list_centers(null, $state),
'center_states' => $this->centers_model->list_center_states(),
);
$this->load->view('header');
$this->load->view('clients/add_client', $data);
$this->load->view('footer');
}
View:
<div class="col-sm-3">
<aside id="centers_sidebar" class="well">
<h2>List of Centers</h2>
<select class="form-control" name="center_select" id="center_select">
<option value="all">All</option>
<?php
foreach ($center_states as $center_state) {
echo '<option value="' . $center_state->center_state . '">' . $center_state->name . '</option>';
}
?>
</select>
<ul id="center_list">
<?php
foreach ($centers as $center) {
$output = '<li class="center">';
$output .= '<h5>' . $center->center_name . '</h5>';
$output .= '<p>' . $center->center_type . '</p>';
$output .= '<p>' . $center->center_city . ', ' . $center->center_state . '</p>';
$output .= '<p>' . $center->center_phone . '</p>';
$output .= '</li>';
$output .= '<hr>';
echo $output;
}
?>
</ul>
</aside>
</div>
I failed to notice that you request a POST but setup for a GET. So here we supply the proper structure to ajax.data
select handler
$('#center_select').change(function () {
var st = $(this).val();
var url = 'update_centers';
$.ajax({
type: 'POST',
dataType: 'html',
data: {state: st},
url: url,
success: function (data) {
console.log(data);
$("#center_list").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
//useful for trouble shooting & error handling
console.log(textStatus, errorThrown);
}
});
return false;
});
AJAX responder method - builds html to send back to ajax.success
We need to pull the input from $_POST (using input->post)
I've put in a bunch of validity checks and a general purpose ajax error response function too. No extra charge.
function update_centers()
{
$this->load->model('centers_model');
$state = $this->input->post('state');
if(!isset($state))
{
$this->ajax_bad_request_error("No state data received");
return;
}
$centers = $this->centers_model->list_centers(null, $state);
if(!isset($centers))
{
$this->ajax_bad_request_error("The database failed to find centers in $state");
return;
}
$output = "";
foreach($centers as $center)
{
$output .= "<li class='center'><h5>$center->center_name</h5>"
."<p>$center->center_type</p>"
."<p>$center->center_city, $center->center_state</p>"
."<p>$center->center_phone</p></li><hr>";
}
echo $output;
}
function ajax_bad_request_error($msg)
{
//All purpose reporting of ajax failure
header('HTTP/1.1 400 Bad Request');
header('Content-Type: application/json; charset=UTF-8');
$data = array('type' => 'error', 'message' => $msg);
echo json_encode($data);
}
Cannot guarantee this will work perfectly as is - syntax errors may exist. But the concept is sound.
I have a problem when trying to select the <li> inside a <ul> list from an ajax response using jQuery.html();
This is my AJAX request:
if (searchid != '') {
$.ajax({
type: "POST",
url: "/service/search.php",
data: dataString,
cache: false
}).done(function (html) {
$("#result").html(html).show();
var images = $("#result").find(".dbRows.sixth").html();
console.debug(images);
})
.fail(function (jqXHR, textStatus) {
$("#explainMessage").html('Unable to check at the moment. Please retry later').show();
})
}
return false;
and in php I have this code:
if ( mysqli_num_rows($result)==0)
{
$display = '<div id="explainMessage" class="explainMessage">Sorry, this was not found.</div>';
echo $display;
} else {
$counter = 0;
while ($row = $result->fetch_assoc()) {
++$counter;
$image_filename = $row['image_filename'];
$imageFolder = $_SERVER['DOCUMENT_ROOT'] . '/service/img/';
$imageList = scandir($imageFolder, 1);
$imageLink = '/service/img/' . $image_filename;
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $image_filename);
$pattern = '/^(' . quotemeta($withoutExt) . ').*$/';
$display = '<div class="dbRows sixth" style="display:none"><ul>';
foreach ($imageList as $image) {
if (preg_match($pattern, $image)) {
if (in_array($image, $imageList)) {
$display .= '<li><img src="' . $imageLink . '" /></li>';
}
}
};
$display .= '</ul></div>';
echo $display;
the problem is that when I try to use the AJAX.done(); function, in my console I have just <ul></ul> without the list of images.My question is, why i can't select the code inside the <ul> tags even if the list of images is actually in the code? I'm pretty new with PHP, any help will be really appreciated. Thanks in advance.
You are doing it wrong. As I doubt before asking you for response HTML, you have blank `'.
$("#result").find(".dbRows.sixth").html() will print html for first matched element only.
Try this, if you want to fetch html for all matched element:
$("#result").find(".dbRows.sixth").each(function(){
console.log($(this).html());
});
From a quick look I can see a few problems. In your php change your first line of code from <div class="dbRows sixth" style="display:none"><ul>'; to $display = '<div class="dbRows sixth" style="display:none"><ul>';
I'd probably change this: var images = $("#result").find(".dbRows.sixth").html(); to this: var images = $("#result > .dbRows.sixth");.
Then add images.show(); and console.log(images.html());. Not tested but might get you on the right track.
I am trying to map traceroutes to google maps.
I have an array in php with traceroute data as
$c=ip,latitude,longitude, 2nd ip, its latitude, longitude, ....target ip, its lat, its lng
I used json_encode($c, JSON_FORCE_OBJECT) and saved the file
Now, how do I access this using javascript, by directly equating it to new JS object?
earlier I used to have a data format like this on harddrive
var data12 = {
"route":[
{
"ip": "some ip",
"longitude": "some lng",
"latitude": "some lat",
.....
and in my javascript it was used as
data=data12.route;
and then simply acces the members as data[1].latitude
I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.
For parsing JSON, simply do
var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );
You can now access everything easily:
alert ( obj.name );
Note: jQuery uses the browser's native JSON parser - if available - which is very quick and much safer then using the eval () method.
Edit: To get data from the server side to the client side, there are two possibilities:
1.) Use an AJAX request (quite simple with jQuery):
$.ajax ( {
url: "yourscript.php",
dataType: "json",
success: function ( data, textStatus, jqXHR ) {
// process the data, you only need the "data" argument
// jQuery will automatically parse the JSON for you!
}
} );
2.) Write the JSON object into the Javascript source code at page generation:
<?php
$json = json_encode ( $your_array, JSON_FORCE_OBJECT );
?>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );
//]]>
</script>
I know this is old, but I recently found myself searching for this. None of the answers here worked for my case, because my values had quotes in them. The idea here is to base64 encode the array before echo'ing to the page. That way the quotes don't conflict.
< ?php
$names = ['first' => "some'name"];
?>
var names = JSON.parse(atob('< ?php echo base64_encode(json_encode($names)); ?>'));
console.log(names['first']);
I could get the JSON array by using PHP's json_encode() from backend like this example:
<!doctype html>
<html>
<script type="text/javascript">
var json = <?php echo json_encode(array(1 => '123', 'abc' => 'abd', 2 => 5));?>;
console.log(json[1]);
console.log(json.abc);
</script>
</html>
No quotation marks means an eval() of whatever was printed out. This is a quick hack that we utilised often to quickly add initial values to our AJAX page.
no need for jquery, just:
var array= <?php echo json_encode($array); ?>;
console.log(array->foo);
we have to display the json encode format in javascript , by using below one:
var responseNew = JSON.parse(' {"name" : "John"} ' );
alert(responseNew['name']);
This function works for you I guess:
function json_encode4js($data) {
$result = '{';
$separator = '';
$count = 0;
foreach ($data as $key => $val) {
$result .= $separator . $key . ':';
if (is_array($val)){
$result .= json_encode4js($val).(!$separator && count($data) != $count ? ",":"");
continue;
}
if (is_int($val)) {
$result .= $val;
} elseif (is_string($val)) {
$result .= '"' . str_replace('"', '\"', $val) . '"';
} elseif (is_bool($val)) {
$result .= $val ? 'true' : 'false';
} elseif (is_null($val)) {
$result .= 'null';
} else {
$result .= $val;
}
$separator = ', ';
$count++;
}
$result .= '}';
return $result;
}
$a = array(
"string"=>'text',
'jsobj'=>[
"string"=>'text',
'jsobj'=>'text2',
"bool"=>false
],
"bool"=>false);
var_dump( json_encode4js($a) ); //output: string(77) "{string:"text", jsobj:{string:"text", jsobj:"text2", bool:false}, bool:false}"
var_dump( json_encode($a));//output: string(85) "{"string":"text","jsobj":{"string":"text","jsobj":"text2","bool":false},"bool":false}"
HTML
<select name="sub" id="subcat" class="form-control" required="required">
</select>
PHP
$this->load->model('MainModel');
$subvalue = $this->MainModel->loadSubData($var);
echo json_encode($subvalue);
//if MVC
// or you can just output your SQLi data to json_encode()
JS
$("#maincat").change(function(){
var status = this.value;
$.ajax({
type: 'POST',
url: 'home/subcat/'+status,
success: function(data){
var option = '';
var obj = JSON.parse(data);
if(obj.length > 0){
for (var i=0;i<obj.length;i++){
option += '<option value="'+ obj[i].id + '">' + obj[i].name + '</option>';
}
//Now populate the second dropdown i.e "Sub Category"
$('#subcat').children("option").remove();
$('#subcat').append(option);
}else{
option = '<option value="">No Sub Category Found</option>';
$('#subcat').children("option").remove();
$('#subcat').append(option);
}
},
error: function(){
alert('failure');
}
});
I have an ajax script, which I kinda understand, but still need some extra help.
$('.images').click(function(){
var imageId = $(this).attr('id');
alert(imageName);
$.ajax({
type: "get",
url: "imageData.php",
dataType: "json",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
alert(imageId);
$("#images_"+imageId).html(data);
}
});
//$('#images_'+imageId).toggle();
});
I have that code, it goes to this imageData.php file
<?php
if(isset($_GET)){
$images = "";
$path = 'img/';
$imageId = $_GET['getImageId'];
$sql = mysql_query("SELECT * FROM images WHERE iID = '".$imageId."'");
while($row = mysql_fetch_array($sql)){
$images .= $path.$row['images'];
}
$json = json_encode($images);
?>
<img src='<?php echo $json;?>'/>
<?php
}
?>
Why does it output error when I try to echo a string from $images, but it outputs correctly when I do echo $imageId;? I'm trying to output something from mysql, but not trying to output just the id.
Need help please, thank you
You don't need use json_encode here, there is not data that needs to be in JSON format. There is also no reason to loop over the result set, if the query only returns one image.
Try this:
<?php
if(isset($_GET['getImageId'])) {
$path = '';
$imageId = mysql_real_escape_string($_GET['getImageId']); // SQL injection!
$result = mysql_query("SELECT images FROM images WHERE iID = '".$imageId."'");
$row = mysql_fetch_array($result);
if($row) {
$path = 'img/' . $row['images'];
}
}
?>
<?php if($path): ?>
<img src='<?php echo $path;?>'/>
<?php endif; ?>
If the iID is actually an integer, you need to omit the single quotes in the query.
You also have to change the dataType from json to html, as you are returning an image tag (HTML) and not JSON:
$.ajax({
type: "get",
url: "imageData.php",
dataType: "html",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
$("#images_"+imageId).html(data);
}
});
Another option is to return only text (the link) and create the images on the client side:
<?php
if(isset($_GET['getImageId'])) {
$path = '';
$imageId = mysql_real_escape_string($_GET['getImageId']); // SQL injection!
$result = mysql_query("SELECT images FROM images WHERE iID = '".$imageId."'");
$row = mysql_fetch_array($result);
if($row) {
echo 'img/' . $row['images'];
}
}
?>
And in JavaScript:
$.ajax({
type: "get",
url: "imageData.php",
dataType: "text",
data: {getImageId: imageId},
error: function() {
alert("error");
},
success: function(data){
$("#images_"+imageId).html('<img src="' + data + '" />');
}
});
As you may get many images because you use while loop you probably want to do this like so:
in php:
$x = 0;
$another = array();
while($row = mysql_fetch_array($sql)){
$another[$x] = $path.$row['images'];
$x++;
}
echo json_encode($another);
and in jquery (in your success callback):
$.each(data, function(i, v){
// Do the image inserting to the DOM here v is the path to image
$('#somelement').append('<img src="'+v+'"');
});
For outputing an image you must set src attribute of the image tag, if you already have one, or you can create it on the fly. See here how to do that > jQuery document.createElement equivalent?