Update mysql database with jquery array using ajax - javascript

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.

Related

Change PHP session variable from AJAX call

I am building a website for a school-project. I have been programming in PHP for about a year now, and javascript shouldn't be that much of a problem either.
However, I ran into a problem a couple of days ago. I have a "warning/notification" bar under my navbar. There is two buttons, one where you close the notification and one where you get redirected to read more about it.
If you click the close button, I want to make an AJAX call to the same file, where I have PHP code that will detect the call and then change a SESSION variable, so the notification doesn't show up again regardless of which file you are on.
This however, does not seem to work no matter how many approaches I have tried. I've had enough of this struggle and would greatly appreciate any help from this wonderful community.
This by the way is all in the same file.
Here's the AJAX code:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
type:"POST",
url:"navbar.php",
data: info
});
});
And here's the PHP code (that prints out the HTML):
<?php
require "includes/database.php";
$sql = "SELECT * FROM posts WHERE (post_sort = 'homepage' OR post_sort = 'everywhere') AND post_type = 'warning'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($_SESSION["closed_notification"] == 'no') {
if($resultCheck >= 1) {
while($row = mysqli_fetch_assoc($result)) {
$post_header = $row["header"];
$post_content = $row["post_content"];
$post_index = $row["post_index"];
echo '<div class="nav_bottom_holder_warning">
<div class="navbar_lower_container">
<p>'.$post_header.'</p>
<button class="btn" id="close_warning">Stäng</button>
<button class="btn" id="show_warning">Visa inlägg</button>
</div>
</div>';
}
}
}
?>
Last but not least, the code that is responsible for changing the actual SESSION:
<?php
$_SESSION["closed_notification"] = "no";
if(isset($_POST["info"])) {
$_SESSION["closed_notification"] = "yes";
}
?>
I have tried numerous approaches to this problem, this is just one of them. At this point I am just clueless of how to solve it, thank you.
EDIT: I have already included this file in another file that contains a "session_start()" command. So using that in this file would be no help.
First of all there is no session_start(); on the first line so it will give you an error for the Session Variable.
Secondly update your ajax code to this:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
url: 'navbar.php',
type: 'post',
data: {info:info}
});
});
It basically means that data:{name1:variable2}
Here you are giving the data from js variable(variable2) 'info' to php as info(name ==> that we generally set the input attribute) so in php you can access it as $_POST['info'];.
And lastly you gave the js variable value 'close' and you just checked whether the variable is set while changing the session variable.
Change it to actually checking the value which is better and clear when others read your code.
Summary:
Change data: info to data:{info:info}
Just use Javascript local storage or session storage. I guess it is not important for the server to know if a user has closed the notification yet or not.
$("#close_warning").click(function(){
// close the notification
$("#notification").hide();
// set 'closed' flag in local storage
storage.setItem('closed', 1);
});
Have javascript hide the notification, if the 'closed' flag is set.
if (storage.getItem('closed')) {
$("#notification").hide();
}

how can i prevent to insert data in database when there is duplicate

This is my php code that will put the inserted data to database and will prevent to insert data if there is duplicate.
include('session.php');
$cid="";
$chat_name=$_POST['chatname'];
$chat_password=$_POST['chatpass'];
$sql3="SELECT * FROM chatroom where chat_name='$chat_name'";
$query=mysqli_query($conn,$sql3);
if(mysqli_affected_rows($query) == 1){
echo("<script>alert('ee');</script>");
}
else{
mysqli_query($conn,"insert into chatroom (chat_name, chat_password, date_created, userid) values ('$chat_name', '$chat_password', NOW(), '".$_SESSION['id']."')");
$cid=mysqli_insert_id($conn);
mysqli_query($conn,"insert into chat_member (chatroomid, userid) values ('$cid', '".$_SESSION['id']."')");
echo $cid;
}
this is jquery code
$(document).on('click', '#addchatroom', function(){
chatname=$('#chat_name').val();
chatpass=$('#chat_password').val();
$.ajax({
url:"add_chatroom.php",
method:"POST",
data:{
chatname: chatname,
chatpass: chatpass,
},
success:function(data){
window.location.href='chat.php';
}
});
});
When I enter a duplicate data the alert in echo don't execute but it continue to put in database although it is duplicate. THANKS FOR THE HELP !
First thing, I would change
if(mysqli_affected_rows($query) == 1){
to
if(mysqli_affected_rows($query) >= 1){
this will make sure that even if there are already duplicates, no more duplicates can be added
There are however some bigger issues with the code that you should address
You should add a uniqueness constraint on your chatname (in the database). This will make it that even if your code is wrong, you will not be able to add duplicate entries to your table.
You are receiving user input and just adding it into your sql querys. This leaves your database open to SQL injection which basically means, anyone can do anything to your database (delete things, add things, etc.). You should look into prepared statements to solve this issue

Posting a variable to a PHP File with Ajax to delete a row from Mysql - doesn't work

here's my Ajax function.:
$( document ).ready(function(){
$("#deletebutton").click(function(){
var del_id = $(this).attr('name');
var answer = confirm ("Are you sure?");
if (answer)
$.ajax({
type: "POST",
url: "deletescript.php",
data:'delete_id='+del_id,
success: function(data)
{
alert("Done!");
}
});
});
});
And here's the affected button:
echo'<input type="button" name="'.$id.'" id="deletebutton" value="delete">'
Here's my PHP Script called deletescript.php:
$id = $_POST['delete_id'];
$query = "DELETE from items where id = '$id'";
$result = $mysqli->query($query);
Even when I get "Done!" as an alert - my Item still exists. I also checked with Firebug that the correct ID is succesfully sent to the deletescript.php file. What do I have to do? I also tested the SQL-Query manually on my Databse and it worked. Searched for similar questions and found some, sadly even their solutions didn't help. I don't know what to do...
Thank you!
Let print your full query and execute this in your database management tool. So you can see exactly which query it is.
Generally, I will say a couple of things to you:
For deletion, send a DELETE request instead of POST
Don't put variables between quotes
Sanatize query parameters to prevent sql injection
Better alternative and solution for you:
Soft deleting
Add state field to your table
You can have active state and non active state (deleted)
Do you want to delete record? Set state to non active
Default read out the active items
try jquery $.post:
$( document ).ready(function(){
$("#deletebutton").click(function(){
var del_id = parseInt($(this).attr('name'));
var answer = confirm ("Are you sure?");
if (answer){
$.post('deletescript.php',{id:del_id}, function(callback){
if(callback){
alert("Done!");
}
});
}
});
});
The PHP file will get access to the id with $_POST['id']
The callback will contain whatever ur PHP file will echo/show

AJAX Request from Table Rows to Details

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
}

Live Dynamic search of MySQL table using jquery and php

I am sure there are a number of articles covering this topic, but every piece of code I try just doesn't seem to work. If this has been answered somewhere else already, I am sorry that I could not find it.
I am trying to create a live search that displays all data in my table until someone starts typing in an input field. As soon as they start typing a key, I want to run a select query on my table to narrow the results if any of the columns contain the string that is currently being typed (kind of like how google starts showing you results as you type in the search bar).
My code seems to work up until I try to use either $.get or $.post to interact with my php file that runs the MySQL search. I am kind of new to web development and have been teaching myself as I go along, but this one has stumped me for 2 days now. Here is the code I currently have (although I have tried about 20 different versions):
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
document.getElementById("search").onkeyup(searchScript());
function searchScript(){
var search = $("#search").val();
if(search==""){
return;
}
else{
$.get("resultspage.php",{search : search},function(result){
$("#results").html(result);
}});
}
</script>
<table id="results">
<?php
<...var assignments storing my db login data...>
$con=mysqli_connect($host,$username,$password,$database);
$sql="SELECT * FROM Registration";
if(mysqli_query($con,$sql)){
$result=mysqli_query($con,$sql);
}
else{
echo "error: " . mysqli_error($con);
}
while($row=mysqli_fetch_array($result))
{
<...code that displays the results...>
?>
</table>
My PHP file
$search=$_GET['search'];
<...variables storing log in data...>
$con=mysqli_connect($host,$username,$password,$database);
$sql="SELECT * FROM Registration WHERE CONCAT(fName,lName,storeName,numLocations,primaryPhone,secondPhone,email,products) LIKE %$search%";
if(mysqli_query($con,$sql)){
$result=mysqli_query($con,$sql);
}
else{
echo "error: " . mysqli_error($con);
}
while($row=mysqli_fetch_array($result))
{
<...code that displays results....>
}
Any help would be much appreciated! Thank you.
Recognizing that jquery is another mountain to climb, I would still learn & use it for it's simplicity. Once the data has been retrieved from the server, use jquery to hide the values not starting with or containing the entered value (.match() below), instead of repeated calls to the server.
Not knowing the structure of your table, a framework you might try:
$( "#search" ).keyup(function() {
// Test search letter entry is working
alert( "Handler for .keyup() called." );
var s = $("#search").attr("value"); // Typed in letter
// Pass an array of table contents
// there are a couple ways you could approach the 'gathering' of table items...
$(".individual-item-class").each(function(index, element) {
if (!element.match(/s/))
$(element:parent).css("display","none");
else
$(element:parent).css("display","table-row")
}):
});
This code will not get you off the ground, but pointed in a direction.
You can learn about selectors and a few jquery functions. Used here are each(), attr() and css().

Categories