AJAX Search Function Not Updating Answer - javascript

I have an AJAX function that calls a php function to search a mysql database. The script fires off on keyup and the problem is on the first key press the html content is updated but it will not update after the initial keyup event
How do I make the page continuously update the html content with the new data that is coming in after every keyup.
My AJAX function,
var searchPath = "<?php echo $searchPath ?>";
$("#itemID").keyup(function (){
var itemID = $(this).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
});
And this is the php behind it all,
<?php
require_once ('Dbconfig.php');
$sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
?>

Related

How to insert PHP row record into AJAX url

I possible to insert update.php?id=" . $row["id"] . " into AJAX url?
I'm trying to make async sql row updating via form. I don't have specific id, because id is called on click.
JS
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
$.ajax({
type: "POST",
url: 'update.php?id=" . $row["id"] . "',
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
PHP where update.php call is located
$sql3 = "
SELECT id, potnik_id, ura, naslov
FROM prevoznik
ORDER BY HOUR(ura), MINUTE(ura) ASC;
";
$result = $conn->query($sql3);
$potnik = $row["potnik"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Spremenjena oblika datuma
$date = date_create($row["ura"]);
$ura_pobiranja = date_format($date,"H:i");
echo "<div class=\"row list divider-gray\">
<div class=\"col-1 fs-09 fw-600\">" . $row["id"] . " </div>
<div class=\"col-3 flex-vcenter-items fw-600 fs-09\">" . $row["naslov"] . " </div>
<div class=\"col-1 flex-vcenter-items fw-600 fs-09\">$ura_pobiranja</div>
";
if ($row["naslov"] !== null) {
echo " <div class=\"col-6 flex-vcenter-items fs-1\">Nastavi uro<form id='form' action='update.php?id=" . $row["id"] . "' method='POST'><input id='id' name='potnik' value='".$row["id"]."' type='hidden' /> <input id='cas' class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input id='submit' type='submit' value='Posodobi'> <label id=\"info\"></label></form></div>";
echo " </div>";
}
else {
echo " </div>";
}
}
} else {
echo "<div class=\"col flex-vcenter-items fw-100 fs-1\"><i class=\"far fa-frown-open pr-3\"></i>Nimaš še nobenih opravil
</div>";
}
First, you will want to fix a lot of your HTML. You have many repeating ID attributes for various HTML elements. This will cause many JavaScript issues and is incorrect syntax for HTML.
$html = ""
$id = $row['id'];
if ($row["naslov"] !== null) {
$html .= "<div class='col-6 flex-vcenter-items fs-1'>\r\n";
$html .= "\tNastavi uro\r\n";
$html .= "\t<form id='form-$id' action='update.php?id=$id' method='POST' data-id='$id'>\r\n";
$html .= "\t\t<input id='cas-$id' class='form-control fancy-border' type='text' name='posodobljeni_cas' />\r\n";
$html .= "\t\t<input id='submit-$id' type='submit' value='Posodobi'> <label id='info-$id'></label>\r\n";
$html .= "\t</form>\r\n</div>\r\n";
$html .= "</div>";
echo $html;
} else {
echo " </div>";
}
You can see a lot being done here. First we create a $html and $id variable to just make things easier. Now when we enter String data into the $html variable, if we're using " (double quote) for wrapping, we can just use $id directly in the string. We will also use ' (single quote) for wrapping all the HTML Element attributes.
Try this for your jQuery:
$(function(){
$("form[id|='form']").on('submit', function(e) {
e.preventDefault();
var form = $(this);
var id = form.data("id");
var cas = $("inptu[id|='cas']", form);
var info = $("input[id|='info']", form);
if(validate()) {
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
});
More Info on the selector: https://api.jquery.com/attribute-contains-prefix-selector/
Unable to test this as you have not provided a testing area. Hope it helps.
You can assign the PHP $row['id']; variable to a local JS variable and append it to the URL as shown below -
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
var id=<?=$row['id'];?>;
$.ajax({
type: "POST",
url: 'update.php?id='+id,
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});

How to use setInterval() when there's a param?

I'm trying to get a single div on a php page to refresh every 5 seconds.
In HTML I have: EDIT: NEW SCRIPT FUNCTION
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'game.php',
success:function(data){
$("#read_chat").html(data);
}
});
}
setInterval(callAjax, 5000);
});
</script>
And the function (in a php block) I'm trying to refresh is:
echo" <div class='read_chat' >";
function get_messages($db){
//get messages
$get_m = "select user_name, message, time, character_name from Chat NATURAL JOIN User LEFT OUTER NATURAL JOIN Character where Chat.game_id =".$_SESSION[game_id]." ORDER BY Chat.chat_id;";
$messages = $db->query($get_m);
//display messages
foreach ($messages as $row) {
//display each message in row
if ( $row['character_name'] == NULL){
echo "<div class='left'>" . $row['user_name'] . ": </div>";
}
else {
echo "<div class='left'>" . $row['character_name'] . ": </div>";
}
echo "<div class='center'>" . $row['message'] . "</div>";
echo "<div class='right'>" . $row['time'] . "</div>";
}
}
echo "</div>";
The display of this is only the CSSed block without any content. If I just call get_messages($db) all the chat from the database loads. How do I make this div refresh automatically? Thanks!
EDIT:
The name of the file is "game.php" and the php function is "get_messages()".
For the record I looked at:
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
and
Pass parameters in setInterval function
Javascript
setTimeout(function(){
$.ajax({url: "get_message.php", success: function(result){
var num_records = result.length,
i,
content;
for(i=0;i<num_records;i++){
if (result[i]['character_name'] !== null){
content += "<div class='left'>" + result[i]['character_name'] +": </div>";
}
else{
content += "<div class='left'>" + result[i]['user_name'] +": </div>";
}
content += "<div class='center'>" + result[i]['message'] + "</div><div class='right'>" + result[i]['time'] + "</div>";
}
$('.read_chat').html(content);
}});
}, 5000);
get_message.php
$get_m = "select user_name, message, time, character_name from Chat NATURAL JOIN User LEFT OUTER NATURAL JOIN Character where Chat.game_id =".$_SESSION[game_id]." ORDER BY Chat.chat_id;";
$messages = $db->query($get_m);
$response = array();
foreach ($messages as $row) {
$response[] = $row;
}
echo json_encode($response);
I'd suggest using jQuery $.load, see the example below:
setTimeout(function(){
$('.read_chat').load('get_message.php');
}, 5000);
You'll need to return nice html from the PHP script instead, but it's cleaner.

Creating jQuery array variable and Transferring array to another page PHP

I currently have this function exactly how I want it except for the jQuery at the bottom in which I am only alerting and not creating a real variable. It all works but I am stuck on how I can take all of the data from the jQuery script and then make it into a variable so that I can bring it to another page? Any ideas, NEED HELP!
function getGrade($id, $grades_array) {
$counter = 0;
$sql = "Select grade FROM grades";
$result = mysql_query($sql) or die (mysql_error());
echo '<select name="grades_selected" multiple="multiple" id="grades_selected">';
while ($row = mysql_fetch_array($result)) {
if ($row['grade'] != $grades_array[$counter]) {
echo "<option>" . $row['grade'] . "</option>";
} else {
echo "<option selected=" . $row['grade'] . ">" . $row['grade'] . "</option>";
$counter = $counter + 1;
}
}
mysql_free_result($result);
echo '</select>';
$_SESSION['test'] = $grades_array;
?>
<script>
$(document).ready(function() {
$('#grades_selected').change(function() {
alert($(this).val());
});
});
</script>
<?
}
You need to use ajax within on change function:
$(document).ready(function() {
$('#grades_selected').change(function() {
var variable = $(this).val();
$.ajax({
type: 'post',
url: 'target_page.php',
data: {variable : variable},
success: function (res) {
alert(res);
}
});
});
});
On target_page.php:
echo $_POST['variable'];

Confirmationbox inside a php whileloop

I have a site where I can update my Database. In the same page I also have a tabel with the most importent information in the database. This tabel is generated by a php while loop, and at the end of each row I have a Edit-button and a Delete-button. But I want to have a confirmation to the deletebutton. But I dont knopw how..
This is my code:
mysql_connect("localhost","user","pass") or die (mysql_error());
mysql_select_db("kalender") or die(mysql_error());
$data = mysql_query("SELECT * FROM event where datum > now() ORDER BY `pub` DESC LIMIT 0, 40") or die(mysql_error());
echo '<table>';
echo '<tr>';
echo '<th>Nr</th> <th>V.</th> <th>Tid</th><th>Dag</th><th>Datum</th><th>Ändra</th><th>Ta bort</th>';
echo '</tr><tr>';
while($info = mysql_fetch_array( $data))
{
$eventTime=$info['datum'];
$tid= strtotime($eventTime);
echo '<td width="20px">' .$info['id'] . '</td>';
echo '<td width="20px">' .$info['vecka'] . '</td>';
echo '<td width="40px">' .date("H:i", $tid) . '</td>';
echo '<td width="40px">'.$info['dag'] . '</td>';
echo '<td width="50px">' .date("j M", $tid) . '</td>';
echo '<td width="70px"><button id="checkoutbutton" type="button"><Edit</button></td>';
echo '<td width="70px"><button id="checkoutbutton" type="button">Delete</button></td></tr>';
}
echo '</table>';
Please help me!
You try this.
In PHP Script:
Update this in while loop
...
...
$tempId = $info['id'];
echo "<td width='70px'><a href='javascript:;' onClick='go_edit($tempId);'><input type='button' value='Edit'/></a></td>";
echo "<td width='70px'><a href='javascript:;' onClick='go_del($tempId);'><input type='button' value='Delete'/></a></td>";
...
...
In Javascript:
Add these functions in under php script
<script>
function go_edit(id) {
window.location.href = "http://kalend.mizgalski.se/update.php?id="+id;
}
function go_del(id) {
var choice = confirm('Are you sure want to delete?');
if(choice) {
window.location.href = "http://kalend.mizgalski.se/delete?id="+id;
}
}
</script>
You can do confirmation using javascript on the client side before sending data to the server

calling a php function in javascript

I dont know how to use ajax in my problem:
I have a function in php (assign) that update a temporary table in database, I want to when user user click on a button (feedback function that is defined in javascript) this function (assign) run, what should I do?
<script>
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign(1);
}
else{
assign(0);
}
}
}
</script>
<?php
$con = mysql_connect("localhost", "root", "")
or die(mysql_error());
if (!$con) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db("project", $con)
or die(mysql_error());
$result = mysql_query("select * from words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
function assign($checkparm){
//mysql_query("update words set checking=$checkparm ");
mysql_query("create TEMPORARY TABLE words1user1 as (SELECT * FROM words) ");
mysql_query("update words1user1 set checking=$checkparm ");
}
mysql_close($con);
?>
<button onclick="ShowMeanings()">ShowMeanings</button>
<button onclick="feedback()">sendfeedback</button>
There is only one way to call a php function after the page is loaded:
1.ajax:
function callPHP() {
$.ajax ({
url: "yourPageName.php",
data: { action : assign }, //optional
success: function( result ) {
//do something after you receive the result
}
}
in your PHP, write
if ($_POST["action"] == "assign")
{
assign(your parameters); //You need to put the parameters you want to pass in
//the data field of the ajax call, and use $_POST[]
//to get them
}
There are many great guides on the internet. I will however suggest you get too know JQuery. It will help you on your learning curve.
function ajaxCall(){
$.ajax({
type: "GET",
url: "scripts/on/serverside.php"
});
};

Categories