I have a file cart.html which displayes a list of items fetched from database and each item has a button 'AddToCart' which when clicked call the function addDB() and add the product to the table product_add.
My problem is that when the button 'AddToCart' is clicked only nulll values are inserted in the table product_add .
//This function is found in the cart.html and get the items from the database
$(document).ready(function() {
$("#product").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "allProducts.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
//the above function is called when a button 'View All Products' is clicked
<input type="button" id="cart" value="View Cart"/>
The above code works fine and displayes the result
//These lines of codes are in the allProducts.php
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td><img src=".$row['image']." width='120' height='100'/></td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['price']."</td>";
echo "<td>";
echo "<input type='button' value='Add to Cart' onclick='addDB()'/>";
echo "</td>";
echo "</tr>";
Here is the function addDB()
function addDB() {
var request = $.ajax({
url: "add.php",
type: "GET",
dataType: "html"
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
};
This is the add.php
<?php
include 'dbConnect.php';
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id', '$name','$price')";
$insertQuery=mysql_query($insert);
?>
My problem is that when the button 'AddToCart is clicked' null or 0 are being inserted in the database.Can somebody please help me ?
You are not sending any data to the php-page. A simple approach would be to pass them via GET-Parameters in the url of you AJAX-Call:
function addDB(id, name ,price) {
var request = $.ajax({
url: "add.php?id=" + id + "&name=" + name + "&price=" + price,
type: "GET"
});
request.done(function() {
alert("Ajax call done.");
});
}
Also, your code is vulnerable to sql-injections. Please do ALWAYS use prepared statements
You modified add.php would then look like this:
<?php
include 'dbConnect.php';
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$price= isset($_GET['price']) ? $_GET['price'] : "";
$query = $mysqli->prepare("INSERT INTO product_add(id, name, price) VALUES (?, ?, ?)");
$query->bind_param("isi", $id, $name, $price);
$query->execute();
$query->close();
?>
You would of course have to initialize the object "$mysqli" somehow in your file dbConnect.php in order to use it.
Related
What I'm trying to achieve is a user to follow another user without having to refresh the page. So far I've played around and had no problem inserting and deleting the rows in mysql table, but now when I'm trying with AJAX I can't get it to work.
jquery
$(document).ready(function(){
$("#followbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();
$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#followbutton').hide();
$('#unfollowbutton').show();
// $("#unfollowbutton").hover(function(){
// $(this).text("Unfollow");
// }, function(){
// $(this).text("Unfollow");
// });
}
});
});
});
$(document).ready(function(){
$("#unfollowbutton").click(function(e) {
e.preventDefault();
var theuserid = $('#theuserid').val();
var thefollower = $('#thefollower').val();
$.ajax({
url: 'includes/followuser.inc.php',
type: 'post',
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitUnfollow': true},
success: function(response){
$('#followmessage').html(response);
$("#followmessage").show().delay(3000).fadeOut();
$('#unfollowbutton').hide();
$('#followbutton').show();
//I want the button to change its text to Following and when hovering it should say unfollow if user is followed
}
});
});
});
followuser.inc.php
<?php
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
if (isset($_POST["submitFollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('INSERT INTO userfollow (thefollower, theuserid, followstatus) VALUES (?,?,?)');
$followstatus = 1;
$stmt->bind_param('sss', $userthatisfollowed, $theuserid, $followstatus);
$stmt->execute();
echo $response = "<span>Followed!</span>";
$stmt->close();
} else if(isset($_POST["submitUnfollow"])){
$userthatisfollowed = $_POST["thefollower"];
$theuserid = $_POST["theuserid"];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('DELETE userfollow FROM userfollow WHERE thefollower = ? AND theuserid = ?');
$stmt->bind_param('ss', $userthatisfollowed, $theuserid);
$stmt->execute();
echo $response = "<span>Unfollowed!</span>";
$stmt->close();
} else {
echo "DID NOT WORK";
}
profile.php
if(isset($_SESSION["userid"]) && $_SESSION["userid"] != $userthatisfollowed) {
?>
<form action="<?php echo htmlspecialchars("includes/followuser.inc.php");?>" id="followform" method="post">
<?php
if ($resulted->num_rows > 0){
$subscribe_status = "Unfollow";
$subscribe_text = "Following";
} else {
$subscribe_status = "Follow";
$subscribe_text = "Follow";
}
echo "<button name='submit".$subscribe_status."' id ='unfollowbutton' type='submit' style='display:none'>";
echo "<span>".$subscribe_text."</span>";
echo "</button>";
echo "<button name='submit".$subscribe_status."' id ='followbutton' type='submit'>";
echo "<span>".$subscribe_text."</span>";
echo "</button>";
// echo "<button name='submit".$subscribe_status."' id ='notificationbell' type='submit' style='display:none'>";
// echo "<i class='fa fa-bell'></i>";
// echo "</button>";
echo "<div id='followmessage'></div>";
?>
<input type="hidden" name="theuserid" id="theuserid" value="<?php echo $_SESSION["userid"] ?>">
<input type="hidden" name="thefollower" id="thefollower" value="<?php echo $userthatisfollowed; ?>">
</form>
<?php
}
What's worth noting is that I'm getting the response DID NOT WORK which tells me that if(isset($_POST["submitUnfollow"])) is not set. However, If I try with if(isset($_POST["theuserid"]) && (isset($_POST["thefollower"])) then it actually works for the insert query but not for the delete query.
You're missing the submitFollow parameter in the data: object. Instead, you have followbutton: true, which isn't used by the PHP code. So change that to:
data: {'theuserid': theuserid, 'thefollower': thefollower, 'submitFolow': 'true'},
And for the unfollow button, use submitUnfollow instead.
whats wrong with this?
EDIT:
$check = $row['publish'] == 1 ? 'true' : 'false';
It works when I want to unpublished, but if the checkbox is empty I cannot publised.
OnClick="doAction(<?php echo $check;?>, <?php echo $id;?>);"
function doAction(check,id){
$.ajax({
type: "GET",
url: "test.php",
data: "check=" + check + "&id=" + id,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
and the file test.php:
$id = $_GET['id'];
$check = $_GET['check'];
if ($check == "false"){
$query = mysql_query("update article set publish = 1 where id =" . $id);
echo "Published";
}
else {
$query = mysql_query("update article set publish = 0 where id =" . $id);
echo "Unpublished";
}
I cannot display the id in the test.php file.it gives me nothing. But in the doAction parameters are(.., id) so it's been sent but I don t receive it in the ajax call and then in file. Why?
Try change:
data: "check=" + check + "&id = " + id,
To:
data: "check=" + check + "&id=" + id,
And you should define what will be response HTML , JSON etc. use for this example:
dataType: "JSON"
If you are passing the value in arguments use below code.
OnClick="doAction('<?php echo $check;?>', '<?php echo $id;?>');"
I have a table display and I want to enable users to edit the values of the table in a live way using jQuery. The table is simple, it just has 1 column with a list of names. I have it all built out but at the moment the table doesn't update the value. All the code is below, I am still learning everything so it's probably not written very well/correctly! Thanks in advance.
Form Display:
<?php
echo "<div class=\"table-responsive\"><table class=\"table table-striped\">";
echo "<thead><tr><th>Employee Name</th><th></th></tr></thead><tbody>";
require_once 'connectionsettings.php'; // Gets connection settings
$sql = "SELECT id, employees FROM Employees ORDER BY employees ASC";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// what it's saying is that if there's rows do something
while($row = $result->fetch_assoc()) {
// now it's saying get the data and put it in rows
echo "<tr><td data-id='{$row['id']}' contenteditable=\"true\">" . $row["employees"] . "</td><td><span data-id='{$row['id']}' name='remove_{$row['id']}' class='employee glyphicon glyphicon-remove' aria-hidden='true'></span></td></tr>";
}
}else{
echo "No Employees! Let's add some.";
}
$mysqli->close();
echo "</tbody></table></div>";
?>
Jquery Info:
$(function(s){
$("td[contenteditable=true]").blur(function(){
var id = $(this).attr("id") ;
var name = $(this).text() ;
var formURL = "updateemployeename.php";
$.ajax({
url : formURL,
type: "POST",
data : {name: name, id: id},
success:function(data, textStatus, jqXHR)
{
$('#successmessage2').slideDown('fast').delay(1500).slideUp('fast');
$('div#employeedisplay').hide();
$('div#updatedemployeedisplay').load('employeedisplay.php').fadeIn(3000);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
});
s.preventDefault(); //STOP default action
});
SQL Info:
<?php
require_once 'connectionsettings.php'; // Gets connection settings
$name = htmlspecialchars(trim($_POST['name']));
$id = htmlspecialchars(trim($_POST['id']));
$sql = "UPDATE Employees SET employees='$name' WHERE id='$id'";
if($mysqli->query($sql) === TRUE) {
echo "status updated successfully";
}else{
echo "Error updating status" . $mysqli->error;
}
$mysqli->close();
?>
If I click on submit button using only php, data are recorded in mysql.
Through ajax _autosave.php only update works. Insert does not work. going crazy.... can not understand
ajax code in first.php
<script type="text/javascript">
$(document).ready(function() {
setInterval(function (){
var date_day1=$("#date_day1").val();
var amount1=$("#amount1").val();
DATA = 'date_day1=' + date_day1 + '&amount1=' + amount1;
$.ajax({
type: "POST",
url: "_autosave.php",
data: DATA,
cache: false,
/*success: function(){
$(".done").show().html("Saved as a draft!");
}*/
});
setTimeout(function(){
$(".done").hide();
}, 1000);// 15 seconds
}, 3000);// 1 minute
});
</script>
HTML input
<td><input type="text" name="date_day1" id="date_day1" value="<?php echo $_POST['date_day1']?>" size="1"></td>
<td><input type="text" name="amount1" id="amount1" value="<?php echo $_POST['amount1']?>" size="5"></td>
Part of php code that is identical in first.php and _autosave.php
$date_day1 = $_POST['date_day1'];
$amount1 = $_POST['amount1'];
if ($stmt = mysqli_prepare($mysqli, "SELECT RecordDay FROM 2_1_journal WHERE RecordDay = ? ")) {
$stmt->bind_param('s', $date_day1);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($RecordDay);
$stmt->fetch();
//echo $RecordDay .' $RecordDay<br>';
}
if ($RecordDay == $date_day1) {
if ($stmt = mysqli_prepare($mysqli, "UPDATE 2_1_journal SET Amount = ? WHERE RecordDay = ? ") ) {
$stmt->bind_param( 'ds', $amount1 , $date_day1 );
$stmt->execute();
/*echo $date_day1 .' date_day1<br>';
echo $amount1 .' amount1<br>';*/
}
}
else {
if ($stmt = mysqli_prepare($mysqli, "insert into 2_1_journal
(RecordDay, Amount, DebitAccount, CreditAccount)
values(?,?,?,? )")) {
$stmt->bind_param('sdss', $date_day1, $amount1, $debit1, $credit1 );
$stmt->execute(); //execute above insertion
}
}
Update works in both files (called from both files). Insert works only if called without ajax. What is wrong?
Update
Finally found what was wrong. If $_POST is not set (not send), nothing is recorded in mysql. However no error message after execution. Simply need to remember that all variables here $stmt->bind_param('sdss', $date_day1, $amount1, $debit1, $credit1 ); must exist.
The data syntax might be the reason, use this format:
data: { key1: "value1", key2: "value2" }
See this example from: http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
so, for your case try:
$.ajax({
type: "POST",
url: "_autosave.php",
data: {date_day1:$("#date_day1").val(), amount1: $("#amount1").val()},
cache: false,
});
in insert you binding 5 parameters instead of 4
I have a PHP form that uses jQuery/AJAX to submit data into a MySQL database table. Currently, I have a message display saying " Done!" once the form is submitted, but would like the actual data to instantly display after it has been submitted. I have a loop setup to display previously added messages in divs with the class name 'msg_container', and would like the new data to display in one of these divs after form submission.
What is the best way to do this? Any help would be greatly appreciated!
index.php javascript
<script type="text/javascript">
$(document).ready(function () {
$(".button").click(function () {
var user_id = $("textarea#uer_id").val();
var msg = $("textarea#msg ").val();
var dataString = 'user_id=' + user_id + '&msg=' + msg;
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function () {
alert("Done!")
}
});
return false
});
});
</script>
index.php query
$user_id = $_GET['user_id'];
require_once('../../includes/connect.php');
$dbh = get_dbh($_SESSION['ORG_ID']);
$sth = $dbh->query ("SELECT *, user.last_name, user.first_name FROM msgs
INNER JOIN users
ON msgs.user_id = users.id
WHERE user_id = '$user_id'
ORDER BY timestamp");
$row = $sth->fetch ();
index.php HTML
<div id="msgs">
<?php while ($row = $sth->fetch ()) { ?>
<div class="msg_container">
<div class="left"><? echo $row['last_name'].', '.$row['first_name']; ?><br />
<? $timestamp = date('m/d/Y g:i a', strtotime($row['timestamp'])); echo $timestamp; ?>
</div>
<div class="right"><? echo $row['msg']; ?></div>
<div class="clear"></div>
</div>
<? } ?>
<div class="add_note">
<div class="left">Add Message</div>
<div class="right">
<form id="add_msg">
<textarea id="msg" name="msg"></textarea>
<input type='submit' class="button right-aligned" value='Submit' />
</form>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</div>
add.php
<?php
require_once('../../includes/connect.php');
$dbh = get_dbh($_SESSION['ORG_ID']);
$user_id = $_POST['user_id'];
$msg= $_POST['msg'];
date_default_timezone_set("UTC");
$timestamp = date('Y-m-d H:i:s', strftime(gmmktime()));
date_default_timezone_set($_SESSION['TIME_ZONE']);
$sth = $dbh->prepare ("INSERT INTO msgs (id, user_id, msg, timestamp) VALUES (?, ?, ?, ?)");
$data = array (NULL, $user_id, $msg, $timestamp);
$sth->execute ($data);
session_write_close();
?>
You could just append the new message after the previous ones. Something like this:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function() {
alert ("Done!");
$('#msgs').append('<div class="msg_container">' +
'<div class="left">' + lastNameVariable + ', ' + firstNameVariable +
'<br />' + timeStampVariable +
'</div><div class="right">' + msg + '</div>' +
'<div class="clear"></div></div>');
}
});
You will need to put the first name, last name, timestamp, etc. into variables (or do it a different way, like do an AJAX call to get the info - whatever you prefer). I didn't know what user_id is so I just thought I would let you fill in those variables.
This is just the basic idea of what you could do. If you have any questions, just ask.
I hope this helps.
Edit:
If you created another page called "getname.php" or something like that (to get the first and last name) that would display "first name, last name" based on the user ID passed in the URL, that could work. In the URL it could have ?user_id=1234567 and then on that page, it would do a mysql_query and display the first and last name. This is what I would do:
getname.php ↓
<?
// ...
$user_id = $_GET['user_id'];
$result = mysql_query("SELECT * FROM table WHERE user_id = '$user_id' AND ...");
$row = mysql_fetch_array($result);
// ...
echo $row['last_name'] . ', ' . $row['first_name'];
// ...
?>
Of course you would do this the way you do your queries, but hopefully this helps you understand what I'm saying. Then, after you have that, you can do:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function() {
alert ("Done!");
var firstAndLast = '';
var theTime =
$.get('getname.php?user_id='+user_id, function(data) {
firstAndLast = data;
});
$('#msgs').append('<div class="msg_container">' +
'<div class="left">' + firstAndLast // this will display: "first name, last name" because of getname.php
+ '<br />' + theTime +
'</div><div class="right">' + msg + '</div>' +
'<div class="clear"></div></div>');
}
});
As for the time, you could either display it with JavaScript (when they refresh it would show the time that was recorded by PHP) or do the same as you did for name.
Consider the jQuery ajax method load. This is a higher level version of ajax. You will send your request and the response will immediately be placed into the preceding selector elements.
$('#result').load('ajax/test.html', data);
Here's just a quick idea to get you going. You need to return the data from the script you call with AJAX; a data that you would use to generate the DIV you want. You'll also need to change the ajax call to something like this:
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function(data) {
console.log(data); //to see what's returned
//use the data to generate content you want
alert ("Done!")
}
});
Due to the structure of your data, it might be the best to send a JSON response.
In the success part add this code:
success: function(data){
$('#flash').css("display","block");;
setTimeout(function () {
$('#flash').slideUp();`enter code here`}, 2000);
}
In the HTML add this code:
<div id="flash" style="display:none;">Data Saved Successfully</div>