Refresh div that contains db data with a button - javascript

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.

Related

How to refresh the comments with ajax?

I was to use ajax to automatically update the page so when a new comment is added I don't have to refresh the page to see it. I have a commented out section in my code where I have tried to do this. I can add posts new comments but when I do I have to refresh the page in order to see the new comment and I just want it to appear automatically when posted.
$(document).ready(function() {
var comments = document.getElementById("allcomments").value;
//Get Storage
var username = window.localStorage.getItem("username");
// Call Ajax for existing comments
$.ajax({
type: 'GET',
url: 'URL.php',
success: function(result) {
var arr = JSON.parse(result);
for(var i = 0; i < arr.length; i++) {
var obj = arr[i];
var output = document.getElementById("allcomments");
output.innerHTML += '<div class="comment-container"><div class="username">'+obj.username+'</div><div class="comment">'+obj.comment+'</div><div class="date">'+obj.commDate+'</div><div class="like">'+obj.sentiment+'</div></div>';
}
}
});
return false;
});
/*//Refresh comments
var int=self.setInterval("showComments()",5000);
function showComments(){
$.post("comments.php", function ( arr ) {
$("#allcomments").html( arr );
});
} */
HTML
<h1>Forum</h1>
<form id="forumPost" method='POST'>
<textarea rows="3" col="60" name="comment" placeholder="Create a Post..." id="comment"></textarea>
<button><input type='submit' name='submit' value='Post' class="post"></button>
</form>
<p id="error" class="errormessage"></p>
<p id="allcomments" class="postmessage"></p>
<div class="comment-container">
<div class="username"><!--obj.username--></div>
<div class="comment"><!--obj.comment--></div>
<div class="date"><!--obj.commDate--></div>
<div class="like"><!--obj.sentiment--></div>
</div>
PHP
// Print out existing comment
$query = "SELECT comments.commDate, comments.ID, comments.username, comments.comment, users.username, comments.sentiment FROM comments LEFT JOIN users ON comments.username = users.username";
$result = mysqli_query($db_server, $query);
if (!$result)
die("Database access failed: " . mysqli_error($db_server));
while ($row = mysqli_fetch_array($result)) {
$comments[] = $row;
}
mysqli_free_result($result);
require_once("db_close.php");
echo json_encode($comments);
Try removing your code from this block-
$(document).ready(function() {
}
Then change
<button><input type='submit' name='submit' value='Post' class="post"></button>
to:
<button><input type='button' id='submit' value='Post' class="post"></button>
And now put your ajax post code in this block:
$("#submit").on("click", function(){
});

Function is not defined when call Js function in PHP Laravel

I'm working on a Laravel project. In my blade view, I have a Javascript function like this:
<script type="text/javascript">
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>
Then, I call this function in the body tag and pass two php parameters to it:
<?php echo "<script> autoFill('$dropDown', '$emptyDropDown'); </script>"; ?>
But when I run this, I got a error: "Uncaught ReferenceError: autoFill is not defined".
Here is my full code in blade view if you want:
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title m-b-md">
Activiti Form
</div>
#if(isset($formDataResult) && isset($dropdownValue))
<div class="links">
<form action="{{ url('handle-form') }}" method="POST">
<!--Loop form data and call components to render form-->
#foreach($formDataResult as $formDataValue)
<div class="links">
#if($formDataValue['type'] == 'select')
#if(array_key_exists('description',$formDataValue))
<?php
$dropDown = $formDataValue['name']
?>
#component('components/InputSelect',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name'],
'enumData' => $dropdownValue
])
#endcomponent
#else
<?php
$emptyDropDown = $formDataValue['name'];
?>
#component('components/EmptyInputSelect',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name']
])
#endcomponent
#endif
#elseif($formDataValue['type'] == 'text')
#component('components/InputText',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name'],
'type'=>$formDataValue['type']
])
#endcomponent
#endif
<br>
</div>
#endforeach
<?php echo "<script> autoFill('$dropDown', '$emptyDropDown'); </script>"; ?>
<!--Hidden input to store task id-->
#component('components/HiddenInput',[
'id' => $taskId
])
#endcomponent
<div>
<input type="reset" value="Reset Form">
<button type="submit">Complete Task</button>
</div>
</form>
</div>
<!--If don't have form data, show error alert-->
#else
<div class="alert">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<strong>Notice!</strong> There are no tasks at this moment!
</div>
#endif
</div>
</div>
</body>
<script type="text/javascript">
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>
How I can fix this?
Thank you very much!
You are trying to call the function before you define it. Put the <script type="text/javascript">...</script> defining the function before your <script> autoFill('$dropDown', '$emptyDropDown'); </script> which tries to call it.
You can read js value to using PHP. But you can print js value to HTML screen.
You have a <span> or <div> tag with class or id attribute then you can place your value inside that.
Here is your js functionality
<script>
// whatever value you need in your js from PHP. you need to below code.
let dropdown = <?php echo $dropDown; ?>
let emptyDropdown = <?php echo $emptyDropDown; ?>
// now pass your js variables here.
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
let $this = $(this);
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>

Stop repeating div content in PHP AJAX MySQL

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

My SQL PHP Generated edit button is only working once

I'm developing a web application which is like a notepad or a to-do list with php sql html css jquery
The query gets the list at index page and displays it and on displaying it adds a button with an "edit" class.
When they press on the edit the edit works but only once after submitting.
On submitting the button launches an ajax call with jQuery to another PHP file which edits the data and and displays all the items from the database again.
There's also an "add item" button which adds a new item. Which on submit adds a new item and also gets everything again from the database and displays it (also ajax).
The bug is either after submitting a new item or after editing, the edit button stops working
Please check the snippet below -- snippet 1 is the jquery, snippet 2 is the file to be run on ajax call, and snippet 3 is the index php file:
$("#submit").click(function(){
textarea = $("#textarea").val();
date = $("#date").val();
if(textarea == "" || date == ""){
$("#message").html("<span class='error'>Make sure you didn't leave anything empty");
}
else{
$("#message").html("");
submitItem();
$("#contentCont").fadeOut(200);
}
});
$(".edit").click(function(){
i = "edit";
itemID = $(this).attr("name");
var dateValue = $("#date"+itemID).text();
var statusValue = $("#status"+itemID).attr("name");
var textboxValue = $("#textbox"+itemID).text();
var categoryValue = $("#category"+itemID).text().toLowerCase();
$("#contentCont").fadeIn(200);
$("#textarea").val(textboxValue);
$("#date").val(dateValue);
$("#categories").val(categoryValue).prop("selected",true);
$("#status").val(statusValue).prop("selected",true);
});
function submitItem(){
textarea = $("#textarea").val();
status = $("#status").val();
category = $("#categories").val();
date = $("#date").val();
var ajaxReq = new XMLHttpRequest();
ajaxReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("todoCont").innerHTML = this.responseText;
}
}
ajaxReq.open("POST","../php/addItem.php",true);
ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxReq.send("textarea="+textarea+"&category="+category+"&status="+status+"&date="+date+"&itemID="+itemID+"&i="+i);
}
<?php
session_start();
require("server.php");
$cnx = new mysqli($server_name,$server_username,$server_password,$db);
$category = validate($_POST["category"]);
$item = $_POST["textarea"];
$date = $_POST["date"];
$status = validate($_POST["status"]);
$userID = $_SESSION["userID"];
$itemID = $_POST["itemID"];
$i = $_POST["i"];
$searchForCategoryID = "SELECT * FROM categories where userID='$userID' AND categoryname = '$category'";
$result = $cnx->query($searchForCategoryID);
$row = $result->fetch_assoc();
$categoryID = $row["CategoryID"];
if ($i === "new"){
$addItem = "INSERT INTO Items(userID,ItemValue,DueDate,CategoryID,Status) VALUES ($userID, '$item' , '$date' , $categoryID,'$status')";
$cnx->query($addItem);
}
else if ($i === "edit"){
$editItem = "UPDATE Items SET ItemValue='$item' , DueDate='$date' , CategoryID = $categoryID,Status='$status' WHERE itemID = $itemID " ;
$cnx->query($editItem);
}
$getTableRows = "SELECT * FROM Items WHERE userID = $userID ORDER BY DueDate";
$result = $cnx->query($getTableRows);
if($cnx->error){
echo "Could not get your stuff";
}
if($result->num_rows > 0){
while ($rows = $result->fetch_assoc()){
$getCategory = "SELECT CategoryName FROM Categories WHERE CategoryID = " . $rows["CategoryID"] . ";";
$result2 = $cnx->query($getCategory);
$rows2 = $result2->fetch_assoc();
if ($rows["Status"] == "ongoing"){
$status = "ongoing";
}else
if ($rows["Status"] == "overdue"){
$status = "overdue";
}else
if ($rows["Status"] == "done"){
$status = "done";
}
echo ' <div class="box-container">
<div class="right">
<div class="textbox">
<span id="textbox'.$rows["itemID"].'">'. $rows["ItemValue"] .'</span>
</div>
<div class="footer">
<div class="status '. $status .'" id="status'.$rows["itemID"].'" name="'.$status.'"></div>
<span class="date" id="date'.$rows["itemID"].'">'.$rows["DueDate"].'</span>
<span class="category" id="category'.$rows["itemID"].'">'.ucfirst($rows2["CategoryName"]).'</span>
<button type="button" name="'. $rows["itemID"] .'" class="btn btn-info edit">Edit</button>
</div>
</div>
</div>';
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php session_start();?>
<?php
include("server.php");
$cnx = new mysqli($server_name,$server_username,$server_password,$db);
$userID = $_SESSION["userID"];
<!--This is how the info is shown and the EDIT button is made-->
echo ' <div class="box-container">
<div class="right">
<div class="textbox">
<span id="textbox'.$rows["itemID"].'">'. $rows["ItemValue"] .'</span>
</div>
<div class="footer">
<div class="status '. $status .'" id="status'.$rows["itemID"].'" name="'.$status.'"></div>
<span class="date" id="date'.$rows["itemID"].'">'.$rows["DueDate"].'</span>
<span class="category" id="category'.$rows["itemID"].'">'.ucfirst($rows2["CategoryName"]).'</span>
<button type="button" name="'. $rows["itemID"] .'" class="btn btn-info edit">Edit</button>
</div>
</div>
</div>';
}
?>
you need to register your events more globally:
$("body").on("click", "#submit", function(){
});
and
$("body").on("click", ".edit", function(){
});
You need to delegate as the element is getting created dynamically.
Change the below line:
$(".edit").click(function(){
to:
$(".edit").on('click', function(){
And the same applies for
$("#submit").click(function(){
to
$("#submit").on('click', function(){

Ajax call not working after page reload.

I have my home page in php with checkboxes by the names of brand and store list.and in the end one submit button which is given below
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="brand"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
function get_store_value(){
var d_value=[];
$('input[name="store"]:checked').each(function () {
d_value.push(this.value);
});
return d_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function (e)
{e.preventDefault();
alert("hi");
//var os = $('#originState').val();
//var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
var store=get_store_value();
//var queryString = "os=" + os;
var data = "?ser=" + ser;
var queryString = "&ser=" + ser;
alert(ser);
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: {ser:ser,store:store},
dataType : 'html',
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>
brand
<input type="checkbox" name="brand" value="Sunbaby" />Sunbaby
<br/>
<input type="checkbox" name="brand" value="Advance Baby" />Advance Baby
<br/>
store
<br/>
<input type="checkbox" name="store" value="JCPenny" />JCPenny
<br/>
<input type="checkbox" name="store" value="Supermart" />Suoermart
<br/>
<input type="checkbox" name="store" value="Target" />Target
<br/>
<button id="btnSubmit">sort</button>
<div id="results">
</div>
</body>
</html>
On click of submit,button it goes for ajax call and displays the result in results div.
<?php
include('connection.php');
$query=$_POST['ser'];
$query1=$_POST['store'];
echo $query;
echo $query1;
$query=explode(",",$query);
$query = array_filter($query);
$query1=explode(",",$query1);
$query1 = array_filter($query1);
$result=count($query);
$result1=count($query1);
//echo $result;
echo $result1;
$parts = array();
$limit = 10;
$offset = 0;
if(!empty($query))
{
foreach( $query as $queryword ){
$parts[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
$brandsql='SELECT * FROM XML WHERE ('.implode ('OR',$parts).') order by price asc';
$brandsql1=mysql_query($brandsql);
$numrows = mysql_num_rows($brandsql1);
$countArray=array();
print($brandsql);
echo "<br />";
while($row = mysql_fetch_array($brandsql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
$parts1=array();
if(!empty($query1)){
foreach( $query1 as $queryword1 ){
$parts1[] = '`STORE` LIKE "%'.$queryword1.'%"';
}
$storesql='SELECT * FROM XML WHERE ('.implode ('OR',$parts1).') order by price desc';
$storesql1=mysql_query($storesql);
$numrows1 = mysql_num_rows($storesql1);
$countArray=array();
print($storesql);
while($row = mysql_fetch_array($storesql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
?>
<?php
foreach($countArray as $array)
{
?>
<div>
hi</div>
<?php $i++; } ?>
But iF I refresh my page or press F5 from keyboard,after getting content in results div,it goes back to previous content i.e.first page with checkboxes and submit button.
Please tell me where m doing wrong in the code or what do i need to include so that after ajax call if i refresh the page,content should remain same,should not go to previous content...
Use setTimeout() to run a refresh on the page after X seconds inside the AJAX callback, after you display content.
You could use the _SESSION variable in your PHP script to store what checkboxes were selected most recently, and display results on your results div, appropriately.
Although, if a user clicks refresh he might want to reset the choices he made anyway. You could give him a warning that his changes will be lost if he refreshes.
window.onbeforeunload = function() {
return confirm("You have made changes to this form. Do you want to continue without saving these changes?");
}

Categories

Resources