I'm trying to get a value from my database and then run an update using sweet alert pop-up but it is not working. The alert seem to pop-up and once the value is entered, it displays the value entered but not working. below is my actual ajax code:
viewproduct.php
<script>
$(document).ready(function() {
$('.btnupdatestock').click(function() {
var id = $(this).attr("id");
//var new_stock = $(this).val();
swal("Add Stock:", {
content: "input",
})
.then((updateStock) => {
$.ajax({
type: 'POST',
url: 'stock-in.php',
data:{
stock_up: updateStock,
},
success: function(data){
swal(`Updated: ${updateStock}`);
},
error: function(data){
swal(`Error updating: ${updateStock}`);
}
});
});
});
});
</script>
the above method was designed to trigger sql in stock-in.php and the code in stock-in.php is below:
<?php
include_once'connectdb.php';
if($_SESSION['useremail']=="" OR $_SESSION['role']=="Admin"){
header('location:index.php');
}
$idd=$_GET['id'];
$select=$pdo->prepare("select * from tbl_product where pid=$idd");
$select->execute();
while($row=$select->fetch(PDO::FETCH_OBJ)){
$productName = $row['pname'];
$oldstock = $row['pstock'];
//$id=$_POST['uid'];
$stockup=$_POST['stock_up'];
alert('I clicked');
$new_stock = $oldstock + $stockup;
$sql="UPDATE `tbl_product` SET `pstock` = ? WHERE pid= ? ";
$update=$pdo->prepare($sql);
$update->execute([$new_stock, $idd]);
if($result){
echo'Stock updated!';
}else{
echo'Error in updating stock';
}
}
?>
below is a picture of my UI that shows pop-up but it's not updating.
This is what I intend to do: If a user clicks on update and enters a value say 50, it should retrieve the old stock (database, say 100) and add to the new stock (value entered, say 50) and then update the database with 150. I am stuck here and any help would be appreciated. Thanks.
$(document).ready(function() {
$('.btnupdatestock').click(function() {
swal("Add Stock:", {
buttons: true,
closeModal: true,
content: "input",
}).then((updateStock) => {
if (updateStock === "") {
swal("You need to write something!");
return false
}else{
$.ajax({
type: 'POST',
url: 'stock-in.php',
data:{
stock_up: updateStock
<?php
echo ', id: '.$row->pid.' '
?>
<?php
echo ', oldstock: '.$row->pstock.' '
?>
},
success: function(data){swal(`Updated: ${updateStock}`);},
error: function(data){swal(`Error updating: ${updateStock}`);}
});
}
});
});
});
The major issue I had was I didn't make the SQL query global at the top of my page and then applied '.$row->pid.'
Related
I'm working on my first php/SQL database project and my goal is to store an array of checkbox values into a database.
On clicking the submit on the checkbox form, i am trying to post the array of checkbox values from my jquery doc to index.php
The success response is my index.php page, which i think is correct, so it all seems correct for me and i'm having a hard time figuring why
My array is generated from a series of .push() calls that update to determine when a box is checked it not and only submitted when i click my form submit, which should trigger the ajax post.
var checkArr =
[
{id: "CB1", val: "checked"},
{id: "CB3", val: ""},
{id: "CB5", val: ""},
{id: "CB4", val: "checked"},
{id: "CB2", val: ""}
];
//SUBMIT CHECKBOX VALUES TO PHP
$('#submitCheck').on('click', function(){
$.ajax({
url: 'index.php',
type: 'POST',
data: {checkArr:checkArr},
cache: false,
success: function(response){
alert("ok");
console.log(response);
}
});
});
Here however when i check to see if the post worked i only return 'is not set'.
if(isset($_POST['checkArr'])){
$arr = $_POST['checkArr'];
echo $arr;
} else {
echo 'Is not set';
}
I know there are many similar questions but i haven't found a solution in any of them unfortunately.
I found one thread that mentioned it might be redirecting me before the post can be processed so i removed the action from my form and nothing changed. I tried to stringify my output as json and still the same problem (even if stringify is redundant because of jquery).
Edit: Full code snippet
var checkArr = [];
//COLOUR ITEMS ON PAGE LOAD
$(document).ready(function(){
var box = $(':checkbox');
if(box.is(':checked')){
box.parents("li").removeClass('incomplete');
box.parents("li").addClass('complete');
} else {
box.parents("li").removeClass('complete');
box.parents("li").addClass('incomplete');
}
});
//DELETE ITEM
$(document).on('click','.delete', function(){
console.log('DELETED');
var id = $(this).attr('id')//get target ID
var item = $(this).closest('li');//targets the li element
//AJAX
$.ajax({
url: 'delete.php',
type: 'POST',
data: { 'id':id },
success: function(response){
if(response == 'ok') {
item.slideUp(500,function(){
item.remove();
});
} else if(response == 'error') {
console.log("error couldn't delete");
} else {
console.log(response);
}
}
});
});
//CREATE ARRAY OF CHECKBOX VALUES
$('#checkform').on('click','.boxcheck', function(){
var check = $(this).prop("checked");
var val = "";
var tempId = $(this).attr('id');
if(check === true){
val = "checked";
console.log(val);
var tempArr = {
"id": tempId,
"val": val
};
checkArr.push(tempArr);
} else if (check === false){
val = "";
console.log(val);
for (var i = checkArr.length - 1; i >= 0; --i) {
if (checkArr[i].id == tempId) {
checkArr[i].id = tempId;
checkArr[i].val = val;
}
}
}
console.log(checkArr);
});
//CHANGE COLOUR OF ITEMS
$(':checkbox').change(function(){
var current = $(this);
if(current.is(':checked')){
current.parents("li").removeClass('incomplete');
current.parents("li").addClass('complete');
} else {
current.parents("li").removeClass('complete');
current.parents("li").addClass('incomplete');
}
});
//SUBMIT CHECKBOX VALUES TO PHP
$('#submitCheck').on('click', function(e){
e.preventDefault();
console.log(checkArr);
$.ajax({
url: 'index.php',
type: 'POST',
data: {checkArr:checkArr},
cache: false,
success: function(response){
alert("ok");
}
});
});
I tried your code and it's working perfectly for me.
Now the only thing I can think of is your url in your ajax request. make sure you are really submitting to index.php.
You can use JSON.stringify() to submit the array from ajax to php
Posting here to update just in case anyone has a similar problem, the code itself was correct(sort of), after a lot of digging and asking around, it turns out the local server i was using, XAMPP, had too small a POST upload limit hence the empty array on the php side, increasing the php.ini upload limit from 2mb to 10mb finally fixed it!
I am using the script found here to update my database if a box is checked.
https://stackoverflow.com/posts/4592766/revisions
It works if I check an unchecked box.
However, I can't seem to get it working if I uncheck a checked box. It will not update the database.
Here is the modified code:
$(document).ready(function() {
$("input[type=checkbox]").click(function() {
var isSel = this.checked;
var isNotSel = this.unchecked; //added
$.ajax({
url: 'file.php',
type: 'POST',
dataType: 'json',
data: {
id : this.id,
isSelected : isSel,
isNotSelected : isNotSel // added
},
success: function(data) {
alert('updated');
},
error: function() {
alert('error');
}
});
});
});
This is the code showing the checkboxes (created from database):
if($status == 'pending')
{ echo '<input type="checkbox" name="status" id='.$submission_id.' >' .
$task_name . '<br>'; }
if($status == 'done')
{ echo '<input type="checkbox" name="status" id='.$submission_id.' checked>'
. $task_name . '<br>'; }
Here is the code for file.php
if ($_POST && isset($_POST['isSelected'])) {
$sql = 'UPDATE ft_form_53 SET status = "done" WHERE submission_id = ' . $_POST['id'];
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
if ($_POST && isset($_POST['isNotSelected'])) {
$sql = 'UPDATE ft_form_53 SET status = "pending" WHERE submission_id = ' . $_POST['id'];
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
No error message is thrown. Any ideas?
Change
var isNotSel = this.unchecked;
to
var isNotSel = !isSel;
or
var isNotSel = !this.checked;
Checkboxes don't have an unchecked property. They have a boolean checked property (true if checked, false if not). And you've already grabbed that into isSel, so...
Got it working. Thanks to shehary for the click to change modification and to T.J. Crowder for the !this.checked tip. I ended up using two separate scripts but it works :) Thanks again to all!
The one below is for uncheck.
$(document).ready(function() {
$("input[type=checkbox]").change(function() {
var isNotSel = !this.checked;
$.ajax({
url: 'file.php',
type: 'POST',
dataType: 'json',
data: {
id : this.id,
isNotSelected : isNotSel
},
success: function(data) {
alert('updated');
},
error: function() {
alert('error');
}
});
});
});
I have a button which calls a modal box to fade into the screen saying a value posted from the button then fade off, this works fine using jquery, but I also want on the same click for value sent from the button to be posted to a php function, that to run and the modal box to still fade in and out.
I only have this to let my site know what js to use:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
I'm still new so sorry for a rookie question, but will that allow ajax to run, or is it only for jquery?
The current script I'm trying is: (Edited to be correctly formed, based on replies, but now nothing happens at all)
<script>
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.ajax
({
url: 'reservebook.php',
data: "book_id="+book_id,
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
Though with this the modal box doesn't even happen.
The php is, resersebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['jqbookID']))
{
$bookID = $_POST['jqbookID'];
mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
}
?>
and to be thorough, the button is:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>"><button>Reserve Book</button></div>
I'm new to this and I've looked at dozens of other similar questions on here, which is how I got my current script, but it just doesn't work.
Not sure if it matters, but the script with just the modal box that works has to be at the bottom of the html body to work, not sure if for some reason ajax needs to be at the top, but then the modal box wouldn't work, just a thought.
Try this. Edited to the final answer.
button:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
<button class="reserve-button">Reserve Book</button>
</div>
script:
<script>
$('.reserve-button').click(function(){
var book_id = $(this).parent().data('id');
$.ajax
({
url: 'reservebook.php',
data: {"bookID": book_id},
type: 'post',
success: function(result)
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
reservebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['bookID']))
{
$bookID = $_POST['bookID'];
$result = mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
if ($result)
echo "Book #" + $bookId + " has been reserved.";
else
echo "An error message!";
}
?>
PS#1: The change to mysqli is minimal to your code, but strongly recommended.
PS#2: The success on Ajax call doesn't mean the query was successful. Only means that the Ajax transaction went correctly and got a satisfatory response. That means, it sent to the url the correct data, but not always the url did the correct thing.
You have an error in your ajax definitions. It should be:
$.ajax
({
url: 'reserbook.php',
data: "book_id="+book_id,
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
You Ajax is bad formed, you need the sucsses event. With that when you invoke the ajax and it's success it will show the response.
$.ajax
({
url: 'reserbook.php',
data: {"book_id":book_id},
type: 'post',
success: function(data) {
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
}
Edit:
Another important point is data: "book_id="+book_id, that should be data: {"book_id":book_id},
$.ajax
({
url: 'reservebook.php',
data: {
jqbookID : book_id,
},
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
Try this
i want to save data in database by a button click.here is my code,in Firefox it do not work it show empty alert and data do not saved in table.
$("#Save").click(function () {
var price = $("#price").val();
var agent_1_id= $("#agent_1_id").val();
var type = $("#type").val();
$.post("ajax_files/myDeals.php",
{
price: price,
agent_1_id: agent_1_id,type:type
},
function(data) {
alert(data);
});
});
click event fires and this function calls. Here is code on myDeals.php to save in table..
$price = $_REQUEST['price'];
$agent_1_id = $_REQUEST['agent_1_id'];
$type = $_REQUEST['type'];
mysql_query('insert query here');
echo "Saved Successfully ";//this is not alerted?
Try the sample sending the data as an object:
function end_incident() {
$.ajax({
type: "POST",
url: "http://www.example.co.uk/erc/end_incident.php",
data: { name: "Daniel", phone: "01234123456" },
success: function(msg){
alert('Success!');
}
});
};
In a JS file I am performing this function:
$(function() {
$(".button").click(function() {
//get the button's ID (which is equal to its row's report_id)
var emergency = this.id;
var button = this.attributes['name'].value;
var dataString = 'reportid=' + emergency;
alert(dataString);
if (button == "clockin") {
$.ajax({
type: "POST",
url: "/employeetimeclock.php",
data: dataString,
success: function() {
window.location = "/employeetimeclock.php";
}
});
} else if (button == "closereport") {
var r = confirm("Are you sure you want to close this report?\nThis action CANNOT be undone!");
if (r == true) {
$.ajax({
type: "POST",
url: "/closeemergencyreport.php",
data: dataString,
success: function() {
alert("Report Successfully Closed!");
window.location = "/closeemergencyreport.php";
},
error: function() {
alert("An error has occured, the report was not closed");
}
});
} else {
alert("Report was not closed.");
}
}
});
});
For the else if (to closeemergencyreport.php) the code in that php script is as follows:
<?php
require_once("models/config.php");
require_once("models/header.php");
require_once("models/dbconnect.php");
$reportid = $_POST['reportid'];
var_dump($_POST);
$sql = "UPDATE emergency_report SET report_closed = '1' WHERE report_id IN ( $reportid )";
//execute and test if succesful
$result = mysql_query($sql) or die(mysql_error());
if($result){
} else{
}
?>
I've done this same exact thing on 3 other pages and it works flawlessly however this is giving me trouble where on that php script the VAR_DUMP is saying it's returning an empty array. I've been reading and rereading the code for about an hour and a half now so I think i'm burnt out and need to have an outside view. Ive been all over the site and no one has had a solution that worked for me.
I know it's posting because fire bug is showing this on the form's page that the javascript is run on:
http://i.imgur.com/hItdVU1.png (sorry cant post images yet)