Retrieving JSON data and display in a table with AJAX - javascript

I am very new to programming with jQuery. I've spent quite a while trying to move forward with this, and I've managed to get some of it done. But I've really hit a wall and I can't seem to find help from anywhere/anyone.
Scenario:
I am using a select box to store different music genres, which I have retrieved via PHP/MySQL.
<?php
include 'connectingDB.php';
$catSQL = "SELECT * FROM category ORDER BY catDesc";
$queryresult = mysql_query($catSQL)
or die (mysql_error());
echo "<select id= \"catID\">";
while ($row = mysql_fetch_assoc($queryresult)) {
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = \"$catID\">$catDesc</option>\n";
}
echo "</select>";
mysql_free_result($queryresult);
mysql_close($conn);
?>
When I click on a genre, I want all of the related CDs and CD information to be retrieved in JSON format and dynamically displayed in a table using AJAX (below the select box on that same page)
<?php
header('Content-type: application/json');
include 'connectingDB.php';
$category = $_REQUEST['catname'];
$sql = "SELECT `CDID`, `CDTitle`, `CDYear`, `pubID`, `CDPrice`
FROM `tiptop_cd`
INNER JOIN tiptop_category
ON tiptop_cd.catID=tiptop_category.catID
WHERE catDesc = '{$category}'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
while($row = mysqli_fetch_array($result)){
$returned[] = $row;
}
echo json_encode($returned);
?>
All of the above code works on its own. But I'm looking to connect it all together. I think it needs to be via an onchange event in jQuery?
I've got an alert to pop up after clicking a category, but that's as far as I can get..
$(document).ready(function(){
$("#catID").change(function(){
alert("The text has been changed.");
});
});
Does it need to be in a foreach loop? Or a foreach within a foreach?
To summarize, I'm trying to understand how to: display the cds and cd information that are related to the specific category that is currently selected, in a dynamic table with ajax
Any help is massively appreciated.

hopefully this can get you started
$(document).ready(function () {
$("#catID").change(function () {
$.post("index.php?catname=" + $(this).val(), function (data) {
var table = $('<table></table>'); //create table
$.each(data, function (index, value) { //loop through array
var row = $('<tr></tr>'); //create row
var cell1 = $("<td></td>").val(value.CDID); //create cell append value
//etc
row.append(cell1); //append cell to row
table.append(row); //append row to table
});
$('#div').append(table); //append table to your dom wherever you want
});
});
});

You may want to use AJAX for this purpose. Ajax will allow you to send the user's choice (ie. the dropdown selection) to a back-end PHP file.
The PHP file will process the received data (ie. the user's choice) and perform a database lookup based on that info. It will take the result from db and construct (in a variable) the required HTML for the table, and then echo back the contents of that variable -- which will be received in the AJAX procedure's success: (or .done() to use promise syntax) function.
INSIDE the success/done function, you can use received data. For example, you can use the jQuery .html() method to replace the contents of a specified DIV with the HTML you received.
My approach would differ from the other proposed solutions in the following ways:
I prefer using the full $.ajax() syntax, as it allows for greater structure, which makes it somewhat easier to understand/manipulate at first. Note that .post(), .get() and .load() are all shortcut forms of $.ajax() that make certain assumptions in order to streamline the process. I suggest learning the $.ajax() format first, and then utilizing the others. Having done gazillions of ajax blocks myself, I continue to use $.ajax() most times. Perhaps it is a preference, but I find it much easier to use/read/review -- and it also allows additional params that the others do not, which makes it more flexible and useful**.
It is necessary to use a second .PHP file to act as your ajax processor. You cannot use the same .PHP file that contains your AJAX code block. See this answer.
The place to construct the HTML table is in the PHP (processor file). As mentioned, construct it all in a variable and then, at the end, output that variable:
Note how the $r variable is constructed in the while loop, and only ECHOed out at the end.
$aContact_info = mysql_query("SELECT * FROM `contacts`");
$r = '<table>';
while ($rrow = mysql_fetch_array($aContact_info)) {
$r .= '<tr>
<td>
Name:<br/>
<input type="text" id="first_name" name="first_name" value="'.$rrow['first_name'].'">
<input type="text" id="last_name" name="last_name" value="'.$rrow['last_name'].'">
</td>
<td>
Email:<br/>
<input type="text" id="email" name="email" value="'.$rrow['email1'].'">
</td>
<td>
Cell Phone:<br/>
<input type="text" id="cell_phone" name="cell_phone" value="'.$rrow['cell_phone'].'">
</td>
</tr>
';
}
$r .= '</table>';
echo $r;
Here are some examples that should help:
Simple explanation of AJAX
Example with MySQL lookup in PHP Processor file
** Differences between .get() and .post() and $.ajax():
GET vs POST in AJAX calls
Kevin Chisholm
Sychronous AJAX

another (faster) method would be to return an html table as a string and inject it into the DOM. generate the table in your PHP handler, then do $('#div').load('/index.php?catname=catname'); or do $.get like below
$(document).ready(function () {
$("#catID").change(function () {
$.get({
url: 'index.php',
data: { catname: $(this).val() }
dataType: 'html',
success: function (html) {
$('#div').html(html);
},
error: function (xhr, err) { displayErrorMessage("Error: \n\nreadyState: " + xhr.readyState + "\nstatus: " + xhr.status + "\nresponseText: " + xhr.responseText, 'nosave'); }
});
});
});

Related

Store JavaScript variable in a php variable without page refresh

I've been been through numerous articles on here and tried dozens of variations including ajax. What I want to do is click a button and store the id of that button in a php variable without having to refresh the page.
I've tried using isset and POST and I get some variation of Undefined key array.
Ajax was suggested but when I use ajax I can get the variable stored, but I'm unable to get it into a php variable.
Current setup...
I have an HTML button from which I need the id stored in a php variable so I can use it in another SQL statement. This button is part of an HTML table of MySQL records returned from the db.
<input type='button' value='Edit' name='editbtn' onclick='edit(this.id)' id = '" . $row['id'] . "'/>
JavaScript...
function edit(clicked_id){
var selid = clicked_id;
var seleid = selid.toString();
$.ajax({
type: 'post',
data: {name: seleid},
datatype: 'text',
success: function(data){
console.log(name);
alert("Success, data is: " + data); // This correctly returns the id of the button clicked
},
});
}
The PHP at the top of the page is...
if(isset($_POST['name']) && !empty($_POST['name'])){
ob_clean();
$varid = $_POST['name'];
echo $varid;
exit;
}
PHP is not receiving anything. Is there a way to do this? I guess it's a backend/frontend issue?
Note: I have been able to store a JavaScript variable in an HTML tag but I've been unable to use it as part of a SQL statement, even after trimming the tags off of it.
Please help and thank you!
Try something like this in your php code :
$data = json_decode(file_get_contents('php://input'), true);
if(isset($data['name']) && !empty($data['name'])){
ob_clean();
$varid = $_POST['name'];
echo $varid;
exit;
}

automatically load dynamic content with ajax and php

I have a PHP chat application that automatically get messages from database and displays it, currently everything works fine but page must be manually reloaded to display new messages .. How do I implement JQuery ajax to get the messages or silently refresh the specific messages list div without refreshing the whole page? Here is my code (not the full code on the page but the main PHP part I want to use ajax on)
Some answers I read online specified that the PHP code must be on a separate file but Some of the functions and variables in the code below depends on the main file holding this code therefore making it useless if put in a separate file.
<?php
// Attempt select query execution
global $db;
$id = $_GET["id"];
$sql = "SELECT * FROM msg WHERE id='$id' ";
if ($result = $db->query($sql)) {
if ($result->rowCount() > 0) {
while ($row = $result->fetch()) {
echo '<div class="chat-messages-item ' . chattype($row['sender']) . '">';
echo '<div class="chat-avatar chat-avatar-lg circle"><img src="' . senderpic($row['sender'], 'thumbnail', '100', '100') . '" alt=""></div>';
echo '<div class="chat-messages-content">';
echo '<div class="chat-messages-bubble ' . $msg_visibility . '">';
echo '<p>' . $row['message'] . '</p>';
echo '</div>';
echo '<ul class="chat-messages-info">';
echo '<li>';
echo '<div class="chat-time chat-seen"><span>' . $row["time"] . '</span>';
echo '</li>';
echo '</ul>';
echo '</div>';
echo '</div>';
}
unset($result);
} else {
echo "<p class='lead'><em>No Chat</em></p>";
}
} else {
echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}
Thanks
[EDIT]
What i've tried :
1. Moving the code above into a separate PHP file and using jquery to to get the page with the following js code but nothing appears and no errors displayed. if i open the page in browser it displays the list of all messages
function update() {
$.get("aj/messages.php", function(data) {
$("#allmessages").html(data);
window.setTimeout(update, 10000);
});
}
here is the page structure
- Message.php (the main message page that displays other chat information like contacts, messages list, messages, send message input etc)
aj/msg.php (a php page that gets all the messages from database and wraps it in style/css/html which is also the php code above and expected to be inside a div with the id="allmessages" located inside Message.php)
As you mentioned, it is a good practice to separate your PHP Code and your HTML/JavaScript Code. Yes, this may mean you have to write more PHP Code, yet if PHP Scripts must use the same code snippet, this is where PHP include and include_once can be used so that you can store specific functions in one script and them import them to other scripts. Please see:
https://www.php.net/manual/en/function.include.php
Currently, there is not enough of an example to be able to properly answer your question. I would suggest that you either create a more functional PHP Script that can accept new Chat input or another that can show the current chat transcript from the Database.
In this use case, each member of the chat must send new data to the database and then periodically get/refresh their view of the transcript. You can send new data to the database at any time and then based on a specific refresh rate, look for differences in the transcript. So your JavaScript will have a few function. Something like
startChat()
sendMessage()
getMessages()
endChat()
These will send data to the PHP Script and the PHP Script may give a response. This can all be done with AJAX. AJAX is the use of HTTP GET or POST along with JavaScript. This is basically how a Client Side Script language like JavaScript can talk to a Server Side Scripting language like PHP. PHP is processed when the HTTP request is handled by the Web Server and once the data is sent to the browser, PHP can no longer interact with it, this is why it's a pre-processor. JavaScript can only run in the browser and is processed after all the data from the server is received by the browser.
So if you have some HTML like:
<div class="chat-window">
<div class="transcript">
</div>
<div class="user-input">
<input type="text" /> <button>Send</button>
</div>
</div>
You can use JavaScript to perform tasks when the User types in text and clicks the button. One of those tasks can be to collect the text entered by the User and send it to the PHP Script to be added to the Database. Another task can be to update the field if there are any new messages in the Database since the last time the script checked.
Using jQuery Framework for JavaScript, it might be something like:
function sendMessage(user, txt){
$.post("chat_input.php", { u: user, msg: txt });
}
This creates a HTTP POST call to a PHP Script with a payload of info, such as the User and some Text. You'll need to collect this information from the HTML based on a specific Event.
$(".user-input > button").click(function(){
sendMessage("jsmith", $(this).parent().find("input").val());
});
This bit of jQuery binds a anonymous function as a callback to the click event. When the User clicks the button, it runs that code in the function.
The PHP Code might be something like:
<?php
$user = $_POST['u'];
$txt = $_POST['msg'];
include_once 'db_conn.php';
$stmt = $mysqli->prepare("INSERT INTO 'chat' VALUES (?, ?)");
$stmt->bind_param("ss", $user, $txt);
$stmt->execute();
$stmt->close();
?>
As you can see, this is very rudimentary and will not answer your overall question. You must do a lot of research and I would advise you find example PHP/jQuery Chat example that you can learn from or begin taking some JavaScript/jQuery Tutorials.
See More:
https://api.jquery.com/jQuery.post/
https://api.jquery.com/click/
https://api.jquery.com/category/selectors/
Update
If your PHP Code is setup to collect some data and "send" it back to an AJAX script, then you would prepare it like any other PHP Page, and output the data to the page in some fashion.
<?php
$results = new array();
/* Assuming connection to DB */
/* Assuming SQL Query and result set is now in $results */
header('Content-Type: application/json');
echo json_encode($results);
?>
When you navigate to this page, you will see the collected data in JSON format. Something like:
[
{
"sender": "jsmith",
"message": "Hello World!",
"time": "12/27/2019 10:28:01"
},
{
"sender": "ssmith",
"message": "shut up john",
"time": "12/27/2019 10:28:12"
}
]
When AJAX sends a request to this script, it will get the data back and can then iterate each item in the array, create HTML for it as needed. You can use HTML or Text or XML too, I just use JSON when possible.
In jQuery, this function might look like:
function getMessages(){
var lastMessage = $(".chat-messages-item:last .chat-time").text().trim();
$.get("chatmessages.php", function(data){
$.each(data, function(i, msg){
if(lastMessage < msg.time){
var newMsg = $("<div>", {
class: "chat-messages-item " + chattype(msg.sender),
}).insertAfter($(".chat-messages-item:last"));
var av = $("<div>", {
class: "chat-avatar chat-avatar-lg circle"
}).appendTo(newMsg);
$("<img>", {
src: senderpic(msg.sender, 100, 100),
class: "thumbnail"
}).appendTo(av);
$("<div>", {
class: "chat-messages-content"
}).html("<p>" + msg.message + "</p>").appendTo(newMsg);
}
});
});
}
setTimeout(getMessages, 10000);
This is just an example based on your code.

fetch column from sql data base into html pull down menu using php

I am quite new to java script and i am struggling with the following.
I am using php 7 and trying to call data from sql database, the data is a table, but i want to select one column from that table and put it into a pull down menu in html.
So, I used mysqli prepare function as follows. I have two question, the first: can this run inside the same php where another sql query was open. the second is how to use what is returned (the column in that case) and put it into a pull down menu the user can choose from in html.
what I tried is to put that code inside the code as I saw in another post. but the data cannot be populated.
EDIT:
The database is oracle so i cannot use mysqli, i used instead the following code
but i am getting only the first number in the column and not displaying it in the pull down menu, how can i use foreach to loop over all retrieved numbersand use that in the pull down menu?. I am confused, where to include the select statement for html pull down menu
<td>
<?php
require_once("..//ora_db");
// Create connection
$oracle_db = new ora_database("abc");
// Check connection
$sql = "SELECT * FROM cvbh";
$cursor = $oracle_db->execute_sql($sql);
$counter=0;
while (OCIFetchInto ($cursor,$row))
{
$number= $row[1];
# echo "<select><option value="number">$number</option></select>";
$counter ++;
}
print_r($number);
?>
<select><option value="number">number</option></select>
</td>
First of all there is no need for javascript here.
Answer to your first question: Yes you can run multiple query's on the same page.
Answer to your second question: You can easily generate html code based on your for loop by doing something like this
<select>
foreach ($stmt->get_result() as $row)
{
echo "<option> $row['Column'] </option>";
}
</select>

Sub Total is not getting the changed value from database to input box

I am trying to get the sub total updated, when adding the items to the database from java-script. But, currently it displays the first amount and not updates when adding items. (But when runs the query from phpMyAdmin it works correctly)
java-script code
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
HTML code
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" / >
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
The problem is, that when you declare the function with PHP, the function cannot be refreshed by using PHP again... because everything that PHP does, happens before the page is loaded, therefore, let's say as an example:
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
this 'value' from $rowT[0] = 10 from the first query, it will always be 10, because that is what PHP read from the database when it checked upon page load. You will have to use something like jquery or ajax to read the contents of another php file that contains the value (the mysqli_fetch_row).
PHP is literally named hypertext preprocessor, meaning everything that is processed before the html is printed to the user. (before the page has finished loading)
try experimenting with this: https://api.jquery.com/jquery.get/
ShowSubTotal() will bring only the value when the page loads. Dynamic actions will not make any changes, because php needs an server request to operate.
You should bring the subtotal through a dynamic request (ajax) call.
Or:
Use javascript to sum the values and set the value in your txtSubTotal field. If you go for this option, remember to not rely on this value on your server side processing, as it may be adulterated by users.
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);
try this code
$("#btnSave").click(function(){
$.ajax({
url : file_url.php,
type : 'post',
data : {
get_subtotal:"subtotal",
},
success : function( response ) {
alert(response);
$("#txtSubTotal").val(response );
},
error: function(response) {
console.log(response);
}
});
});
file_url.php
if(isset($_POST['get_subtotal'])){
$resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
echo $rowT[0];
}

How do I update MySQL database using a button's onclick event?

Ok I know this can't be done using PHP and I think it's done by using Ajax/Javascript...
Unfortunately I'm very low on these and I need your help..
So I have made a <select> based on what players there are playing for the team the user has selected. It works fine, no problems.
What I need for it is a button that will add 1 XP to the player that the user has selected.
<?php
$query = mysql_query("SELECT `team` FROM `users` WHERE `username`='". $_SESSION['username'] ."'");
$row2 = mysql_fetch_assoc($query);
$result = mysql_query("SELECT `name` FROM `players` WHERE `team`='". $row2['team'] ."'");
$dropdown = "<select name='players'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['name']}'>{$row['name']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
<button onclick="">Support</button>
In my case, the update would look something like this:
$oldxp = mysql_query("SELECT `xp` FROM `players` WHERE `name`="the option the user selected,got stuck here");
mysql_query("UPDATE `players`SET `xp`=''". $oldxp ."' + 1' WHERE `name` = "the option the user selected, got stuck here");
So what I need is how do I get what the user has selected and replace it with that "the option user selected, got stuck here" and how do I do this in Java since I can't put that PHP code in the onclick event because it won't work?
Thanks a lot.
Change your button html
-- add a onclick function
html:
<button onclick="saveData()">Support</button>
onclick in the button send an ajax request to the server and run your query.
jquery:
function saveData(){
$.ajax({
type: "POST",
url: "your_php_page.php",
data: { name: $("select[name='players']").val()},
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
}
php:
your_php_page.php:
$sql = "UPDATE `players`SET `xp`= `xp`+ 1 WHERE `name` = '".$_REQUEST['name']."'";
if(mysql_query($sql)){
return "success!";
}
else {
return "failed!";
}
you should not use mysql_* since it is deprecated. you should use pdo or mysqli_*
jquery ajax api doc
First off, Java and Javascript are totally different languages. They share very little except a name and their both a programming language.
You'd need to use Ajax to do this, so you'd need a PHP file on your server that the AJAX can request to run the query you're wanting. You would then use AJAX to request this file to add the XP, I suggest you use jQuery (http://jquery.com/) for AJAX calls as its much easier to use than pure javascript.
Once you have included jQuery into your site you can use the following to make an ajax call:
$.ajax({
type: 'post',
url: 'http://domain.com/myscript.php',
success: function(data){
// callback function
}
});
Documentation: https://api.jquery.com/jQuery.ajax/
You could wrap the ajax call in a function and then call that function using onclick on the button you're wanting to use.
eg:
<button onclick='javascript:ajaxCall()'>Call AJAX</button>
function ajaxCall(){
// include code above
return false; // not always essential, but I usually return false.
}

Categories