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"];
Related
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 have a search function that calls a php file onkeyup. Now in JQuery i have a onClick function that when you click a div from that same JSON call it alerts something, maybe it will be easier to understand from my code below:
<?php
$Connect = new mysqli("localhost", "root", "", "Data");
$Val = $_POST['Val'];
if($Val)
{
$Search = 'SELECT * FROM Users WHERE ';
$Term = explode(" ", $Val);
foreach($Term as $Key)
{
$I = 0;
$I++;
if($I == 1)
{
$Search .= 'Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
else
{
$Search .= 'OR Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
}
if($Result = $Connect->query($Search))
{
while($Row = $Result->fetch_assoc())
{
$User = $Row['Username'];
$USearch['S'][] = '<div class="Result"><label class="TText" style="cursor:pointer;">' . $User . '</label></div>';
}
}
}
echo json_encode($USearch);
?>
Now, as you can see, once the user types into a box a div shows up showing all LIKE records of Users, once the div is clicked on nothing happens.
$('.Result').click(function()
{
alert('Hi');
});
When the ajax call return a state of success you can use for example the jquery bind method. (see here for more info http://api.jquery.com/bind/ )
function myAjaxFunct(val){
$.ajax(
{
type: "POST",
url: myPhpFile.php,
datatype: "jsonp",
data: {val: val},
success: function (result) {
$("#jsonResultDisplay").text(result);
$('.Result').bind('click', function() {
alert('hi');
});
}
});
}
You are dynamically creating element that is why it doesn't work.
Use on()method.
Check an example:
http://jsfiddle.net/pZQ8T/
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 );
The following code will not do what I hoped, that is run the Ajax function when the div ="dist" li
created by the PHP code's is clicked.
Guidance please.
<?php
// ...
$result = mysql_query($sql);
echo "<div class=\"dist\">";
echo "<ul>";
while ($row = mysql_fetch_array($result)) {
echo "<li><a href=\"devplan.php?search-n=" . $row['NAME'] .
"&" . rawurlencode($row['PLAN']) . "\"" . ">" .
$row['PLAN'] . "</a></li>";
};
echo "</ul>";
echo "</div>";
?>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
});
});
</script>
Here is a starter for ten - I've corrected some additional braces and added error handling. If you still get an error, at least you#ll be able to tell us what it is.
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I'd add a console.log(urlplan) right after the click event handler. make sure that returned value works if you manually enter
php/dpdetails.php?q=test&anotherVar=5
into the address bar.
What does console.log(urlplan) return?
Here is a sample piece of code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>What</title>
</head>
<body>
<?php
$anchorList = "";
$rows = array(
array(
'NAME' => 'me1'
, 'PLAN' => 'thePlan1'
)
, array(
'NAME' => 'me2'
, 'PLAN' => 'thePlan2'
)
);
$anchorList .= "<div class=\"dist\">";
$anchorList .= "<ul>";
foreach ($rows as $row) {
$anchorList .= "<li>";
$anchorList .= createAnchorTag($row['NAME'], $row['PLAN']);
$anchorList .= "</li>";
}
$anchorList .= "</ul>";
$anchorList .= "</div>";
echo $anchorList;
function createAnchorTag($name, $plan) {
return "" . $plan . "";
}
?>
</body>
</html>
<script type="text/javascript" src="../scripts/jquery-1.4.2.modified.js"></script>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>
In your click function you need to return false in order to override the anchor tags wanting to redirect.
[EDIT]
I believe your actually looking to parse the href attribute of the anchor tag and pass it to the Ajax, right? If so use this script:
<script type="text/javascript">
$(document).ready(function() {
$('.dist a').click(function() {
var urlquery = $(this).attr('href').val();
// regex would be better than split, could create a more generic function
var urlparts = urlquery.split('&');
var urlplan = urlparts[1];
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>