For some reason I can't get data to send to my database using ajax and php.
I click the add to cart button, the success message doesn't show up at all, and no data is sent to the database. No errors show up at all. What is going on here?
<form action="includes/addcart.inc.php?id=<?= $row['id'] ?>" class="cart-form">
<input type="hidden" class="pid" value="<?= $row['id'] ?>">
<input type="hidden" class="pname" value="<?= $row['product_name'] ?>">
<input type="hidden" class="pprice" value="<?= $row['product_price'] ?>">
<input type="hidden" class="pimage" value="<?= $row['product_image'] ?>">
<input type="hidden" class="pcode" value="<?= $row['product_code'] ?>">
<input type="submit" class="atcbutton btn btn-info btn-block" name="Add To Cart" value="Add To Cart">
</form>
Here is the form I'm using.
$(document).ready(function() {
// Send product details in the server
$('.cart-form').submit(function(e) {
e.preventDefault();
var $form = $(this).closest(".cart-form");
var pid = $form.find(".pid").val();
var pname = $form.find(".pname").val();
var pprice = $form.find(".pprice").val();
var pimage = $form.find(".pimage").val();
var pcode = $form.find(".pcode").val();
var pqty = $form.find(".pqty").val();
$.ajax({
url: 'includes/addcart.inc.php',
method: 'POST',
data: {
pid: pid,
pname: pname,
pprice: pprice,
pqty: pqty,
pimage: pimage,
pcode: pcode
},
success: function(response) {
$("#message").html(response);
}
});
});
});
Here's the js and ajax.
<?php
require 'dbh.inc.php';
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
$pname = $_POST['pname'];
$pprice = $_POST['pprice'];
$pimage = $_POST['pimage'];
$pcode = $_POST['pcode'];
$pqty = $_POST['pqty'];
$total_price = $pprice * $pqty;
$sql = ('SELECT product_code FROM cart WHERE product_code=?');
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, 's', $pcode);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);
$r = mysqli_fetch_assoc($res);
$code = $r['product_code'] ?? '';
if (!$code) {
$query = ('INSERT INTO cart (product_name, product_price, product_image, qty, total_price, product_code) VALUES (?,?,?,?,?,?)');
mysqli_stmt_init($conn);
mysqli_stmt_bind_param($query, 'ssssss', $pname, $pprice, $pimage, $pqty, $total_price, $pcode);
mysqli_stmt_execute($query);
echo '<div class="alert alert-success alert-dismissible mt-2">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Item added to your cart!</strong>
</div>';
} else {
echo '<div class="alert alert-danger alert-dismissible mt-2">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Item already added to your cart!</strong>
</div>';
}
}
header("location: ../shop");
exit();
and that's the php. (dbh.inc.php is just a simple database connection)
I have tried double checking for typos/errors and I can't seem to find anything wrong.
Related
i want to make a post form and display the post i made on the list bellow the form. Here is my code. The problem is that when i click the post button the post is stored in the database BUT i have to refresh the page to show the post i did underneath.
<form method="post" id="form_wall">
<textarea name="content" id="content" class="form-control" placeholder="Share any thing what's in your mind"></textarea>
<br>
<div align="right">
<input type="submit" name="submit" id="submit" class="btn btn-primary btn-sm" value="Post" />
</div>
</form>
<h4>Latest POst </h4>
<br>
<div id="website_stuff"> </div>
</div>
</div>
</html>
<script>
$(document).ready(function(){
load_stuff();
function load_stuff()
{
$.ajax({
url:"load_stuff.php",
method:"POST",
success:function(data)
{
$('#website_stuff').html(data);
}
})
}
$('#form_wall').on('submit', function(event){
event.preventDefault();
if ($.trim($('#content').val()).length == 0)
{
alert("Please write something");
return false;
}
else
{
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data: form_data,
success:function(data)
{
if(data == 'done')
{
$('#form_wall')[0].reset();
load_stuff();
}
}
})
}
});
});
</script>
here is my insert.php code that I call when I hit the post button
<?php
include('database_connection.php');
if(isset($_POST["content"]))
{
$query = "INSERT INTO content (user_id, description) VALUES (:user_id, :description)";
var_dump($query);
$statement = $connect->prepare($query);
$statement->execute(
array(
'user_id' => $_SESSION['user_id'],
'description' => $_POST["content"]
)
);
$result = $statement->fetchAll();
if(isset($result))
{
echo 'done';
}
}
?>
Here is the load_stuff.php
<?php
include('database_connection.php');
include('function.php');
if(isset($_SESSION["user_id"]))
{
$output = '';
$query = "SELECT content.content_id, content.user_id, content.description, user_details.user_name FROM content
INNER JOIN user_details
ON user_details.user_id = content.user_id
ORDER BY content_id DESC;
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_rows = $statement->rowCount();
if($total_rows > 0)
{
foreach($result as $row)
{
$like_button ='';
if(!is_user_has_already_like_content($connect, $_SESSION["user_id"], $row["content_id"]))
{
$like_button = '<button type="button" name="like_button" class="btn btn-info btn-xs like_button" data-content_id="'.$row["content_id"].'">Like</button>';
}
$count_like = count_content_like($connect, $row["content_id"]);
$output .='
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> By '.$row["user_name"].'</h3>
<button type="button" name="total_like" id="total_like" class="btn btn-warning btn-xs">'.$count_like.' Like</button>
</div>
<div class="panel-body">
'.$row["description"].'
</div>
<div class="panel-footer" align="right">
'.$like_button.'
</div>
</div>';
}
}
else
{
$output = 'Nobody has share nothing';
}
echo $output;
}
?>
INDEX.PHP
<body>
<br />
<h2 align="center">Comment System using PHP and Ajax</h2>
<br />
<div class="container">
<form method="POST" id="comment_form" >
<div class="form-group w-50">
<input type="text" name="comment_name" id="comment_name" class="form-control" value="<?php echo $_SESSION['username'];?>" readonly/>
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-inline ">
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Comment" />
</div>
<input type="reset" value="Cancel" class="btn btn-primary" style="margin-left: 5px;">
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();//CONVERTS/STORES THE FORM INTO URL IN CODE
$.ajax({
url:"add_comment.php",//WHERE WILL THE INFO GO ---- OR ---- SENDS REQUEST/GOES TO ADD_COMMENT.PHP and records the info
method:"POST",//FOUND IN THE FORM METHOD, telss what kind of method to use to send the data to server so we use ---POST---
data:form_data,//data: it is the variable/code we used to convert/store the form into url in code
dataType:"JSON",
success:function(data)//Will be called if the sending of data to the comment.php is successful
{ //and success will receive the same data/the form_data from server OR DATA WAS RECEIVED BY SUCCESS
if(data.error != '')//check if there is no error in the process and DISPLAYS THE DATA BELOW
{
$('#comment_form')[0].reset();//as Array, it starts with 0 and the .reset() JUST RESETS THE FORM FIELD/OFF THE AUTO COMPLETE
$('#comment_message').html(data.error);//outputs if there is an error or not
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()//loads all the comment
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)//DISPLAYS DATA BELOW if success
{
$('#display_comment').html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();// if click it will focus on the comment name
});
});
</script>
ADD_COMMENT.php
<?php
session_start();
//add_comment.php
$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
$error = '';
$comment_name = $_SESSION['username'];
$comment_content = '';
if(empty($_POST["comment_name"]))
{
$error .= '<p class="text-danger">Name is required</p>';
}
else
{
$comment_name = $_POST["comment_name"];
}
if(empty($_POST["comment_content"]))
{
$error .= '<p class="text-danger">Comment is required</p>';
}
else
{
$comment_content = $_POST["comment_content"];
}
if($error == '')//if this condition runs then there is no validation error or whatsoever
{
$query = "
INSERT INTO tbl_comment
(parent_comment_id, comment, comment_sender_name)
VALUES (:parent_comment_id, :comment, :comment_sender_name)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':parent_comment_id' => $_POST["comment_id"],
':comment' => $comment_content,
':comment_sender_name' => $comment_name
)
);
$error = '<label class="text-success">Comment Added</label>';
}
$data = array(
'error' => $error
);
echo json_encode($data);
?>
FETCH_COMMENT.php
where the reply part is
<?php
session_start();
//fetch_comment.php
$connect = new PDO('mysql:host=localhost;dbname=testing', 'root', '');
$query = "
SELECT * FROM tbl_comment
WHERE parent_comment_id = '0'
ORDER BY comment_id DESC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
$delete = '';
foreach($result as $row)
{
$output .= '
<div class="panel panel-default">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>';
$output .= get_reply_comment($connect, $row["comment_id"]);
}
echo $output;
function get_reply_comment($connect, $parent_id = 0, $marginleft = 0)
{
$query = "
SELECT * FROM tbl_comment WHERE parent_comment_id = '".$parent_id."'
";
$output = '';
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$count = $statement->rowCount();
if($parent_id == 0)
{
$marginleft = 0;
}
else
{
$marginleft = $marginleft + 48;
}
if($count > 0)
{
foreach($result as $row)
{
$output .= '
<div class="panel panel-default" style="margin-left:'.$marginleft.'px">
<div class="panel-heading">By <b>'.$row["comment_sender_name"].'</b> on <i>'.$row["date"].'</i></div>
<div class="panel-body">'.$row["comment"].'</div>
<div class="panel-footer" align="right"><button type="button" class="btn btn-default reply" id="'.$row["comment_id"].'">Reply</button></div>
</div>
';
$output .= get_reply_comment($connect, $row["comment_id"], $marginleft);
}
}
return $output;
}
?>
First of all before i show you the code i will explain how my webpage works.
User selects date -> AJAX Calls On Date Change
Resulting PHP data displays in two sections on page.
First Section is Orders Table Contents
Second Section is Items Table Contents (not including the items inside Orders)
What i am trying to add is functionality to 3 buttons that will change the tables dynamically using AJAX.
I currently have working non ajax requests.
Here is the Code:
$(document).ready(function(){
$('.date-picker').change(function(){
$.ajax({
type: 'POST',
url: 'php/getproduct.php',
data: {dateorderpicker: $('.date-picker').val()},
dataType: 'JSON',
success: function(data)
{
$("#cartrow").html(data.result_1);
$("#otheritems").html(data.result_2);
}
});
});
});
PHP file for Current AJAX:
session_start();
include('db_config.php');
$datepicker = $_POST['dateorderpicker'];
$sql = "SELECT * FROM orders WHERE deliveryDate = ? AND customerId = ? ";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $datepicker, PDO::PARAM_STR);
$stmt->bindParam(2, $_SESSION['customer_id'], PDO::PARAM_INT);
$stmt->execute();
$container = array();
$data['result_1'] = $data['result_2'] = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$container[] = "'{$row['itemName']}'"; // put them inside a temporary container
$data['result_1'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/edit.php" method="post" class="form-inline pull-right">
<h3>' . $row['itemName'] . '</h3>
<h4>Total Price: $'.$row['price'].'</h4>
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>Our best seller. Full of flavour.</p>
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" value="' . $row['qty'] . '">
</div>
</div>
<input type="hidden" name="id" value="'.$row['id'].'">
<button type="submit" name="update" class="btn btn-primary">Update</button>
<button type="submit" name="delete" class="btn btn-primary">Remove</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
if(!empty($container)){
$excluded_names = implode(',', $container);
$sql = "SELECT * FROM item WHERE itemName NOT IN($excluded_names)";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$price ="";
if ($_SESSION['customer_band'] == 'A') {
$price = $row['bandA'];
}
else if ($_SESSION['customer_band'] == 'B') {
$price = $row['bandB'];
}
else if ($_SESSION['customer_band'] == 'C') {
$price = $row['bandC'];
}
else if ($_SESSION['customer_band'] == 'D') {
$price = $row['bandD'];
}
else if ($_SESSION['customer_band'] == 'E') {
$price = $row['bandE'];
}
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input id="itemname" type="hidden" name="itemName" value="'.$row['itemName'].'">
<h3>$'.$price.'</h3><input id="price" type="hidden" name="pricetotal" value="'.$price.'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input id="description" type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input id="qty" type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" id="additem" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
}
else
{
$sql = "SELECT * FROM item";
$stmt = $conn->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$price ="";
if ($_SESSION['customer_band'] == 'A') {
$price = $row['bandA'];
}
else if ($_SESSION['customer_band'] == 'B') {
$price = $row['bandB'];
}
else if ($_SESSION['customer_band'] == 'C') {
$price = $row['bandC'];
}
else if ($_SESSION['customer_band'] == 'D') {
$price = $row['bandD'];
}
else if ($_SESSION['customer_band'] == 'E') {
$price = $row['bandE'];
}
$data['result_2'] .= '
<div class="col-sm-4 col-md-4">
<div class="content-boxes style-two top-column clearfix animated flipInY" style="opacity: 1;">
<div class="content-boxes-text">
<form action="php/additem.php" method="post" class="form-inline pull-right">
<h4>'.$row['itemName'].'</h4><input type="hidden" name="itemName" value="'.$row['itemName'].'">
<h3>$'.$price.'</h3><input type="hidden" name="pricetotal" value="'.$price.'">
<img src="../wholesale/img/sourdough.jpg" class="img-reponsive">
<p>'.$row['description'].'</p><input type="hidden" name="description" value="'.$row['description'].'">
<div class="form-group">
<label class="sr-only" for="exampleInputAmount">Qty</label>
<div class="input-group">
<input type="number" name="qty" class="form-control" id="exampleInputAmount" placeholder="How Many?">
</div>
</div>
<button type="submit" id="additem" class="btn btn-primary">Add</button>
</form>
</div>
<!-- //.content-boxes-text -->
</div>
<!-- //.content-boxes -->
</div>
';
}
}
echo json_encode($data);
exit;
Both Update and Delete PHP file:
include('db_config.php');
if (isset($_POST['update']))
{
$qty = $_POST['qty'];
$id = $_POST['id'];
echo $id;
$sql = "UPDATE orders SET qty=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($qty,$id));
header('Location: ../order.php');
}
if (isset($_POST['delete']))
{
$id = $_POST['id'];
$sql = "DELETE FROM orders WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->execute(array($id));
header('Location: ../order.php');
}
The code above needs to be converted to AJAX, and both sections on the page using ajax should update the table automatically. It might be that you will call the first ajax query to reload the tables correctly?
Thanks for having a look at this.
I am having trouble wrapping my head around how i should get this work.
Alex
It is easy you can give a class (NOTE : yes class ) to your update button and similarly to delete button
Suppose your update button has class "update_task"
but your content was added to DOM after DOM already loaded, so you will need to create two ajax request with DELEGATE Methods for delete and update.
For delegate reference -
http://api.jquery.com/delegate/
// for update
$("body").delegate(".update_task","click",function(){
current_id = $(this).previous("input:hidden").val() // for current update button id,
$.ajax({
type: 'POST',
url: 'php/update_product.php',
data: {id: current_id, othervalues: other_value_of_choice},
dataType: 'JSON',
success: function(data)
{
if(data==1)
{
// what ever you want to do if data has been updated
}
}
});
});
Send AJAX request to PHP for update/delete. Return result of operation (true/false).
If result is true, update/remove from html with javascript(jquery).
By the way, don't use redirect, when you call php via ajax.
Now this one seems a little complicated and maybe I have got myself into more than I can manage but it seems the only way I can achieve what I need.
I am a complete novice and am going at this blindly for a project I'm working on (this is the most complicated thing in the whole project) so any help would be much appreciated!
I basically have a bootstrap webpage, this webpage displays a users list (from php in a while loop). What I need the user to be able to do is select a user from this and edit the details in a form in a bootstrap modal.
So far I have everything working, modal loading etc and from various sources online have wrangled JSon but I've never learnt it and am way out of my depths. Currently it is printing '[object HTMLCollection]' in each field.
Firstly here is the HTML for the modal & list:
Modal (This comes up perfectly)
<div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h2 class="modal-title" id="editModalLabel"></h2>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="username" class="control-label">Username:</label>
<input type="text" name="username" class="form-control" id="username"></input>
</div>
<div class="row">
<div class="col-lg-12">
<div class="form-group">
<label for="password" class="control-label">Password:</label>
<div class="input-group">
<span class="input-group-btn">
<input type="button" class="form-control" value="Change Password" onClick="changeRandomPassword();">
</span>
<input type="text" name="password" class="form-control" id="password" value="" required></input>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="firstName" class="control-label">First Name:</label>
<input type="text" name="firstName" class="form-control" id="firstName">
</div>
<div class="form-group">
<label for="lastName" class="control-label">Surname:</label>
<input type="text" name="lastName" class="form-control" id="lastName">
</div>
<div class="form-group">
<label for="jobTitle" class="control-label">Job Title:</label>
<input type="text" name="jobTitle" class="form-control" id="jobTitle">
</div>
<div class="form-group">
<label for="TaskTeam" class="control-label">Task Team:</label>
<input type="text" name="TaskTeam" class="form-control" id="TaskTeam">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success">Submit Changes</button>
</div>
</div>
</div>
</div>
Here is the php list: (again no trouble here)
<?php
include("dbconnect.php");
$dbQuery= mysql_query("SELECT * FROM users ORDER BY lastName ASC;");
while($dbRow = mysql_fetch_array($dbQuery))
{
$userID = $dbRow['id'];
$username = $dbRow['username'];
$firstName = $dbRow['firstName'];
$lastName = $dbRow['lastName'];
$jobTitle = $dbRow['jobTitle'];
$userteam = $dbRow['TaskTeam'];
$admin = $dbRow['admin'];
echo '<tr>';
echo '<td>';
echo '<button type="button" class="btn btn-primary close" data-toggle="modal" data-target="#editUserModal" value='.$userID.' id="user" name="user"" data-user='.$userID.'><span title="Edit" aria-hidden="true" class="glyphicon glyphicon-edit"></span></button>';
echo '</td>';
echo '<td>'.$firstName.'</td>';
echo '<td>'.$lastName.'</td>';
echo '<td>'.$jobTitle.'</td>';
echo '<td>'.$userteam.'</td>';
echo '<td>'.$admin.'</td>';
echo '<td>';
echo '<a href="deleteUser.php?id='.$userID.'">';
echo '<button type="button" name="delete_row" id="delete_row" class="close">';
echo '<span title="Delete" aria-hidden="true" class="glyphicon glyphicon-trash">';
echo '</span>';
echo '<span class="sr-only">';
echo 'Delete';
echo '</span>';
echo '</button>';
echo '</a>';
echo '</td>';
echo '</tr>';
}
echo mysql_error();
mysql_close();
?>
Here is where the problem must lay:
<script>
$('#editUserModal').on('show.bs.modal', function (event)
{
var button = $(event.relatedTarget)
var recipient = button.data('user')
var modal = $(this)
modal.find('.modal-title').text('Edit ' + recipient + "'s details.")
$(function ()
{
$.ajax(
{
type: 'GET',
url: "getUser.php?id=",
data: 'recipient',
dataType: "json",
success: function(data)
{
var obj = JSON.parse(data);
$.each(obj, function(key, val)
{
console.log(val);
var id = data[0];
var firstName = data[1];
var lastName = data[2];
var username = data[3];
var password = data[4];
var jobTitle = data[5];
var TaskTeam = data[6];
var admin = data[12];
});
}
})
})
modal.find('.modal-body #firstName').val(firstName)
modal.find('.modal-body #lastName').val(lastName)
modal.find('.modal-body #username').val(username)
modal.find('.modal-body #password').val(password)
modal.find('.modal-body #jobTitle').val(jobTitle)
modal.find('.modal-body #TaskTeam').val(TaskTeam)
})
</script>
Lastly here is php file to get the user details: (This works too but only is done manually- This is the bulk of it excluding passwords etc)
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$userid = intval($_GET['id']);
$sql="SELECT * FROM users WHERE id = $userid";
$result = $conn->query($sql);
/*
$user = array();
while ($row = mysql_fetch_array($result)) {
$details = array(
"username" => $row['username'],
"firstName" => $row['firstName'],
"lastName" => $row['lastName'],
"taskTeam" => $row['taskTeam']
);
$user[] = $details;
}
echo json_encode($user);
$conn->close();
*/
if ($result->num_rows > 0) {
// output data of each row
$array = array();
while($row = $result->fetch_assoc()) {
array_push($array, $row);
}
echo json_encode($array);
} else {
echo "0 results";
}
$conn->close();
Sorry for lack of Mysqli I know this is the latest standard and am currently implementing it in this project.
Any help would be great! Thanks
The problem with your code is here:
var obj = JSON.parse(data);
$.each(obj, function(key, val)
{
console.log(val);
var id = data[0];
var firstName = data[1];
var lastName = data[2];
var username = data[3];
var password = data[4];
var jobTitle = data[5];
var TaskTeam = data[6];
var admin = data[12];
});
You've already told your AJAX call that you are expecting JSON back from your PHP script. You did this with dataType: "json". So there is no reason to do this here: var obj = JSON.parse(data);. Since you told your AJAX call you are going to receive JSON back, it automatically parses it for you when the PHP script completes.
To access the data simply use the . syntax. For example, data.firstName
Also, you may need to need to change this line in your PHP file from
echo json_encode($array);
to
header('Content-Type: application/json');
echo json_encode($array);
Also, your PHP script needed some cleaning up:
<?php
include("dbconnect.php");
$dbQuery = mysql_query("SELECT * FROM users ORDER BY lastName ASC;");
while ($dbRow = mysql_fetch_array($dbQuery)) {
$userID = $dbRow['id'];
$username = $dbRow['username'];
$firstName = $dbRow['firstName'];
$lastName = $dbRow['lastName'];
$jobTitle = $dbRow['jobTitle'];
$userteam = $dbRow['TaskTeam'];
$admin = $dbRow['admin'];
echo '
<tr>
<td>
<button type="button" class="btn btn-primary close" data-toggle="modal" data-target="#editUserModal" value='.$userID.' id="user" name="user"" data-user='.$userID.'><span title="Edit" aria-hidden="true" class="glyphicon glyphicon-edit"></span></button>
</td>
<td>'.$firstName.'</td>
<td>'.$lastName.'</td>
<td>'.$jobTitle.'</td>
<td>'.$userteam.'</td>
<td>'.$admin.'</td>
<td>
<a href="deleteUser.php?id='.$userID.'">
<button type="button" name="delete_row" id="delete_row" class="close">
<span title="Delete" aria-hidden="true" class="glyphicon glyphicon-trash"></span>
<span class="sr-only">Delete</span>
</button>
</a>
</td>
</tr>';
}
echo mysql_error();
mysql_close();
?>
I have a user list on an HTML table, when I click an entry I have a modal loading through AJAX which should fill a form out with all the relevant information from that user. Information can then be changed and submitted via a change.
I cannot get past getting the modal to load and cannot get data to be loaded into the model.
Here is the script:
<script>
$('#editUserModel').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('userID')
$(function ()
{
$.ajax({
url: 'getUser.php?id=',
data: "recipient",
dataType: 'json',
success: function(data)
{
var id = data[0]; //get id
var firstName = data[1]; //get name etc...
var lastName = data[2];
var username = data[3];
var password = data[4];
var jobTitle = data[5];
var TaskTeam = data[6];
var admin = data[12];
var modal = $(this)
modal.find('.modal-body input').html(username)
}
});
});
})
</script>
Here is the PHP which lists the users (this works and when I click the Edit button a modal loads however the modal is grayed out and shows no underlying data)
<?php
include("dbconnect.php");
$dbQuery= mysql_query("SELECT * FROM users ORDER BY jobTitle ASC;");
while($dbRow = mysql_fetch_array($dbQuery))
{
$userID = $dbRow['id'];
$username = $dbRow['username'];
$firstName = $dbRow['firstName'];
$lastName = $dbRow['lastName'];
$jobTitle = $dbRow['jobTitle'];
$userteam = $dbRow['TaskTeam'];
echo '<tr>';
echo '<td>';
echo '<button type="button" class="btn btn-primary close" data-toggle="modal" data-target="#editUserModel" data-userID='.$userID.'><span title="Edit" aria-hidden="true" class="glyphicon glyphicon-edit"></span></button>';
echo '</td>';
echo '<td>'.$firstName.'</td>';
echo '<td>'.$lastName.'</td>';
echo '<td>'.$jobTitle.'</td>';
echo '<td>'.$userteam.'</td>';
echo '<td></td>';
/*
echo '<td>';
echo '</td>';
*/
echo '</tr>';
}
echo mysql_error();
mysql_close();
?>
Here is the modal div:
<div class="modal fade" id="editUserModel" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="editModalLabel"></h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="username" class="control-label">Username:</label>
<input type="text" class="form-control" id="username">
</div>
<div class="form-group">
<label for="password" class="control-label">Password:</label>
<input type="text" class="form-control" id="password">
</div>
<div class="form-group">
<label for="firstName" class="control-label">First Name:</label>
<input type="text" class="form-control" id="firstName">
</div>
<div class="form-group">
<label for="lastName" class="control-label">Surname:</label>
<input type="text" class="form-control" id="lastName">
</div>
<div class="form-group">
<label for="jobTitle" class="control-label">Job Title:</label>
<input type="text" class="form-control" id="jobTitle">
</div>
<div class="form-group">
<label for="TaskTeam" class="control-label">Task Team:</label>
<input type="text" class="form-control" id="TaskTeam">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Submit Changes</button>
</div>
</div>
</div>
</div>
And here is the php file which retrieves the user data:
<?php
$userID = intval($_GET['id']);
include("dbconnect.php");
$sql="SELECT * FROM users WHERE id = $userID";
$result = mysql_query($sql);
$array = mysql_fetch_row($result);
echo json_encode($array);
mysql_close();
?>
I don't fully understand PDO, I'm not sure where the problem is.
Rahter than mysql use mysqli. Also, the problem is happening because you need to iterate through your rows result. Try this:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$userID = intval($_GET['id']);
$sql="SELECT * FROM users WHERE id = $userID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$array = array();
while($row = $result->fetch_assoc()) {
array_push($array, $row);
}
echo json_encode($array);
} else {
echo "0 results";
}
$conn->close();
Then in your JS, replace the contents of .success with this:
success: function(data) {
var obj = JSON.parse(data);
$.each(obj, function(key, val) {
console.log(val);
//add your functions here
/*
var id = data[0]; //get id
var firstName = data[1]; //get name etc...
var lastName = data[2];
var username = data[3];
var password = data[4];
var jobTitle = data[5];
var TaskTeam = data[6];
var admin = data[12];
var modal = $(this)
modal.find('.modal-body input').html(username)
*
*/
});
}