Moment js stops working after ajax call - javascript

Below is my code to convert time to a fancy style for eg. 1 min ago, 9 hours ago etc using moment.js.
<script>
$(document).ready(function() {
var out = "";
var diffDays = moment.utc("<?php echo $row["created_date"]; ?>", "YYYY-MM-DD hh:mm").fromNow();
out += "<span class='glyphicon glyphicon-time hours'></span> "+ diffDays;
$("#divContent<?php echo $row["postid_userid"]; ?>").html(out);
});
</script>
The code is working fine.
I have an ajax load more option on the same page to load more posts when scrolling.
My main problem is that, the moment js I am using stopped working after ajax call. Is this the problem because the code is not getting moment.js on my ajax page get_results.php ?
This is my ajax function (which is on the same page and calls the other page to load more posts)
<script type="text/javascript">
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
var val = document.getElementById("id").value;
document.getElementById("id").value = Number(val)+5;
$.ajax({
type: 'post',
url: 'get_results.php',
data: {
getresult:val
},
success: function (response) {
loading = false;
if(response.trim().length == 0){
//notify user if nothing to load
$('.loading-info').html("No more posts!");
document.getElementById("loading-info").style.display = "block";
return;
}
else
{
var content = document.getElementById("all_rows");
content.innerHTML = content.innerHTML+response;
}
$('.loading-info').hide(); //hide loading animation once data is received
}
});
}
});
And this is the get_results.php page:
<?php session_start();
$user_id=$_SESSION['user_id'];
include "mydbfile.php";
if(isset($_POST['getresult']))
{
$no = $_POST['getresult'];
?>
<?php
$select =$conn->prepare("select * from ----- ");
$select->execute();
while($row =$select->fetch())
{
?>
//design to display more posts
<?php
}
} exit(); ?>

Related

How to make script tag work inside a div?

I am building an edit feature of a post on a website, so i am using jquery ajax and php as the script file that makes the edit inside a database. The problem is in the return script, i have a script tag which contains some jquery and then i place the returned data inside a div, but the script tag is being printed as if it was a text. Can someone help me please to let the script tag act as an actual script and not being printed as text ?
here is my html div :
<div class="board_post_span" id="<?php echo $board_id."-".$board_user_id;?>-spanBoardEdit"><?php echo $board_post;?></div>
and here is my php script :
<?php
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
require_once '../includes/create_thumbnail.php';
// this to prevent from accessing this file by pasting a link to it
if(!is_ajax_request()) {
exit;
}
if(isset($_POST['board_id'], $_POST['board_textarea'])) {
$board_id = (int)$_POST['board_id'];
$board_textarea = mysql_prep($_POST['board_textarea']);
// UPDATE table
$query = "UPDATE board_table ";
$query .= "SET board_post = '$board_textarea' ";
$query .= "WHERE board_id = $board_id";
$result = mysqli_query($connection, $query);
// now we select the updated board post
$query2 = "SELECT * FROM board_table ";
$query2 .= "WHERE board_id = $board_id ";
$result2 = mysqli_query($connection, $query2);
confirm_query($result2);
$result_array = mysqli_fetch_assoc($result2);
}
?>
<?php
echo $result_array['board_post'];
?>
<script>
// This takes care of the board Continue Reading feature ---------------------------------------------------------
$(".board_post_span").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('Continue Reading');
} else {
$(this).text(boardPostText);
}
});
</script>
and here is my jquery and ajax :
$.ajax({
url: url_edit_board,
method: "POST",
data: {
board_id: saveBoardButtonId,
board_textarea: editBoardTextareaVal
},
beforeSend: function() {
CustomSending("Sending...");
},
success: function(data){
$("#sending_box").fadeOut("Slow");
$("#dialogoverlay").fadeOut("Slow");
// this makes the scroll feature comes back
$("body").css("overflow", "scroll");
console.log(data);
$("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit").html(data);
$("#"+saveBoardButtonId+"-formBoardEdit").hide();
$("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit").show();
}
});
The reason is that you're setting boardPostText to the text of the entire DIV, which includes the <script> tag inside the DIV. You should put the text that you want to abbreviate inside another span, and process just that.
So change:
echo $result_array["board_post"];
to:
echo "<span class='board_post_text'>" . $result_array["board_post"] . "</span>";
Then in the JavaScript you're returning you can do:
$(".board_post_text").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if(boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('Continue Reading');
} else {
$(this).text(boardPostText);
}
});
First of all, it seems you don't need else part:
else {
$(this).text(boardPostText);
}
Then, before do anything, make sure that your return data from PHP file, the text has not become encrypted in some way. if < becomes < then the text never consider as JS code.
You can create a script tag then place your JS script into it as a function then call it yourself right after injecting.
replace your script in PHP file with this:
<script>
var scriptText = `function editPost() {
$(".board_post_span").each(function(){
var boardPostText = $(this).text();
var boardPostLength = boardPostText.length;
var boardIdAttribute1 = $(this).attr("id");
var boardIdAttributeArray1 = boardIdAttribute1.split("-");
var boardPostId = boardIdAttributeArray1[0];
var boardPostUserId = boardIdAttributeArray1[1];
if (boardPostLength > 250) {
var boardPostTextCut = boardPostText.substr(0, 250);
$(this).text(boardPostTextCut+"...");
$("#"+boardPostId+"-continueReading").remove();
$(this).after('<a href="board_comment.php?
user_id='+boardPostUserId+'&board_id='+boardPostId+'" class="board_continue_reading" target="_blank" id="'+boardPostId+'-continueReading">Continue Reading</a>');
}
});
}`
</script>
then change your js file to:
$.ajax({
// ...
success: function(data) {
// ...
var container = $("#"+saveBoardButtonId+"-"+editBoardButtonUserId+"-spanBoardEdit")
container.html(data)
var scriptEl = $('<script></script>').html(scriptText).appendTo(container)
// now call the editPost function
editPost()
$("#"+saveBoardButtonId+"-formBoardEdit").hide();
container.show();
}
});

ajax / jquery not passing 2nd click values [duplicate]

This question already has an answer here:
Function doesn't work after appending new element
(1 answer)
Closed 5 years ago.
Extremely new to JavaScript, jquery and ajax and am having difficulties with a very basic set of scripts to load more data from a database on button clicks.
The first time I click load more, it works. But the 2nd clicks do not pass the values and does nothing.
Here is the main script that loads data once and includes the jquery, ajax stuff.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn1, #btn2").click(function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
$("#btn1").hide();
$("#div1").append(response);
}
}
});
});
});
</script>
</head>
<?php
// main.php contains db connection
include('main.php');
$rowsperpage = 2;
$q = "SELECT col1, col2 from mytableORDER BY col1 LIMIT $rowsperpage OFFSET 0";
$r = pg_exec($dbconnect, $q);
echo "<div id='div1' style='margin:10px;'>";
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
echo "<button id='btn1' value=2>Load More</button>";
echo "</div>";
?>
And here is the script fetched more data to display.
<?php
include('../config.php');
include('functions.php');
$rowsperpage = 2;
if(isset($_POST['page'])) {
$paged=$_POST['page'];
} else {
$paged = 1;
}
if($paged > 1) {
$rowoffset = $rowsperpage * ($paged -1);
$limit = " LIMIT $rowsperpage OFFSET $rowoffset";
} else {
$limit = " LIMIT $rowsperpage OFFSET 0 ";
}
$q = "select subindustryid, subindustry from sub_industries ORDER BY subindustry $limit";
$r = pg_exec($dbconnect, $q);
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";
?>
The problem is the the 2nd button is displayed and nothing happens when it gets clicked.
Thank for your time!
The problem is the event binding. Change this line-
$("#btn1, #btn2").click(function() {
to this line
$("#div1").on("click","#btn1, #btn2",function(){
Also your php returns a button with id btn1 and not btn2
Read about jQuery Event bindings here: https://learn.jquery.com/events/handling-events/ and http://learn.jquery.com/events/event-delegation/
Actually id identifiers should be unique- this is general convention. You have load more button with id="#btn1" and hiding old button appearing new button from the response text form ajax by hiding and appending- but you can manage such with out sending button in response text-
Have following changes on your html page
value should be quoted <button id="btn1" value="2">Load More ... </button>
Make use of dedicated function calling in jQuery like- $(document).on('event','dom_identifiers',callbackfunction(){})
In ajax don't need to hide current button which is clicked, instead of hiding the button just add new records fetched before the load more button by using before() function of jQuery
For next page you can increase the value of current button
$(document).ready(function(){
// dedicated function calling
$(document).on('click','#btn1',function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
// increase the value load more
$("#btn1").val(parseInt($("#btn1").val())+1);
// add response data just before the loadmore button
$("#btn1").before(response);
}
}
});
});
});
button should be like
echo "<button id='btn1' value="2">Load More</button>";
Now in fetching php page please remove these two lines-
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";

how to fix undefined variable in php?

I have an index.php page. The function of this page is infinite scrolling using AJAX, PHP and MySQL. The top portion contains PHP MySQL codes and bottom contains JavaScript.
I want to print the total number of rows in center of the page, but every time I try it shows "undefined variable" error.
I think when loading the page, the total number of variable tries to print first and then the PHP query takes place, so it shows "undefined variable", but when I put the total number of variable inside the PHP codings, there is no problem.
How can I prevent this?
My index.php is
//my php part here
<?php
if(isset($_POST["anotherID"])){
require_once("config.php");
$limit = (intval($_POST['limit']) != 0 ) ? $_POST['limit'] : 10;
$offset = (intval($_POST['offset']) != 0 ) ? $_POST['offset'] : 0;
$id = $_POST["anotherID"];
$query = $id;
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM x where title like '%xx%' ORDER BY rand() LIMIT $limit OFFSET $offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
$row_object = $DB->prepare("Select Found_Rows() as rowcount");
$row_object->execute();
$roww_object =$row_object->fetchobject();
$actual_row_count = $roww_object->rowcount;
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo'something';
}
}
$count = $actual_row_count;
exit;
}
?>
//my html part here
<html>
//some html codes
<?php echo $count; ?>
//some html codes here
//my java scripts here
<script type="text/javascript">
var busy = false;
var limit = 6
var offset = 0;
var anotherID = 5
function displayRecords(lim, off) {
$.ajax({
type: "POST",
async: false,
data: "limit=" + lim + "&offset="+ off+"&anotherID="+anotherID,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default btn-block" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('<button class="btn btn-default btn-block" type="button"><div id="loader_image"><img src="loader.gif" alt="" width="24" height="24">Loading please wait...</button>').show();
}
window.busy = false;
}
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
//some html codes her
</html>
I know when a page is loading, the HTML parts are first loaded and then my jQuery stimulates the PHP part and then my results appear.
How can I fix this?
Why does $count always show "undefined variable"?
Thanks in advance.
You get an error of undefined $count because $count is defined only inside the if statement.
When the if clause doesn't apply $count is not defined.
Add an else clause to the if and initialize $count=0; and it will solve your problem.
Example:
....
$count = $actual_row_count;
exit;
}
else $count = 0;
?>

How to use ajax to scrape one page at a time, return the next page link and go again

Question:
I have a php scraping function and code that all works well, however it times out because its trying to load 60 different pages...
I was thinking of using AJAX to load one page at a time in a loop. Since i'm very new to AJAX im having some trouble.
This is what I have so far, I can get it to loop through the links if I provide them, however I want it to scrape page 1, return the next page link and then scrape the next page on a continuous loop until there are no more pages. As it stands it goes into infinite loop mode...
Any ideas guys?
Here is my code which i took from a youtube video which was using an array (i am only passing through a string)
<?php
ini_set('display_errors',1);
//error_reporting(E_ALL);
set_time_limit(0);
require_once 'scrape_intrepid.php';
//posted to this page
if(isset($_POST['id'])) {
//get the id
$id = $_POST['id'];
//this returns the next page link successfully, i just cant get it back into the function
$ids = scrapeSite($id);
echo $ids;
echo "<br>";
$data = $id . " - DONE";
echo json_encode($data);
exit();
} else {
$ids = 'http://www.intrepidtravel.com/search/trip?page=1';
}
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() {
function update() {
ids = <?=json_encode($ids);?>;
if(ids){
var id = ids;
$.post("index.php",{id:id}).done(function(msg){
console.log(ids,msg);
update();
});
} else {
console.log("done");
$("#log").html("Completed!");
}
}
$("#go").click(function() {
$("#go").html("Loading...");
update();
});
});
</script>
</head>
<body>
<button id="go">Go button</button>
<div id="log">Results</div>
</body>
Ended up solving this in another way: The function I am calling to function.php runs the script and returns the next URL to scrape. which is the msg value, so the refresh is called again once this is validated. Just processed 60 pages each taking 38 seconds each :S
<script>
$(document).ready(function() {
refresh('http://www.intrepidtravel.com/search/trip?');
function refresh(url) {
$.ajax({
type: "GET",
url: "function.php",
data: 'url=' + url,
success: function(msg){
$('#result').append('--->Completed! <br>Next Page: is ' + msg);
console.log(msg);
if ($.trim(msg) == 'lastpage'){
$('#result').append('--->Last page - DONE!');
}
else {
refresh(msg);
}
}
}); // Ajax Call
} //refresh
}); //document.ready
</script>
And the function.php file:
require_once 'scrape_intrepid.php';
if ($_GET['url']){
$url = $_GET['url'];
if ($url=="lastpage"){
echo $url;
} else {
$nextlink = scrapeSite($url);
echo($nextlink);
}
}

Set interval with AJAX

The purpose is to display a DIV when you click on a button and then display text inside that DIV that comes from my database. Thing is that data in databse changes, so text inside that div also. I would need a setInterval... with AJAX
I'm new in javascript and don't know the good way to go...
HTML:
<div onClick="showDiv();"> click </div>
<div style="display: none;" id="div">
Info from database:
<span style="display: hidden;" id="data1"> DATA 1 </span>
<span style="display: hidden;" id="data2"> DATA 2 </span>
</div>
javascript:
function showDiv()
{
document.querySelector("#div").style.display = "block";
setInterval(function () {getData()}, 1000);
}
function getData()
{
$.post(
'process.php',
{
},
function(data){
if(data == '1'){
document.querySelector("#data1").style.display = "inline";
}
else if(data == '2'){
document.querySelector("#data2").style.display = "inline";
}
},
'text'
);
return false;
}
//don't know how to just take data from database without sending by POST or GET.
php:
<?php
SELECT x FROM database
if(x == 1)
{echo '1';}
else if(x == 2)
{echo '2';}
?>
Get data using AJAX : Learn here. Your code to setInterval() is correct or you can do this : setInterval(getData,1000);
Display data in spans :
document.getElementById("data1").innerHTML = "your content from database";
document.getElementById("data2").innerHTML = "your content from database";
You're not giving a lot of info so I will give you a basic example of getting data from a mySQL database with jQuery, Ajax and PHP.
First you need to include jQuery to the head of your document
<script src="http://code.jquery.com/jquery-latest.js"></script>
And then use Ajax
function showDiv(){
document.getElementById("div").style.display = "";
setInterval(function (){ getData('something'); }, 1000);
}
jQuery.noConflict();
jQuery(document).ready(function($){
getData = function(variable){
var postVar = variable;
var postVar2 = "exemple";
$.ajax({
type: "POST",
url: "php/file.php",
data: 'variable=' + postVar + "&" +
'variable2=' + postVar2,
success: function(data){
data = $.trim(data);
var dataSplit = data.split("++==09s27d8fd350--b7d32n0-97bn235==++");
if(dataSplit[0] == "1"){
document.getElementById("data1").innerHTML = dataSplit[1];
}
if(dataSplit[0] == "2"){
document.getElementById("data2").innerHTML = dataSplit[1];
}
}
});
}
});
Finally, you need to create an external php file (in this example "file.php" in the folder "php") to get the data from your database with mysqli
<?php
// to prevent error, I check if the post variable is set and
// if it's not only full of spaces
if(isset($_POST['variable']) && preg_replace("/\s+/", "", $_POST['variable']) != ""){
$con = mysqli_connect("hostname", "username", "password", "database_name");
$query = mysqli_query($con, "SELECT * FROM `table_name` WHERE `column_name` = '".$_POST['variable']."'");
$results = array(); $row = 0;
while($info = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$results[$row] = array();
$results[$row]['column_name1'] = $info['column_name1'];
$results[$row]['column_name2'] = $info['column_name2'];
$row++;
}
foreach($results as $result => $data){
echo "1" . "++==09s27d8fd350--b7d32n0-97bn235==++" .
'<div>'.$data['column_name1'].'</div>'.
'<div>'.$data['column_name2'].'</div>';
}
}
?>
Hope it helps!

Categories

Resources