All need is that ul list is populated with data from php code,on page load.Thanks in advance,and sorry if I am not exact,I am new here.This post is mostly code.
Here's the code of ajax function:
$(document).ready(function() {
var podtip="proba";
$.ajax({
url: 'php/dodajTVpocetna.php',
type: 'POST',
cache:false,
data: { target: podtip },
success: function (data) {
$('#slider ul').append(data);
}
});
});
Here's the code of php file:
$q = $_POST['target'];
$conn=mysqli_connect("localhost","root","","iptv");
if (mysqli_errno($conn)) {
die("Neuspjela konekcija: " . mysqli_connect_error());
}
else{
$upitM='SELECT * FROM stream WHERE Kategorija="Music" ORDER BY rand() LIMIT 0,1';
$music=mysqli_query($conn,$upitM);
$upitF='SELECT * FROM stream WHERE Kategorija="Movies" ORDER BY rand() LIMIT 0,1';
$film=mysqli_query($conn,$upitF);
$upitS='SELECT * FROM stream WHERE Kategorija="Series" ORDER BY rand() LIMIT 0,1';
$series=mysqli_query($conn,$upitS);
$upitN='SELECT * FROM stream WHERE Kategorija="News" ORDER BY rand() LIMIT 0,1';
$news=mysqli_query($conn,$upitN);
$upitMO='SELECT * FROM stream WHERE Kategorija="More" ORDER BY rand() LIMIT 0,1';
$more=mysqli_query($conn,$upitMO);
if(!$music)echo'greska je "'.mysqli_error($conn).'"';
while(($row = mysqli_fetch_assoc($music)) != NULL) {
$row1 = mysqli_fetch_assoc($news);
$row2 = mysqli_fetch_assoc($film);
$row3 = mysqli_fetch_assoc($series);
$row4 = mysqli_fetch_assoc($more);
print_r(error_get_last());
echo"<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row['Link']."\");'>".$row['Naziv']."</a></div></li>
<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row1['Link']."\");'>".$row1['Naziv']."</a></div></li>
<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row2['Link']."\");'>".$row2['Naziv']."</a></div></li>
<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row3['Link']."\");'>".$row3['Naziv']."</a></div></li>
<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row4['Link']."\");'>".$row4['Naziv']."</a></div></li>";
}
mysqli_close($conn);
}
HTML list:
<div class="w3-third">
<div id="liquid1" class="liquid">
<span class="previous"></span>
<div class="wrapper">
<ul id="slider">
</ul>
</div>
<span class="next"></span>
</div>
</div>
I used ajax before,and it worked this way.
first of all check your query , that return values and works fine use:
print_r($film) and other query result to see what happens at the end.
next you dont need to use
$('#slider ul').append(data);
use this:
$('#slider').append(data);
Change your PHP code with this :
$q = $_POST['target'];
$conn=mysqli_connect("localhost","root","","iptv");
if (mysqli_errno($conn)) {
die("Neuspjela konekcija: " . mysqli_connect_error());
}
else{
$upit='SELECT * FROM stream WHERE Kategorija in ("Music","Movies","Series","News","More") ORDER BY rand()';
$all=mysqli_query($conn,$upit);
if(!$all)echo'greska je "'.mysqli_error($conn).'"';
//uzimamo vrijednosti svih proizvoda za zadati podtip,smjestamo ih u div elemente i prikazujemo na pocetno
$ht = "";
while(($row = mysqli_fetch_assoc($all)) != NULL) {
print_r(error_get_last());
$ht .= "<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".$row['Link']."\");'>".$row['Naziv']."</a></div></li>";
}
mysqli_close($conn);
echo $ht;
}
And your js code :
$(document).ready(function() {
var podtip="proba";
$.ajax({
url: 'php/dodajTVpocetna.php',
type: 'POST',
cache:false,
data: { target: podtip },
success: function (data) {
$('#slider').append(data);
}
});
});
You have to accumulate the final HTML content on each iteration through resultset rows. Change your while loop as shown below:
$content = "";
while(($row = mysqli_fetch_assoc($music)) != NULL) {
$row1 = mysqli_fetch_assoc($news);
$row2 = mysqli_fetch_assoc($film);
$row3 = mysqli_fetch_assoc($series);
$row4 = mysqli_fetch_assoc($more);
//print_r(error_get_last());
$content .= "<li><div class=\"tv\"><a href='javascript:changeVideoJW(\"".addcslashes($row['Link'],'"')."\");'>".addcslashes($row['Naziv'],'"')."</a></div></li>";
}
echo $content;
Add dataType option into your ajax request object to get response from server as HTML:
...
dataType : 'html',
...
Also, append response data as HTML as shown below:
...
$('#slider ul').html(data);
...
Related
I have created an ajax method to search for User Lists.
But the ajax function returning me such as :
<ul><li>User Name</li></ul>
I want to trim <ul></ul> and <li></li> tag in main page to use the exact value.
Like :
Before :
<ul><li>User Name</li></ul>
After :
User Name
The ajax result will store in :
<div class="input-group" id="userList"></div>
I have done already some javascript method to do so
Ajax function :
< script >
$(document).ready(function() {
$('#run').keyup(function() {
var query = $(this).val();
if (query != '') {
$.ajax({
url: "userSearch.php",
type: "POST",
data: {
query: query
},
success: function(data) {
$('#userList').fadeIn();
$('#userList').html(data);
paymentStatus(data);
}
});
} else {
$('#userList').fadeOut();
}
});
$(document).on('click', 'li', function() {
$('#run').val($(this).text());
$('#userList').fadeOut();
});
}); <
/script>
userSearch.php File Code :
<?php
require_once '../../config/config.php';
if(isset($_POST['query']))
{
$output = '';
$query = "SELECT Name, Id FROM ucoe_users WHERE Name LIKE '%".$_POST['query']."%' AND RoleId = 3";
$result = mysqli_query($connection, $query);
$output = '<ul>';
if(mysqli_num_rows($result)> 0 )
{
while($row = mysqli_fetch_array($result))
{
$output .= "<li>".$row['Name']."</li>";
}
}
else
{
$output .= '<li>User Not Found</li>';
}
$output .= "</ul>";
echo $output;
}
?>
Use $(html).text() to get text value from your html
success: function(data) {
$('#userList').fadeIn();
$('#userList').html($(data).text());
paymentStatus(data);
}
var html = '<ul><li>User Name</li></ul>';
console.log($(html).text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use the jQuery as following ,
var arrOfValues = [];
$('ul li').each(function(i)
{
arrOfValues.push($(this).text()); //every value of ul li will be push in arrOfvalues.
});
$('#userList').fadeOut();
If it was a DOM element then it would be straight forward just get innerText
for eg :
<ol>
<li>User Name</li>
</ol>
<script>
var olDom = document.getElementsByTagName("ol");
console.log(olDom[0].innerText)
</script>
But in your case you are getting HTML as a response of Ajax, so first we need to create a wrapper div to hold your response in a form of DOM and then we will call innerText.
<script>
var wrapperDiv = document.createElement('div');
wrapperDiv.innerHTML = data;
$('#userList').html(wrapper.innerText);
</script>
Trying to request the posts made by users and loading more posts on user's request.
Getting Unexpected end of JSON input error while making ajax request in console.
Javascript
$("#ajax_load_more").click(function(){
$.ajax({
type: "GET",
url: "action.php?action=morePosts",
success: function(response){
var result = $.parseJSON(response);
console.log(result);
}
});
});
Making request to following code.
$_SESSION['posts']) stores the number of posts to be loaded in the session.
if($_GET['action']=="morePosts"){
if(isset($_SESSION['posts'])){
$_SESSION['posts'] = $_SESSION['posts'] + 4;
echo fetchAllPosts($_SESSION['posts']);
} else if(isset($_SESSION['posts'])&& $_SESSION['posts']>4){
$_SESSION['posts'] = 4;
}
}
Function for requesting all posts
function fetchAllPosts2($array_length){
$db = new db; //Class for database
$query = "SELECT * FROM `posts` ORDER BY `post_id` DESC LIMIT $array_length";
$result = $db::query($query);
$row = mysqli_fetch_all($result);
$post = array();
for($i=0; $i<$array_length; $i++){
if(!empty($row[$i])){
for($j=0;$j<count($row);$j++){
$post['id']=$row[$i][0];
$post['user_id']=$row[$i][1];
$post['title']=substr($row[$i][2], 0 ,75);
$post['text']=strip_tags(mb_substr($row[$i][3],0,50));
$post['image']=$row[$i][4];
$post['date']=$row[$i][5];
}
return json_encode($post);
}
elseif(empty($row[count($row)])){
return json_encode(array());
}
}
}
Please suggest better ways of achieving this functionality,
Try to use echo instead of return and change ajax like also you din not echo the code inside elseif part:
$("#ajax_load_more").click(function(){
$.ajax({
type: "GET",
dataType: "json",
url: "action.php?action=morePosts",
success: function(response){
console.log(response);
}
});
});
try this :
function fetchAllPosts2($array_length){
$db = new db; //Class for database
$query = "SELECT * FROM `posts` ORDER BY `post_id` DESC LIMIT $array_length";
$result = $db::query($query);
$row = mysqli_fetch_all($result);
$post = array();
if($result && mysqli_num_rows($result) > 0) {
foreach($row as $key=>$value){
$post[$key]['id']=$value['id'];
$post[$key]['user_id']=$value['user_id'];
$post[$key]['title']=substr($value['title'], 0 ,75);
$post[$key]['text']=strip_tags(mb_substr($value['text'],0,50));
$post[$key]['image']=$value['image'];
$post[$key]['date']=$value['date'];
}
return json_encode($post);
}
return json_encode(['error'=>"no post found"]);
}
Recently i developed a load more functionality using php and jquery . Please see my code
Html
<div class="container clearfix product-output">
</div>
jQuery
$.ajax({
method: "POST",
url: "result.php",
data: { keyword:"all"}
}).done(function( msg ) {
$( ".product-output" ).html(msg);
$(".load-more").on("click",function(){
var load_num= $('.load-more').length;
var appear=[];
$(".im-product-block").each(function(){
appear.push($(this).attr('id'));
});
$.ajax({
method: "POST",
url: "result.php",
data: { keyword: "all", y_id: appear, load_num: load_num }
}).done(function(msg1){
$('.load-more-div').before(msg1);
if($(".hide-load").val()==1){
$(".load-more").hide();
}
});
});
});
In result .php i write the db connection code and following query .
$query = 'SELECT * FROM `product` ORDER BY id DESC LIMIT 15';
$query_1 = 'SELECT * FROM `product` ORDER BY id DESC';
if (ISSET($_POST['y_id'])) {
$appear = implode("', '", $_POST['y_id']);
$query = "SELECT * FROM `product` WHERE id NOT IN('{$appear}') ORDER BY id DESC LIMIT 15";
$query_1 = "SELECT * FROM `product` WHERE id NOT IN('{$appear}') ORDER BY id DESC";
}
$result = $conn->query($query);
$result_1 = $conn->query($query_1);
$total_num = $result_1->num_rows;
echo '<div class="container clearfix product-output">';
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) { ?>
<div class="col-sm-2 im-product-block" id="<?php echo $row["id"]; ?>">
<p class="product-name"> <?php echo $row["name"]; ?></p></div>
<?php }
echo '</div>';
if ($total_num > 15 && $_POST[load_num] == 0) {
echo '<div class="load-more-div"><p class="load-more"> Load More</p></div>';
}
if ($total_num < 15) {
echo '<input type="hidden" name="hide-load" class="hide-load" value="1">
<div class="load-finished"><p class="load-f"> All Products Loaded Successfully</p></div>';
}
}
Here all this functionality is working fine . But instead of clicking load more button , when user scroll down to load-more it need to fetch the products automatically without clicking .
for that i using the following code
$(window).scroll(function() {
var hT = $(".load-more").offset().top,
hH = $(".load-more").outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
$(".load-more").trigger("click");
}
});
But here the execution is contunied to infinity .It is not stopping . Please check this code and suggest a good method
I think you need to stop your load executing while your ajax call is made and written to the page. Perhaps set a boolean variable to decide if you need to load more.
e.g.
var canLoad = true;
$(window).scroll(function() {
var hT = $(".load-more").offset().top,
hH = $(".load-more").outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH) && canLoad){
canLoad = false;
$(".load-more").trigger("click");
}
});
Set canLoad back to true once your ajax function has finished and you have loaded the data.
I have a small script that runs a php file in the background and gets a variable every 3 seconds and put it in a div
script in document with div
<script>
$(document).ready(function() {
setInterval(function () {
$('#statmoney').load('safe.php');
}, 3000);
});
</script>
PHP FILE (safe.php)
$sql = "SELECT * FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$money = htmlspecialchars($row->money);
echo $money;
If i need to add another variable i would need to make a new document is there a easy way to go about it?
UPDATE
menu.php
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['money', 'ore', 'energy']; // array of needed fields
$.ajax({
type: "POST",
url: "menusafe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
console.log(response)
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
<div class="menustats"><img src="graphics/logos/moneylogo.png" class="menustatimage"><div class="menustattext" id='money'></div></div>
<div class="menustats"><img src="graphics/logos/energylogo.png" class="menustatimage"><div class="menustattext" id="energy"></div></div>
<div class="menustats"><img src="graphics/logos/orelogo.png" class="menustatimage"><div class="menustattext" id='ore'></div></div>
PHP(menusafe.php)
<?php
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
?>
Let's imagine that we want to retrieve three fields from users table : firstname, age and money. In such case it would be better to use $.post or $.ajax method:
js part:
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['firstname', 'age', 'money']; // array of needed fields
$.ajax({
type: "POST",
url: "safe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
php part: (safe.php)
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
I Cannot get comment reply by Ajax under comment, But reply saved in database and If i refresh Index.php page, it display correctly. So I think my problem either in my reply display element(Div id/class or php) OR Ajax call back.
Please help me. I can't do anything last 7 days about this.
my Index.php framework
$results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='$tutid' ORDER BY id DESC LIMIT 20") or die(mysqli_error($dbh));
echo'<div class="content"><comment>';
while($rows = mysqli_fetch_array($results)) {
$id = $rows['id'];
$username = $rows['username'];
//etc all
echo'<div class="post'.$id.'">
//Comments goes here
echo'<p class="name">'.$username.' Says:</p>';
echo'<span class="cdomment_time">'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div>
<div class="cdomment_text">';
echo'.htmlentities($description).'<br>';
echo'</div>';
// Reply Start
$query = "SELECT * FROM comments_reply WHERE parent_id ='".$id."'";
$res = mysqli_query($dbh,$query);
while($row = mysqli_fetch_array($res)){
$parent_id = $row['parent_id'];
$username = $row['username'];
//etc all
echo'<div class="rcontent"><replycomment><div class="reply'.$parent_id.'"><ul>
//Reply goes here
echo'<p class="name">'.$username.' Says:</p>';
echo'<span class="cdomment_time">'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div>
<div class="cdomment_text">';
echo'.htmlentities($description).'<br>';
</ul></div><replycomment></div>';
} //reply while close
} //comment while close
echo'<comment></div>';
my reply.php framework
$results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='$tutid' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
$row = $results->fetch_array();
$id = $row['id'];
$res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE parent_id ='$id' LIMIT 1") or die(mysqli_error($dbh));
while($row = mysqli_fetch_array($res)) {
$parent_id = $row['parent_id'];
$username = $row['username'];
echo'<div class="rcontent"><replycomment><div class="reply'.$parent_id.'"><ul>';
//New reply goes here
echo'<p class="name">'.$username.' Says:</p>';
echo'<span class="cdomment_time">'.$date.'</span><br/>
<div class="avatarcnt">
<img alt="" src="uploadprofile/'.$u_imgurl.'"/>
</div>
<div class="cdomment_text">';
echo'.htmlentities($description).'<br>';
echo'</ul></div><replycomment></div>';
JavaScript { here $tutid is a page id, which work well ( If u have any confusion about this )}
$(document).ready(function(){
var inputReplycom = $(".replycom");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment"); // update comment
//update reply
function updateReplybox(){
var tutid = inputTutid.attr("value");
**(EDITED)** var RID = inputparent_id.attr("value");
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid="+ tutid,
complete: function(data){
**(EDITED)**
$(".postreply"+RID).append(data.responseText);
$(".postreply"+RID).fadeIn(2000);
}
});
}
//on submit reply
$(".replyfrm").click(function(){
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$(".loader").fadeIn(400);
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&replycom="+ replycom + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
$(".reply_here").hide();
updateReplybox();
}
});
//we prevent the refresh of the page after submitting the form
return false;
});
});
EDITED:
New Edited Code that I am trying now which display fadeIn a blank result before refresh
In index.php change:
<div class="postreply'.$parent_id.'"><ul>
In reply.php change:
<div class="postreply'.$parent_id.'"><ul>
JavaScript change
function updateReplybox(){
var tutid = inputTutid.attr("value");
var RID = inputparent_id.attr("value");
//just for the fade effect
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid="+ tutid,
complete: function(data){
$(".postreply"+RID).append(data.responseText);
$(".postreply"+RID).fadeIn(2000);
}
});
}
The following will be your js
$('#commentButton').click(function() {
replycom = document.getElementById('inputReplycom').value;
parent_id = document.getElementById('inputparent_id').value;
tutid = document.getElementById('inputTutid').value;
$.post('reply.php', {'replycom': replycom, 'parent_id': parent_id, 'tutid': tutid}, function(data) {
var parsed = JSON.parse(data);
var html = '<section class="comment-list block"><article id="comment-id-1" class="comment-item"> <a class="pull-left thumb-sm"> <img src="/uploads/' + parsed.photo +'" class="img-circle"> </a> <section class="comment-body m-b"> <header> <strong>'+parsed.username+'</strong> <span class="text-muted text-xs block m-t-xs">'+parsed.created_at.date+' </span> </header> <div class="m-t-sm">'+ parsed.comment +'</div></section> </article> </section>';
$('#extraComments').append(html);
}).success(function() {
$('#comment').val('');
$('#commentSuccess').html('Submitted successfully!').show().delay(5000).fadeOut();
}).fail(function() {
$('#commentFailed').html('Failed!').show().delay(5000).fadeOut();
});
});
in your reply.php get the data
$replycom = $_GET['replycom'];
$parent_id = $_GET['parent_id'];
$tutid = $_GET['tutid'];
//and process it
Please change the var names accordingly
Edited code :
echo json_encode(array('replycom' => $replycom, 'parent_id' => $parent_id, 'tutid' => $tutid));