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.
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 tried to create wordpress ajax call that should return images attached to a post but get_attached_media function returns an empty array. I can get any post data but not attached images. Here is what I have done:
in functions.php:
add_action('wp_ajax_getGallery', 'getGallery');
add_action('wp_ajax_nopriv_getGallery', 'getGallery');
function getGallery() {
$pid = $_REQUEST["post_id"];
$n = 1;
$gallery = get_attached_media('image', $pid);// this $gallery returns an empty array
foreach($gallery as $item) {
if ($n > 5) {
$img_object = wp_get_attachment_image_src($item->ID,'gallerythumb');
$img = $img_object[0];
$str .= '<div class="col-sm-2 col-xs-4"><div class="img-holder"><img class="img-responsive" src="' . $img . '" /></div></div>';
$n++;
}
}
echo $str;
die();
}
and in .js:
$(".post-link").click(function(){
var post_id = $(this).attr("rel");
$("#post-container").html("content loading");
$.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: {
action: 'getGallery',
post_id: post_id
},
success: function(data) {
console.log(data);
$("#post-container").html(data);
},
fail: {
}
});
return false;
});
Does anyone knows why I can't get images here? All code seams fine to me.
Thnx.
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 );
I'm working on a website with comparing multiple products (Link). The productnames are in a box. With a mouseover I can see their specification in the box. The problem is that I have multiple boxes with different products and all of the specification are loading inside one box. I hope someone can help me.
(It's partly Dutch)
if($nieuws['relateditem'])
{
$array1 = explode(",", $nieuws['relatedoption']);
foreach($array1 as $key2)
{
print_r($key2);
}
$content .='
<h2>Gerelateerde producten</h2>
<div id="product-grid">
<div id="product-grid-inner">
';
$array = explode(",", $nieuws['relateditem']);
$i = 0;
$id = 0;
foreach($array as $key1)
{
$id++;
$i++;
$key1 = trim($key1);
$query4x = $mysqli->query("SELECT * FROM producten WHERE productcode='".$key1."'");
$row2x = $query4x->fetch_assoc();
$hammer = str_replace("XXX", $row2x['id'], $hammertimePro);
$content .='
<div id="'.$id.'blok" class="product-grid-item3" onMouseOver="this.style.border = \'1px solid #007fff\'" onMouseOut="this.style.border = \'1px solid #CCCCCC\'">
<h2 class="titel">'.$row2x['naam'].$hammer.'<br /></h2><br />';
//----
$options2 = explode(",", $row2x['relatedoption']);
foreach($options2 as $option2)
{
$query2 = $mysqli->query("SELECT * FROM producten WHERE productcode = '".$option2."'");
while($row2 = $query2->fetch_assoc())
{
$content.= "<div onMouseOver=\"this.style.backgroundColor='#f0f0f0'; this.style.cursor='pointer'; showConc(".$row2['id'].",1)\" onMouseOut=\"this.style.backgroundColor='#ffffff';\">".substr($row2['naam'], 13, 4)."</div>";
}
}
//---- onMouseOver='showInformation(".$prods['id'].")'
$content.='<div id="specs"></div></div>';
}
$content .= '</div></div>';
}
?>
function showConc(id,box) {
$.ajax({
url: 'http://www.ledisvet.nl/A3/concept_prod.php',
type: 'get',
data: 'id='+id,
success: function(result) {
$('#specs').html(result);
}
});
}
Thanks
There are multiple problems here. The #1 problem is that you have three divs with the id specs. Ids must be unique - the browser doesn't know which #specs box you mean so it picks the first it finds.
You never use the showConc() function's second parameter (box). Even if you did, you have it hardcoded to 1: showConc(".$row2['id'].",1).
Change the showConc() function to something like this:
function showConc(id,box) {
$.ajax({
// ... other parameters here
success: function(result) {
$('#specs'+box).html(result);
}
});
}
Then change the specs ids to specs1, specs2 and specs3 and call the function with the correct number.