Stop repeating div content in PHP AJAX MySQL - javascript

I am trying to retrieve the data dynamically from MySQL database into web page using AJAX technique but the div content is repeated. I want to refresh the div without duplicate the information.
here is the code
api.php
<?php
require 'db.php';
$query = "SELECT * FROM variables";
$result = mysqli_query($con,$query);
$data = array();
while ( $row = mysqli_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
?>
client.php
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js">
</script>
</head>
<body>
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output"></div>
<script id="source" language="javascript" type="text/javascript">
function ajaxcall()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', timeout:2000,
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
$('#output').append("<b>id: </b>"+id+"<b> name: </b>"+vname)
.append("<hr />");
}
}
});
};
ajaxcall();
setInterval(ajaxcall, (1 * 1000));
</script>
</body>
</html>

Just change this
success: function(rows)
{
for (var i in rows)
to this
success: function(rows)
{
$('#output').html(''); // empty the container div and append new HTML
for (var i in rows)

try to use $('output').empty(); before the loop in order to avoid duplicating content.

Another way you can do it as:
var htmlData = '';
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
htmlData + ="<b>id: </b>"+id+"<b> name: </b>"+vname+"<hr />";
}
$('#output').html(htmlData);

Related

Refresh div that contains db data with a button

I'm trying to implements a button that can refresh the content of a div. This div contains values taken with ajax from the database.
There is a function that can do it?
This is the main page:
include("top.php");
include("funzioni.php");
is_logged();
?>
<script src="JavaScript/inserisciMateria.js" type="text/javascript"></script>
<body>
<?= include ("navbar.html") ?>
<div class="corpo">
<p class="titolo"> Scegli l'anno di cui ti interessa vedere i corsi disponibili! </p>
<hr>
<div class="anni">
<<button id="ShowPrimoAnno" >Primo Anno</button>
<button id="ShowSecondoAnno" >Secondo Anno</button>
<button id="ShowTerzoAnno" >Terzo Anno</button>
<button id="ShowQuartoAnno" >Quarto Anno</button>
<button id="ShowQuintoAnno" >Quinto Anno</button>
</div>
</div>
<script src="JavaScript/selezionaAnno.js" type="text/javascript"></script>
</body>
</html>
I tried to implement it on the button ShowPrimoAnno, in the file selezionaAnno
$(document).ready(function(){
$("#ShowPrimoAnno").click(function(){
$anno = ($(this).attr('data-value'));
$.getScript("inserisciMateria.js");
});
$("#ShowSecondoAnno").click(function(){
$anno = ($(this).attr('data-value'));
});
$("#ShowTerzoAnno").click(function(){
$anno = ($(this).attr('data-value'));
});
$("#ShowQuartoAnno").click(function(){
$anno = ($(this).attr('data-value'));
});
$("#ShowQuintoAnno").click(function(){
$anno = ($(this).attr('data-value'));
});
});
The main page and the function takes the content from a js file called inserisciMateria
var card1 = "<div class=\"container\"><div class=\"img-container\"><img src=\"imgs/";
var card2 = ".jpg\"></div><div class=\"content\"><div class=\"head\">"
var card3 = "</div><div class=\"preferiti\"><img src=\"imgs/wishlist.png\" alt=\"Mia Immagine\"></div><div class=\"inner-data\">";
var card4 = "</div><div class=\"anno\">Anno: ";
var card5 = "</div><div class=\"difficolta\">Difficolta\': ";
var card6 = "</div><div class=\"info\"><a href=\"";
var card7 = "\" target=\"_blank\">Per saperne di piĆ¹</a><i class=\"far fa-heart\"></i></div></div></div></div>";
$(document).ready(function(){
$.ajax({
url:'action.php',
type: 'GET',
success:function(response) {
var data = JSON.parse(response);
var n = data.length;
var finalCard= "";
for (var i= 0; i < n; i++) {
finalCard+=card1+data[i].Nome+card2+data[i].Nome+card3+data[i].Descrizione+card4+data[i].Anno+card5+data[i].Difficolta+card6+data[i].Link+card7;
}
$(".corpo").append(finalCard);
}
});
});
And it takes the data from the database by this file called action.php
<?php
$conn = new mysqli("localhost","root","","utenti");
$json=array();
$anno=2;
$sql="SELECT * FROM corsi WHERE anno = $anno";
$stmt=$conn->prepare($sql);
$stmt->execute();
$result=$stmt->get_result();
while($row=$result->fetch_assoc()){
array_push($json, $row);
}
echo json_encode($json);
?>
But it doesn't work... what's missing?
you are appending the content in
$(".corpo").append(finalCard);
you are selecting the area for content ".corpo" by class, JS doesn't know which of the different elements with this class to take and this can bring problems, select the area by ID instead.

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

javascript Setinterval prints repeated data from json

Hello i have this code server side to show online users:
header('Content-Type: application/json');
$array = array();
include 'db.php';
$res = mysqli_query($db, "SELECT * FROM `chatters` WHERE status = 1");//users are online
if(mysqli_num_rows($res) > 0){
while($row = mysqli_fetch_assoc($res)){
$array[]= $row; }
}
echo json_encode($array);
As response i get this:
[{"row_id":"40","name":"Krishan kumar","sex":"male","age":"24","country":"India","seen":"20:58:14", "status": "1"}]
So i on the show page i have this code to show the users:
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'json.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data) {
var len = data.length;
var txt = "";
for (var i = 0;i<len; i++) {
txt += "<p>"+data[i].name + "</p>";
}
$(".showUsers").append(txt);
console.log(txt);
}
}
});
}, 2000);
});
But the problem is in every 2 second i get name printed like this:
Krishan kumar
Krishan kumar
Krishan kumar
Krishan kumar
and it continues....
I want to show the users name printed only one time while still opening the request with setinterval() to check if new users are online. How to fix this issue?
Please clear previous user list before append new list. Use following code
setInterval(function(){
$(".showUsers").html('');
$.ajax({ ....

How can I pass a javascript value to php?

I want to add a javascript value to my php query. The code goes like this
<script>
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
<?php
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = '?' ");
?>
})
</script>
I want to put the value of categoryName to the query which I made in php. How will I do it.
Just spend a few hours trying to figure this out myself today. You can use ajax, and send the information using the data tag in an ajax query.
$.ajax({ url: 'file goes here',
data: {action: '0'},
type: 'post',
success: function(output) { //action }
});
The data tag gives you the information.
In your php:
$data = $_POST["action"];
you should use ajax to get the attribute from your clicked div and send it to a php page where you receive the "javascript variable" and use it as a php variable with $_POST like this:
<script type="text/javascript">
$(function() {
$(document).on('click', '.dropdown-menu li a', function() {
{
var categoryname = $(this).attr("id");
var dataString = 'categoryname'+ categoryname ;
$.ajax({
type: "POST",
url: "yourphppage.php",
data: dataString,
cache: false,
success: function(html)
{
$(".result").html(html);
}
});
return false;
});
});
Now in your php page:
$categoryname=$_POST['categoryname'];
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = $categoryname
");
It doesn't go this way, unless you make AJAX calls (see http://api.jquery.com/jquery.get/ and other answers).
The simplest solution (if you do not have too many categories, say a few hundreds tops) would be to cache the categories client-side in a Javascript variable, as in:
<script type="text/javascript">
var categoriesCache = <?php
$cache = array();
$result = mysqli_query($con, "SELECT id, category_name FROM tb_category");
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$cache[$row["category_name"]] = $row["id"];
}
echo json_encode($cache);
?>;
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
var categoryId = categoriesCache[categoryName];
});
</script>
<script>
$(document).on('click', '.dropdown-menu li a', function(e) {
e.preventDefault();
var categoryName = $(this).text();
// !! be careful here !! send web safe category name, `$(this).text();` or even better a numeric value.
$.get('runquery.php', {'category': encodeURIComponent(categoryName)}).done(function (data) {
// on success do something if needed
});
})
</script>
Put your PHP/SQL script in runquery.php
You can do this with Ajax
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
Php-script in a separate File like:
First you JavaScript file:
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
$.post("php-file.php",{cat_Name: categoryName});
});
then you php-file.php looks like:
<?php
$categoryname = $_POST['cat_Name'];
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = '?' ");
?>
if you want to use them again:
add to your PHP on the end:
$return = new array();
$return[0] = ;//your results in this array
echo json_encode($return);
then in your JavaScript should look like:
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
$.post("php-file.php",{cat_Name: categoryName}, function(data){
sccess_function(data);}, "json");
});
then add a function:
function succsess_function(data){
//do thing here
}

is there a way to populate other textbox when onchange?

here's my code. I'm new to php. so sorry in advance.
I actually want to check my input in txtbarcode and if it is existing in my database I would like to populate the txtdescription but I don't know how to do it or is it even possible?
<?php
$barcode = $_POST['txtbarcode'];
$query = "SELECT * FROM product WHERE product_id = '$barcode'";
$query_exe = mysql_query($query);
$chk_query = mysql_num_rows($query_exe);
if($chk_query > 0)
{
$row = mysql_fetch_assoc($query_exe);
?>
<th class = "textbox"><input type = "text" name = "txtbarcode" value = "<?php echo $row['product_id']; ?>" style="width:80px"/></th>
<th class = "textbox"><input type = "text" name = "txtdescription" value = "<?php echo $row['product_name']; ?>" style="width:100px"/></th>
<?php
}
?>
You can do this using JQuery Ajax. Just using the change listener on the barcode field, it will send an ajax call to the check_barcode file - which will query the table and echo the data you want. The result will then be placed into the other textfield via JavaScript :).
The following is a separate PHP file.
<?php
//-----------------------------------
//check_barcode.php file
//-----------------------------------
if (isset($_POST['barcode'])) {
$query = mysql_query("SELECT * FROM product WHERE barcode = '".$_POST['barcode']."'");
$num_rows = mysql_num_rows($query);
if ($num_rows > 0) {
$row = mysql_fetch_assoc($query);
echo $row['product_name'];
}
}
?>
The following is your HTML and JavaScript code.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#txtbarcode').change(function() {
var barcode = $(this).val();
$.ajax({
url: 'check_barcode.php',
type: 'POST',
data: {barcode: barcode},
success: function(result) {
$('#txtdescription').val(result);
}
});
});
});
</script>
<input type="text" name="txtbarcode" id="txtbarcode" />
<input type="text" name="txtdescription" id="txtdescription" />
UPDATE: Returning more data, and populating extra fields.
You'll need you echo a json array from the php script which contains both of the values.
For example:
echo json_encode(array('product_name' => $row['product_name'], 'unit_measure' => $row['product_name']));
and then within the JavaScript
<script>
$.ajax({
url: 'check_barcode.php',
type: 'POST',
data: {barcode: barcode},
dataType: 'json',
success: function(result) {
$('#txtdescription').val(result.product_name);
$('#unitofmeasure').val(result.unit_measure);
}
});
</script>

Categories

Resources