This is my first time on here so I'm sorry if I'm not quite up to snuff with all of you.
In the process of learning AJAX so I'm brand new, but need to get a page done for our staff website.
I have a page (php) which builds a list through a mysql query of all patients. I have absolutely no problem with this. However, I'm stuck on this part.
When a user clicks a specific row (aka Patient Name), I want it to pull up the details of that patient associated with it in our mysql database on the right-hand side so the page doesn't have to refresh and they aren't directed to any other pages.
I have seen examples like this when it came to customers, like you click the name and a div appears to the right containing email, phone, etc. etc.
Does anyone have any good starting points? I have searched as far as I can, and I'm beginning to think I'm not using the right language when searching for my answer.
Thanks ahead of time... Matt
Use jQuery.
First you need to make a web service on your server. The web service will accept a, let's say, POST parameter which will be either patient name or the patient ID. Based on this id/name you will query your MySQL database, fetch all the details and return as json.
On the front end, you can use jQuery.post(). You will need to pass the appropriate URL and the data. In return, you will get JSON data. In the success callback method of jQuery.post/$.post you can create a div on the right and display those data.
If you are going to return the data in json format, you can also just use $.postJSON()
Please make sure to set the appropriate headers in your PHP webservice. These two are probably the most important
Content-Type: application/json // if you are gonna return the data in JSON format
Access-Control-Allow-Origin: * // to let the browser pass the data to the DOM model. This is to allow CORS (Cross Origin Resouce Sharing)
SAMPLE:
example.php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
if (isset($_POST['patientID'])) {
$patientID = $_POST['patientID'];
$data = array();
// Enter the appropriate details below
$mysqli = new mysqli("host", "username", "password", "db_name");
/* check connection */
if ($mysqli->connect_errno > 0) {
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
$statement = $mysqli->prepare("SELECT * FROM `patients` WHERE `patientID` = ? LIMIT 1");
$statement->bind_param('i', $patientID);
$statement->execute();
// You need to write a variable for each field that you are fetching from the select statement in the correct order
// For eg., if your select statement was like this:
// SELECT name, COUNT(*) as count, id, email FROM patients
// Your bind_result would look like this:
// $statement->bind_result($name, $count, $id, $email);
// PS: The variable name doesn't have to be the same as the column name
$statement->bind_result($id, $name, $email, $phone);
while ($statement->fetch()) {
$data["id"] = $id;
$data["name"] = $name;
$data["email"] = $email;
$data["phone"] = $phone;
}
$statement->free_result();
echo json_encode($data);
}
example.html
Patient #123
example.js
function getPatientData(element) {
var patientID = $(element).attr("id");
$.post("example.php", {"patientID": patientID}, function (data) {
// display the data in appropriate div
}, 'json');
return false;
}
You should do an jquery ajax call on element click
$('.patientClass').on('click', function() {
var patientid = $(this).attr('id');
// attr('id') should be the patients id
$.ajax({
url: "getPatientDetailsURL.php",
type: "post",
data: {
id: patientid
},
success: function(response) {
// create div with response details or append parsed json to existing div
}
});
)}
And on the backend get the patiend id with (int)$_POST['id']
Also you on the backend you can set the page to respond only to ajax calls like this:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//code here
} else {
// not ajax call
}
Related
I'm working on a project that allows users to invite other users. When a user gets an invite, a pop-up should, well...pop up...asking them to accept or decline. For this, I'm using an AJAX call to check if they have any invites. This will eventually be an automatically called function, but for now I'm just testing it with a simple button and onclick function.
What happens is, the AJAX request goes to checkInvitations.php, which checks a database table full of users. In plain English, checkInvitations.php checks whether the "user" AJAX sent over has an invitation. If they do, checkInvitations passes information back to the AJAX request with (name of person who invited the user) and (confirmation of an invite).
For whatever reason, though, my function keeps coming up as undefined, even though I've imported the JQuery library. I've no idea why this is the case.
Here's the function with the AJAX request.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript">
function checkForInvitations()
{
var invitedPlayer = '<?php echo $_SESSION["goodUser"]; ?>' //invitedPlayer = the logged-in user
console.log("invitedPlayer is: "+invitedPlayer); //variable debug check
$.ajax({
type: "post",
url: "checkInvitations.php",
data: {invitedPlayer: invitedPlayer},
success: function(data)
{
// parse json string to javascript object
var invitations = JSON.parse(data);
console.log(invitations); //variable debug check
// check the invitations to/from
var invitingPlayer = invitations.invitationFrom;
var invitationStatus = invitations.invitationStatus;
//if player has received an invite, pop up a screen asking them to confirm/accept the invite
if(invitationStatus != 'false')
{
clearInterval(checkInvitationIntervalId);
confirm_yes = confirm(invitingPlayer+" invited you to a game. Accept ?");
}
}
})
}
And here's the PHP page it requests to
<?php
session_start();
// Create connection
$conn = new mysqli('localhost', 'root', '', 'warzone');
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$invitations = array();
//look for rows in database where user=the invited user and the invitestatus has been set to true (after invite was sent)
$request = "SELECT * FROM warzone.logged_in_users WHERE USER='".$_POST["invitedPlayer"]."' AND INVITESTATUS='TRUE'";
$res = $conn->query($request);
if($row = $res->fetch_assoc())
{
$invitations["invitationFrom"]=$row["INVITING_PLAYER"];
$invitations["invitationStatus"]='true';
}
else
{
$invitations["invitationFrom"]='none';
$invitations["invitationStatus"]='false';
}
echo json_encode($invitations);
?>
Keep in mind when I use the $_SESSION["goodUser"] in place of $_POST["invitedPlayer"] in the above PHP file, I get the exact output I'm looking for. I know that works. I just can't get it to work with $_POST, obviously, because the AJAX request isn't being made/is broken/is undefined.
Any help is appreciated!
From the Mozzila Developer API on script tags.
If a script element has a src attribute specified, it should
not have a script embedded inside its tags.
Therefor you want to seperate your inclusion of jquery into a seperate tag.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js" type="text/javascript">
</script>
<!-- end script before you start the one with your code in it -->
<script type="text/javascrpt">
// Your code that involves $ here...
</script>
I do not know what is happening with my code, when I run it, sometimes SESSION says there is an array is stored and sometimes it doesn't. I am using a debugger to check the session. When I use isset($_POST), the return value is always false. I am using ajax to pass an array to php.
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
Javascript:
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
window.location.href = 'example.php';
var jExample = JSON.stringify(array);
$.ajax({
data:{'jExam':jExample},
type: 'POST',
dataType: 'json',
url: 'example.php'
});
});
EDIT:
Figured out why the arrays are stored into SESSION, once I click on the button that opens the other page, and then type in the page before in the url, the array is stored into the SESSION. Don't know why. Still can't figure out why ajax is not sending to post.
EDIT 2:
I created a file that handles the request called handle.php. So the php script on top is added into handle.php instead of the webpage. But I am getting a "Parse error: syntax error, unexpected 'if' (T_IF)". The code is still the same on top.
handle.php:
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
EDIT 3:
I am using the ajax to pass an array to php in order to store it into session, in order to use the array in another page. The problem is that the array is not passing into $_POST. What I am hoping is that the array can actually pass so I can use it on another page.
SOLVED:
All i did was add a form that has a hidden value. And the value actually post
<form id = "postform" action = "cart.php" method = "post">
<input type = "hidden" id="obj" name="obj" val="">
<input type = "submit" value = "Show Cart" id = "showcart">
</form>
In the Javascript:
$(document).ready(function(){
$("#showcart").click(function(){
var json = JSON.stringify(object)
$('#obj').val(json);
$('#obj').submit();
});
});
Thank you for everyone at has answered but hope this helps others.
If example.php is the php file which handles the request, you need to change your js code to
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
var jExample = JSON.stringify(array);
$.ajax("example.php", {
data:{'jExam':jExample},
type: 'POST',
dataType: 'json'
});
});
And you should add the complete-Parameter if you want to handle the response.
Your mistake is, you are redirecting the page using window.location.href before you even send your request. Therefore, your request never gets sent and the PHP-File is called directly instead, not via AJAX, not with the nessecary data. Therefore, you are missing the data in the PHP-File.
You will want to try and make this setup a bit easier on yourself so here are a few things that can help you simplify this. You may or may not have some of these already done, so disregard anything you already do:
Use a config file with concrete defines that you include on 1st-level php files
Just pass one data field with json_encode()
Don't send json as a data type, it's not required, troubleshoot first, then if you need to, make it default as the send type
Use a success function so you can see the return easily
Make functions to separate tasks
/config.php
Add all important preferences and add this to each top-level page.
session_start();
define('URL_BASE','http://www.example.com');
define('URL_AJAX',URL_BASE.'/ajax/dispatch.php');
define('FUNCTIONS',__DIR__.'/functions');
Form:
Just make one data that will send a group of data keys/values.
<button class="cart" data-instructions='<?php echo json_encode(array('name'=>'Whatever','price'=>'17.00','action'=>'add_to_cart')); ?>'>Add to Cart</button>
Gives you:
<button class="cart" data-instructions='{"name":"Whatever","price":"17.00","action":"add_to_cart"}'>Add to Cart</button>
Ajax:
Just send a normal object
$(document).ready(function(){
// Doing it this way allows for easier access to dynamic
// clickable content
$(this).on('click','.cart',function(e)){
e.preventDefault();
// Get just the one data field with all the data
var data = $(this).data('instructions');
$.ajax({
data: data,
type: 'POST',
// Use our defined constant for consistency
// Writes: http://www.example.com/ajax/dispatch.php
url: '<?php echo URL_AJAX; ?>',
success: function(response) {
// Check the console to make sure it's what we expected
console.log(response);
// Parse the return
var dataResp = JSON.parse(response);
// If there is a fail, show error
if(!dataResp.success)
alert('Error:'+dataResp.message);
}
});
});
});
/functions/addProduct.php
Ideally you would want to use some sort of ID or sku for the key, not name
// You will want to pass a sku or id here as well
function addProduct($name,$price)
{
$_SESSION['cart'][$name]['name'] = $name;
$_SESSION['cart'][$name]['price'] = $price;
if(isset($_SESSION['cart'][$name]['qty']))
$_SESSION['cart'][$name]['qty'] += 1;
else
$_SESSION['cart'][$name]['qty'] = 1;
return $_SESSION['cart'][$name];
}
/ajax/dispatcher.php
The dispatcher is meant to call actions back only as an AJAX request. Because of the nature of the return mechanism, you can expand it out to return html, or run several commands in a row, or just one, or whatever.
# Add our config file so we have access to consistent prefs
# Remember that the config has session_start() in it, so no need to add that
require_once(realpath(__DIR__.'/../..').'/config.php');
# Set fail as default
$errors['message'] = 'Unknown error';
$errors['success'] = false;
# Since all this page does is receive ajax dispatches, action
# should always be required
if(!isset($_POST['action'])) {
$errors['message'] = 'Action is require. Invalid request.';
# Just stop
die(json_encode($errors));
}
# You can have a series of actions to dispatch here.
switch($_POST['action']) {
case('add_to_cart'):
# Include function and execute it
require_once(FUNCTIONS.'/addProduct.php');
# You can send back the data for confirmation or whatever...
$errors['data'] = addProduct($_POST['name'],$_POST['price']);
$errors['success'] = true;
$errors['message'] = 'Item added';
# Stop here unless you want more actions to run
die(json_encode($errors));
//You can add more instructions here as cases if you wanted to...
default:
die(json_encode($errors));
}
I am needing a little help with updating a mysql table from data in an jquery array using ajax. I have tried searching for similar issues but could not find anything, or maybe I do not know the correct terms to search... I'm still fairly new to web dev/coding.
I'll try explain what I am trying to do as clearly as I can. I have a page with seats which users select by clicking on them, upon clicking the seat ID is added in its own span tag in a kind of shopping cart area on the left of the page. This works fine.
Upon checkout my js file is able to pick up these seat ID's in an array, but from here I am unsure of how to properly send this array to the php file, and then for the php file to read the seat ID's from the array and update the relevant seat rows to change the availability from 1 to 0 (this is using ajax).
Here is my code:
checkout.js
$(document).ready(function(){
$('#checkout').click(function(){
var status = sessionStorage.getItem("username");
if(sessionStorage.getItem("username")){
var tickets = [];
$("#myTickets").find("span").each(function(){ tickets.push(this.id); });
var type = "POST",
url = "scripts/sendSeatDetails.php";
console.log(tickets);
$.ajax ({
url:url,
type:type,
data:tickets,
success: function(response){
if(response == 5){
alert("Seat update query failed");
} else {
alert("success");
}
}
});
} else {
alert("Before purchasing please log in. If you do not have an account please register.");
}
});
});
In the console log this shows: ["A2", "A3", "A4"] (if I have selected seats with ID A2, A3, A4 etc).
sendSeatDetails.php
<?php
include("dbconnect.php");
$myseats=$_POST['tickets'];
$query="update seats set status='0' where seatnum=";
for($i=0;$i<count($myseats);$i++){
$query.="'$myseats[$i]'";
if($i<count($myseats)-1){
$query.=" || seatnum=";
}
}
$link = mysql_query($query);
if (!$link) {
echo 5;
}
?>
This returns the alert showing success, but this is not true as the tables are not being updated. Can anyone help me with this or point me in the right direction?
I appreciate your help, and hopefully will be able to contribute to this site when I am at a better skill level in the future.
Many Thanks.
To send an array in jQuery you have to serialize it then parse it in the PHP file:
data: tickets.serialize(),
...
parse_str($_POST['data'], $data);
And then you treat it as an ordinary array.
Run update query one by one.
$myseats=$_POST['tickets'];
$flag=0;// Total successful updates
$myseats=explode(',',$myseats);
for($i=0;$i<count($myseats);$i++){
$query="update seats set status=0 where seatnum='".$myseats[$i]."'";
$link = mysql_query($query);
if (!$link) {
$flag=$flag+1;
}
}
echo $flag;die;
Check response. it will be number of updated rows.
I'm in a team developing an Android application that will rely greatly on the use of a remote database. We are using PhoneGap and Jquery Mobile and have been attempting to connect to our MySQL database using AJAX and JSON calls. Currently, we are having trouble in our testing phase, which is to verify we even have a connection at all by pulling a hard-coded user of "Ted" from mySQL / input via MySQL Workbench.
From what we have gathered, the process of data transmission works as this:
On our html file, we have a
<script type="text/javascript" src="Connect.js"></script>
^ Which should run the Connect.js script, correct? So from there, Connect.js is ran?
Connect.js runs, connecting it to our ServerFile.php that is hosted on an external web service, allowing it to run PHP to connect to the MySQL database and pull information.
//run the following code whenever a new pseudo-page is created
$('#PAGENAME').live('pageshow', function(event)) {
// cache this page for later use (inside the AJAX function)
var $this = $(this);
// make an AJAX call to your PHP script
$.getJSON('http://www.WEBSITENAME.com/ServerFile.php', function (response) {
// create a variable to hold the parsed output from the server
var output = [];
// if the PHP script returned a success
if (response.status == 'success') {
// iterate through the response rows
for (var key in response.items) {
// add each response row to the output variable
output.push('<li>' + response.items[key] + '</li>');
}
// if the PHP script returned an error
} else {
// output an error message
output.push('<li>No Data Found</li>');
}
// append the output to the `data-role="content"` div on this page as a
// listview and trigger the `create` event on its parent to style the
// listview
$this.children('[data-role="content"]').append('<ul data-role="listview">' + output.join('') + '</ul>').trigger('create');
});
});
Here is ServerFile.php. This should connect to the MySQL Database, make the Select statement, and then send the output to the browser encoded in the JSON format.
<?php
//session_start();
$connection = mysql_connect("csmadison.dhcp.bsu.edu", "clbavender", "changeme");
$db = mysql_select_db("cs397_clbavender", $connection);
//include your database connection code
// include_once('database-connection.php');
//query your MySQL server for whatever information you want
$query = mysql_query("SELECT * FROM Users WHERE Username ='Ted'", $db) or trigger_error(mysql_error());
//create an output array
$output = array();
//if the MySQL query returned any results
if (mysql_affected_rows() > 0) {
//iterate through the results of your query
while ($row = mysql_fetch_assoc($query)) {
//add the results of your query to the output variable
$output[] = $row;
}
//send your output to the browser encoded in the JSON format
echo json_encode(array('status' => 'success', 'items' => $output));
} else {
//if no records were found in the database then output an error message encoded in the JSON format
echo json_encode(array('status' => 'error', 'items' => $output));
}
?>
Yet nothing is showing here. What do we do from here?
First thing first. Try to determine where is the problem come from, server side or client side.
Print out your database query and encoded json can be useful. If you are creating a simple API service, you should be able to enter http://www.WEBSITENAME.com/ServerFile.php using your browser and look how the output is.
Use echo to print things with php.
If all looks ok, time to print out the response you receive from the server in the javascript and see what is off.
Use console.log to print thing with javascript. The logs should appear in the logcat section of eclipse (since you are developing android app)
I have a table with the following fields: wall_posts, group_id, id, and user_id.
Wall_posts is user entries, group_id is imported from another table and is just a unique group id, id is just a simple counter, and user_id gets the user id from the session.
My code gets rid of all the wall_posts if you press the delete button by comparing the user id to the user in session. I'm trying to find a way to delete individual posts and not all the posts by the user.
Here is the code:
if (isset($_POST['delete'])) {
$current_user = $_SESSION['user_id'];
$result = mysql_query("SELECT * FROM group_posts");
while ($user_id = mysql_fetch_array($result)) {
$id = $user_id['user_id'];
}
if ($current_user == $id) {
mysql_query("DELETE FROM group_posts WHERE $current_user = $id") or die(mysql_error());
}
}
How can I bound the delete button to individual posts instead of deleting all the posts made by the user currently in session?
Your SQL query above doesn't make sense - the WHERE statement should be in the form WHERE column_name = value.
Assuming id is the primary key for group_posts, as you're displaying posts, create a link for each post created by the author, e.g. Delete This Post for post with id 3. Then you'd do a query like this:
DELETE FROM group_posts WHERE id = postIdValueHere
Using the code pattern you have above:
if (isset($_POST['delete']) && $_POST['delete'] > 0) {
$current_user = $_SESSION['user_id'];
$post_id = (int) $_POST['delete'];
if ($current_user == $id) {
mysql_query("DELETE FROM group_posts WHERE id = $post_id AND user_id = $id") or die(mysql_error());
}
That query ensures that only posts with a given ID, created by the current author, can be deleted.
Does that answer your question?
Once you get more comfortable with SQL, you might also want to look into using prepared statements with mysqli or PDO. That will help your code clean and secure.
I'm assuming your delete buttons are simple links. Your links must contain all the information to delete a post. One way would be to pass a post id as a GET variable (e.g. link="myurl.com/posts/delete?id=#").
Your script would then at first make sure the current user is allowed to delete the post. For example:
$user_id = $_SESSION['user_id'];
$post_id = (int) $_GET['id'];
if(canDelete($user_id, $post_id))
{
// assuming post_id is unique for every post
$sql = sprintf("DELETE FROM group_posts WHERE id = %d", $post_id);
mysql_query($sql);
}
Of course, you'd have to implement canDelete($user_id) yourself.
By the way, "DELETE FROM group_posts WHERE $current_user = $id" always deletes every record in your table. At first you're comparing if $current_user equals $id and if they do happen to be equal, your query would look something like WHERE 1 = 1. I think you mean "DELETE FROM group_posts WHERE user_id = '$id'"
EDIT: It seems you want to use ajax for deleting your posts. I recommend using jQuery or any other proper javascript framework as it saves you time. Here is a link from the jQuery documentation describing how to make an ajax call to the server and a similar question to help you understand better.