Set interval with AJAX - javascript

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!

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();
}
});

Accessing JSON returned by php script using jquery ajax

Basically my program is a web page with 5 radio buttons to select from. I want my web app to be able to change the picture below the buttons every time a different button is selected.
My problem is coming in the JSON decoding stage after receiving the JSON back from my php scrip that accesses the data in mysql.
Here is my code for my ajax.js file:
$('#selection').change(function() {
var selected_value = $("input[name='kobegreat']:checked").val();
$.ajax( {
url: "kobegreat.php",
data: {"name": selected_value},
type: "GET",
dataType: "json",
success: function(json) {
var $imgEl = $("img");
if( $imgEl.length === 0) {
$imgEl = $(document.createElement("img"));
$imgEl.insertAfter('h3');
$imgEl.attr("width", "300px");
$imgEl.attr("alt", "kobepic");
}
var link = json.link + ".jpg";
$imgEl.attr('src', link);
alert("AJAX was a success");
},
cache: false
});
});
And my php file:
<?php
$db_user = 'test';
$db_pass = 'test1';
if($_SERVER['REQUEST_METHOD'] == "GET") {
$value = filter_input(INPUT_GET, "name");
}
try {
$conn = new PDO('mysql: host=localhost; dbname=kobe', $db_user, $db_pass);
$conn->setAttribute(PDO:: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM greatshots WHERE name = :name');
do_search($stmt, $value);
} catch (PDOException $e) {
echo 'ERROR', $e->getMessage();
}
function do_search ($stmt, $name) {
$stmt->execute(['name'=>$name]);
if($row = $stmt->fetch()) {
$return = $row;
echo json_encode($return);
} else {
echo '<p>No match found</p>;
}
}
?>
Here's my HTML code where I am trying to post the image to.
<h2>Select a Great Kobe Moment.</h2>
<form id="selection" method="get">
<input type="radio" name="kobegreat" value="kobe1" checked/>Kobe1
<input type="radio" name="kobegreat" value="kobe2"/>Kobe2
<input type="radio" name="kobegreat" value="kobe3"/>Kobe3
</form>
<div id="target">
<h3>Great Kobe Moment!</h3>
</div>
And here's is what my database looks like:
greatshots(name, link)
name link
------ --------
kobe1 images/kobe1
kobe2 images/kobe2
kobe3 images/kobe3
Whenever I run the web app right now, the rest of the images on the page disappear and the image I am trying to display won't show up. I get the alert that "AJAX was a success" though, but nothing comes of it other than the alert. Not sure where I am going wrong with this and any help would be awesome.
As mentioned you should parse the JSON response using JSON.parse(json);.
Also, you should specifically target the div element with a simpler setup:
$("#target").append('<img width="300px" src="' + link + '.png"/>');

JQuery form submission generates a new form

I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}

Ajax database insert isnt working

I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}

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;
?>

Categories

Resources