I am trying to figure out how to retrieve data from a MySQL database using an AJAX call to a PHP page. I have been following this tutorial
http://www.ryancoughlin.com/2008/11/04/use-jquery-to-submit-form/
But i cant figure out how to get it to send back json data so that i can read it.
Right now I have something like this:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "ajax.php",
data: "code="+ code,
datatype: "xml",
success: function() {
$(xml).find('site').each(function(){
//do something
});
});
});
My PHP i guess will be something like this
<?php
include ("../../inc/config.inc.php");
// CLIENT INFORMATION
$code = htmlspecialchars(trim($_POST['lname']));
$addClient = "select * from news where code=$code";
mysql_query($addClient) or die(mysql_error());
?>
This tutorial only shows how to insert data into a table but i need to read data. Can anyone point me in a good direction?
Thanks,
Craig
First of all I would highly recommend to use a JS object for the data variable in ajax requests. This will make your life a lot simpler when you will have a lot of data. For example:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "ajax.php",
data: { "code": code },
datatype: "xml",
success: function() {
$(xml).find('site').each(function(){
//do something
});
});
});
As for getting information from the server, first you will have to make a PHP script to pull out the data from the db. If you are suppose to get a lot of information from the server, then in addition you might want to serialize your data in either XML or JSON (I would recomment JSON).
In your example, I will assume your db table is very small and simple. The available columns are id, code, and description. If you want to pull all the news descriptions for a specific code your PHP might look like this. (I haven't done any PHP in a while so syntax might be wrong)
// create data-structure to handle the db info
// this will also make your code more maintainable
// since OOP is, well just a good practice
class NewsDB {
private $id = null;
var $code = null;
var $description = null;
function setID($id) {
$this->id = $id;
}
function setCode($code) {
$this->code = $code;
}
function setDescription($desc) {
$this->description = $desc;
}
}
// now you want to get all the info from the db
$data_array = array(); // will store the array of the results
$data = null; // temporary var to store info to
// make sure to make this line MUCH more secure since this can allow SQL attacks
$code = htmlspecialchars(trim($_POST['lname']));
// query
$sql = "select * from news where code=$code";
$query = mysql_query(mysql_real_escape_string($sql)) or reportSQLerror($sql);
// get the data
while ($result = mysql_fetch_assoc($query)) {
$data = new NewsDB();
$data.setID($result['id']);
$data.setCode($result['code']);
$data.setDescription($result['description']);
// append data to the array
array_push($data_array, $data);
}
// at this point you got all the data into an array
// so you can return this to the client (in ajax request)
header('Content-type: application/json');
echo json_encode($data_array);
The sample output:
[
{ "code": 5, "description": "desc of 5" },
{ "code": 6, "description": "desc of 6" },
...
]
So at this stage you will have a PHP script which returns data in JSON. Also lets assume the url to this PHP script is foo.php.
Then you can simply get a response from the server by:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "foo.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
// do something with data
for (var i = 0, len = data.length; i < len; i++) {
var code = data[i].code;
var desc = data[i].description;
// do something
}
});
});
That's all.
It's nothing different. Just do your stuff for fetching data in ajax.php as usually we do. and send response in your container on page.
like explained here :
http://openenergymonitor.org/emon/node/107
http://www.electrictoolbox.com/json-data-jquery-php-mysql/
Related
I'd like to create a group chat, and would like all the messages and there matching usernames to be stored in a JSON file.
However, this looks quite hard to do without using node.js or MySQLi.
As you can see below, i can already read the JSON and display it in "chat-wrap". The problem is to add messages to the json file with PHP and/or AJAX, and update the HTML automatically.
The input is where the user types the message, and I assume i'll have to use JS to notice when ENTER is pressed, because i do not want to use a form (unless you can convince me otherwise).
My HTML:
<div class="col chat">
<div class="messages" id="chat-wrap">
<?php include "chat/chat_process.php"; ?>
</div>
<input maxlength='100' type="search" name="type_message" id="type_message" placeholder="Type a message...">
</div>
JSON example:
{
"message_list": [{
"uname": "User 1",
"text": "Hello everyone!"
},
{
"uname": "User 2",
"text": "Hey!"
},
{
"uname": "User 1",
"text": "Hello!"
}
]
}
I've already tried messing with the following code, but i'm new to JS and AJAX so ofcourse the code below didn't really work out...
$("#type_message").keypress(function (event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
var msg = $("#type_message").val();
if (msg.length == 0) {
alert("Enter a message first!");
return;
}
var name = 'Username';
var data = {
uname: name,
text: msg
};
$.ajax({
type: "POST",
url: "chat.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function (response) {
// display chat data stored in text file
}
});
}
});
When a message is typed and entered, it should add to the JSON file and display it live on every users screen.
Please excuse me if i forgot to clarify anything, i'm kinda new to stackoverflow and i'm not sure what y'all pros expect to know...
Thanks!
I added a bit of code to your success function as a result you should be able to add the new text dynamically to your html and also saves the changes to your file messages.json.
$("#type_message").keypress(function(event) {
let keycode = event.keyCode ? event.keyCode : event.which;
if (keycode == "13") {
let msg = $("#type_message").val();
if (msg.length == 0) {
alert("Enter a message first!");
return;
}
let name = "Username";
let data = {
uname: name,
text: msg
};
currentjson.push(data); // Also added one global variable which allows you to push the new data into the old json array.
$.ajax({
type: "POST",
url: "chat/chat.php", // I changed the url slightly since i put the php files in another directory
data: {
data: JSON.stringify(currentjson)
},
dataType: "json",
success: function(response) {
$(".chat").html(""); // Reset the html of the chat
addNodes(response); // Add the new Data to the chat by calling addNodesfunction
},
error: function(err) {
console.log(err);
}
});
}
Here is the php file that saves the json :
<?php
$file = fopen('messages.json','w');
$data = $_POST['data'];
fwrite($file,$data);
fclose($file);
echo $data; // return the new data set
addNodes function :
function addNodes(messages) {
for (let message of messages) {
const chatDiv = $(".chat");
const user = document.createElement("h3");
const content = document.createElement("p");
user.textContent = message.uname;
content.textContent = message.text;
chatDiv.append(user);
chatDiv.append(content);
}
}
I also changed your json to make it a little easier to loop through : (json example)
[
{ "uname": "User 1", "text": "Hello everyone!" },
{ "uname": "User 2", "text": "Hey!" },
{ "uname": "User 1", "text": "Hello!" }
]
Finally the whole client.js code looks like this :
$(document).ready(() => {
let currentjson = undefined;
$.ajax("chat/chat_process.php", { // This gets the file the first time the user opens the page
success: function(data) {
const messages = JSON.parse(data);
currentjson = messages;
addNodes(currentjson);
},
error: function() {
alert("There was some error performing the AJAX call!");
}
});
$("#type_message").keypress(function(event) {
let keycode = event.keyCode ? event.keyCode : event.which;
if (keycode == "13") {
let msg = $("#type_message").val();
if (msg.length == 0) {
alert("Enter a message first!");
return;
}
let name = "Username";
let data = {
uname: name,
text: msg
};
currentjson.push(data); // Also added one global variable which allows you to push the new data into the old json array.
$.ajax({
type: "POST",
url: "chat/chat.php",
data: {
data: JSON.stringify(currentjson)
},
dataType: "json",
success: function(response) {
$(".chat").html(""); // Reset the html of the chat
addNodes(response); // Add the new Data to the chat by calling addNodesfunction
},
error: function(err) {
console.log(err);
}
});
}
});
});
function addNodes(values) {
for (let message of values) {
const chatDiv = $(".chat");
const user = document.createElement("h3");
const content = document.createElement("p");
user.textContent = message.uname;
content.textContent = message.text;
chatDiv.append(user);
chatDiv.append(content);
}
}
But the final tasks that remains is that to display the new data to all the users currently using the website. To be able to do that i think you can use setInterval for like every 5 seconds and call a function which will detect if messages.json was changed by any user and then updates accordingly.
I hope my answers was useful :)
I believe you can, if you register the data into a variable or a text file in the server side.
You can trigger actions using server-sent events
https://www.w3schools.com/html/html5_serversentevents.asp
PS: someone has done it here:
https://www.developphp.com/video/JavaScript/Server-Sent-Events-Simple-Chat-Application-Example
Update sessions for chat directly
Advantages: It's much faster than passing files, storing information in DB. It's far less resource intensive. It avoids a lot of middle-man systems for handling the chat. It doesn't leave you holding onto increasing amounts of data. It avoids a LOT of legal issues with holding onto user data (because you aren't).
Disadvantages: You -have- to make sure it's secure in some way that best fits your use case. Also, troubleshooting session switching if something goes wrong can sometimes be a pain in the arse. Not useful if you're wanting to sell user data.
In php, store the information in session data. Then, fire off a child process (unconnected with the current session) that loads the session of the other user, and updates the other user's session data, having each session holding a variable in their session that stores the session IDs of the other users in the chat.
Mychat.php
$message = "" // Whatever's said
$groupids = implode(",", $other_users_ids); //Whatever your group's ids are.
$_SESSION["group_chat_users"]["my_id"] = session_id();
$_SESSION["my_chat_log"][]= $message;
exec("php my_group_update.php $groupids $_SESSION["group_chat_users"]["my_id"] $message");
my_group_update.php
$groupids = explode(",", $argv[1]);
$calling_user = $argv[2];
$message = $argv[3];
foreach ($groupids as $userid){
session_start($userid);
$_SESSION["my_chat_log"][]= $message");
}
As for outputing the JSON, it's as simple as:
fetch_log.php
header('Content-Type: application/json');
echo json_encode($_SESSION["my_chat_log"]);
Letting the user have their JSON log without it ever having to touch your Harddrive (or, alternatively, you can write it to your harddrive if you prefer.)
Notice: As should go without saying (but apparently needs to be said) As always, validate your inputs. Not doing so will leave you vulnerable to injection.
Ways suggestions on ways to prevent injection:
Have $message be a temporary file name written in Mychat.php and pulled in my_group_update.php
Convert $message to a hex string in Mychat.php and converted back in my_group_update.php
Alter my_group_update to pull the message from the first user's Session before switching to other users where it gets pasted.
Alert mychat to not include any variables other than the group_id in the exec call. Then have my_group_update just take the group ID, and cycle through all the shared chat session arrays, and find all new values, and update all the chats with it <---(probably the best).
Spin up a temporary very tiny VM that only handles the 1 chat, (maybe running with alpine linux or similar for a very small size that then self-destructs when the chat finishes.) This would be much higher overhead, but way more secure than anything else you'll even consider doing.
The list goes on.
I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)
I am using a jquery ajax get method to fetch information from the server however I am having trouble parsing the information so that I may use it. My website has a gallery of products that will filter its items based on category.
Here is the jQuery ajax function:
$('.category').click(function() {
var category;
if ($(this).hasClass('Shirts')) {
category = 'shirts';
}
if ($(this).hasClass('Hats')) {
category = 'hats';
}
if ($(this).hasClass('Acc')) {
category = 'acc';
}
$.ajax({
type: 'GET',
url: 'galleryfetch.php',
data: { 'category' : category },
dataType: 'json',
success: function(data) {
arr = $.parseJSON(data);
alert(arr);
}
});
});
This is the php script that the information is posted to:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$category = $_GET['category'];
$conn = mysqli_connect('localhost', '*****', '*****', 'clothing');
$rows = mysqli_query($conn, "SELECT * FROM products WHERE category = '".$category."'");
while ($row = mysqli_fetch_array($rows)) {
$arr[] = $row;
}
echo json_encode(array('data' => $arr));
}
I using the alert in the success function to see if the information is passed succesfully but at the moment there is no alert and i get an:
Unexpected token o error.
I'm not sure if I'm parsing the information correctly or if Im not correctly using JSON
tl;dr: $.parseJSON(data); should be removed.
Your server is returning JSON (but claiming it is sending HTML, you should have header("Content-Type: application/json")).
You have told jQuery to ignore the claim that it is HTML and parse it as JSON. (This would be redundant if you fixed the above problem)
dataType: 'json',
The parsed data is passed to your success function.
You then pass that data to JSON.parse so it gets converted to a string (which will look something like [ [Object object], ... and is not valid JSON) and then errors.
Remove:
arr = $.parseJSON(data);
And just work with data.
I am continuing a previous question that was asked onclick -> mysql query -> javascript; same page
This is my onchange function for a drop down of names. it is called when each drop down is changed. The idea is to send each runners name into the php page to run a mysql query then return 3 arrays to be entered into javascript.
function sendCharts() {
var awayTeam = document.getElementById('awayRunner').value;
var homeTeam = document.getElementById('homeRunner').value;
if(window.XMLHttpRequest) {
xmlhttp14 = new XMLHttpRequest();
}
else {
xmlhttp14 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp14.onreadystatechange = function() {
if(xmlhttp14.readyState == 4 && xmlhttp14.status == 200) {
var parts = xmlhttp14.responseText.split(','); //THIS IS WHAT IS RETURNED FROM THE MYSQL QUERY. WHEN I ALERT IT, IT OUTPUTS IN THE FORM 14,15,18,16,17,12,13
... code that generates the chart
series: [ {
name: document.getElementById('awayRunner').value,
data: [parts,','], //THIS IS WHERE AN ARRAY MUST BE ENTERED. THIS OUPUTS ONLY ONE NUMBER
type: 'column',
pointStart: 0
//pointInterval
},
{
name: document.getElementById('homeRunner').value,
data: parts, // TRIED THIS
type: 'column',
pointStart: 0
//pointInterval
},
{
name: 'League Avg',
data: [], //THIS IS WHERE 3rd ARRAY MUST BE ENTERED
type:'spline',
pointStart: 0
//pointInterval
},
]
});
}
}
xmlhttp14.open("GET", "getCharts.php?awayRunner="+awayRunner+"&homeRunner="+homeRunner, true);
xmlhttp14.send();
}
my php code looks like this. As you'll see, there are 3 arrays that must be returned to be entered into different spots in the javascript to generate the code.
$away=$_GET['awayRunner'];
$home=$_GET['homeRunner'];
$db=mydb;
$homeRunner=array();
$awayRunner = array();
$totalOverall= array();
$getHome="select column from $db where tmName = '$home'";
$result2 = mysql_query($getHome);
while($row = mysql_fetch_array($result2)){
$homeRunner[]= $row['column'];
}
$getAway="select column from $db where tmName ='$away'";
$result22 = mysql_query($getAway);
while($row2 = mysql_fetch_array($result22)){
$awayRunner[]= $row2['column'];
}
$week = 0;
while($week<20){
$week++;
$teamCount = "select count(column) from $db where week = $week";
$resultTeam = mysql_query($teamCount);
$rowTeam = mysql_fetch_array($resultTeam);
$t = $rowTeam['count(column)'];
$getLeague = "select sum(column) from $db where week = $week";
$resultLeague = mysql_query($getLeague);
while($row3 = mysql_fetch_array($resultLeague)){
$totalOverall[]=$row3['sum(column)']/$t;
}
}
echo join(',',$awayRunner);
currently, by doing it this way, the chart only outputs the second value in the array. for instance, if var parts is equal to 23,25,26,24,23...only 25 is shown.
A previous question resulted with the following answer -
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
I'm lost on #'s 5 - 7. Can someone provide examples of code that gets this done? Normally, I would just ask for direction, but I have been stuck on this problem for days. I'm about ready to scrap the idea of having charts on my site. Thanks in advance
EDIT
this is the first change that I have made to send and receive just one request
<script>
$(function(){
$("#awayRunner").change(function(){
$.ajax({
type: "POST",
data: "data=" + $("#awayRunner").val(),
dataType: "json",
url: "/my.php",
success: function(response){
alert(response);
}
});
});
});
The data displayed in the alertbox is in the form 12,15,16,15. Now, when I enter in
data: response,
only the second number from each is being displayed in the chart. Any ideas?
EDIT
OK, so i figured out that the info in response is a string. It must be converted to an INT using parseInt to be usable in the chart. currently, I have
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayTeam").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var asdf = [];
asdf[0] = parseInt(response[0]);
asdf[1] = parseInt(response[1]);
asdf[2] = parseInt(response[2]);
asdf[3] = parseInt(response[3]);
alert(asdf);
will have to write a function to make this cleaner.
I can't believe it, but I finally got it. here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);
I was trying to implement autocomplete for a textbox which is generated by jQgrid. A Php page would return JSON data. Here's what I was able to do so far: (Please help)
function autocomplete_element(value, options) {
var $ac = $('<input type="text"/>');
$ac.val(value);
$ac.autocomplete({
source: function(request, response) {
$.getJSON("autocomplete.php", { q: request.term }, response);
}
});
return $ac;
}
function autocomplete_value(elem, op, value) {
if (op == "set") {
$(elem).val(value);
}
return $(elem).val();
}
$(function(){
$("#list").jqGrid({
url:'process1.php',
datatype: 'xml',
mtype: 'GET',
colNames:['Column Name'],
colModel :[
{name:'columnid', index:'columnid', width:50, edittype:'custom',
editoptions: {
custom_element : autocomplete_element,
custom_value : autocomplete_value
}
}
]
........
........
////////////////////////////////////////////////
/// THE PHP PAGE ////
////////////////////////////////////////////////
/*
autocomplete.php
*/
<?php
require_once("../dbconfig.php");
$term = trim(strip_tags($_REQUEST['q']));//retrieve the search term that autocomplete sends
$qstring = "SELECT description as value, id FROM test WHERE name LIKE '%".$term."%'";
$result = mysql_query($qstring);//query the database for entries containing the term
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
$row['id']=(int)$row['id'];
$row['value']=htmlentities(stripslashes($row['value']));
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
?>
When I use data such as ["blah","hello","howdy"] in source of $ac.autocomplete, the thing seems to work nicely. But I have around 2000 rows of data to search from. The jQgrid form is working correctly and I am being able to add & edit data. Also, I have tested the php page which displays proper JSON data when I point a browser at it. I am only struck with autocomplete with data returned from the php page since I am not much comfortable with jQuery. Please help.
Try adding exit() after the last echo in php code. I hope this will fix.