Insert HTML input using ajax. Something wrong with code - php

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

Related

Jquery + Ajax is not working properly, why?

This code will show a counter when there's rows with the status = unread, and it will UPDATE the row to status = read when the user click on the a icon <i class="fas fa-bell"></i>.
The problem is: This is not working propelly, when i click on the <i class="fas fa-bell"></i> it get a delay of 3-9 seconds to update the counter to 0, it update my table instantly, only the counter that get some delay, but sometimes i need to reload the page and click on the icon to update my table, why? What's wrong?
html:
<span class="text-white divCountNT" id="datacount"></span>
script:
<script>
$(document).ready(function(){
$("#datacount").load("select.php");
setInterval(function(){
$("#datacount").load('select.php')
}, 10000);
});
$(document).on('click', '.fa-bell', function (){
$.ajax({
type: "POST",
url: "update.php"
});
});
</script>
select.php:
<?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
}
$status = 'unread';
$sql = $conn->prepare("SELECT * FROM noti WHERE status = :status AND user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
if($countNT >= 1){
echo $countNT;
}
?>
update.php:
<?php
require_once 'db.php';
if(!isset($_SESSION))session_start();
if(isset($_SESSION['user_id'])) {
$user_id = $_SESSION['user_id'];
}
$status = 'read';
$sql = $conn->prepare("UPDATE noti SET status = :status WHERE user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();
echo $countNT;
?>
You dont have a callback function for your ajax call so your table only updates itself with load function. Your ajax call should be something like that :
$.ajax({
type: "POST",
url: "update.php"
}).done(function() {
window.location.reload(true);
});
You can Try with this code It's Working Fine
$.ajax({
type: "POST",
url: "update.php"
success: function(result){
$(body).find("#loadData").html(result);
// $(body).find("#loadData").append(result); //you can also use for append data insted of replace
}
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
check this for use of more methods of AJAX https://www.w3schools.com/jquery/ajax_ajax.asp

Ajax response always goes to success

I have a form where the user has to enter their reservation id and last name. If these two values match in the database then I need to return the corresponding values from the database.
It looks like even if the wrong reservation id and name are put in, it treats it as success. The page reloads and display the foobar.
Here is my code
test06.php
<?php
$conn = mysqli_connect("","","","");
$reservation_id=$_POST['reservation_id'];
$guest_last_name=$_POST['guest_last_name'];
$stmt = $conn->prepare("SELECT reservation_id, guest_last_name, guest_full_name, unit_number, floor, key_sa
FROM reservations2
INNER JOIN guest ON (reservations2.reservation_id=guest.reservation_idg)
INNER JOIN unit USING (unit_id)
WHERE reservation_id=?
AND guest_last_name=?");
$stmt->bind_param("ss", $reservation_id, $guest_last_name);
$stmt->execute();
$stmt->bind_result($reservation_id, $guest_last_name,
$guest_full_name, $unit_number,
$floor, $key_sa);
if ($stmt->errno) {
die("Query failed to execute: " . $stmt->error);
}
if ($stmt->fetch()) {
echo json_encode(array("reservation_id" => $reservation_id,
"guest_last_name" => $guest_last_name,
"guest_full_name" => $guest_full_name,
"unit_number" => $unit_number,
"floor" => $floor,
"key_sa" => $key_sa));
} else {
$error="Not matching record";
echo json_encode($error);
}
$stmt->close();
?>
Inside HTML page
<p id='guest_full_name'></p>
<p id='unit_number'></p>
<p id='floor'></p>
<p id='error'></p>
<script>
function validateReservation(){
var reservation_id = document.getElementById("reservation_id").value;
var guest_last_name = document.getElementById("guest_last_name").value;
$.ajax({
type: 'POST',
url: 'test06.php',
// dataType: 'json',
data: {
'reservation_id': reservation_id,
'guest_last_name' : guest_last_name
},
success: function(json) {
var json = JSON.parse(json);
console.log(json);
$('#guest_full_name').html(json.guest_full_name);
$('#unit_number').html(json.unit_number);
$('#floor').html(json.floor);
$('#key_sa').html(json.key_sa);
},
error: function(err) {
console.log(err);
$("#error").html("Error!");
}
});
}
You have to send the status code. Echoing JSON will just give you a 200 response.
header('Content-Type: application/json');
http_response_code(500);
echo $json;
exit;
http://php.net/manual/en/function.http-response-code.php

Add to database with mysql, ajax and php

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.

Ajax post in oscommerce

I'm trying to update my database on the event of a change in my select box. The php file I'm calling on to process everything, works perfectly. Heres the code for that:
<?php
$productid = $_GET['pID'];
$dropshippingname = $_GET['drop-shipping'];
$dbh = mysql_connect ("sql.website.com", "osc", "oscpassword") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("oscommerce");
$dropshippingid = $_GET['drop-shipping'];
$sqladd = "UPDATE products SET drop_ship_id=" . $dropshippingid . "
WHERE products_id='" . $productid . "'";
$runquery = mysql_query( $sqladd, $dbh );
if(!$runquery) {
echo "Error";
} else {
echo "Success";
}
?>
All I have to do is define the two variables in the url, and my id entry will be updated under the products table, ex: www.website.com/dropship_process.php?pID=755&drop-shipping=16
Here is the jquery function that is calling dropship-process.php:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
$('#drop_shipping').change(function() {
var pid = $.urlParam('pID');
var dropshippingid = $(this).val();
$.ajax({
type: "POST",
url: "dropship_process.php",
data: '{' +
"'pID':" + pid + ','
"'drop-shipping':" dropshippingid + ',' +
'}',
success: function() {
alert("success");
});
}
});
});
I'm thinking that I defined my data wrong some how. This is the first time I've ever used anything other than serialize, so any pointer would be appreciated!
Would it not be enough to define your URl like so:
url: "dropship_process.php?pID="+ pid +"&drop-shipping="+ dropshippingid
Your ajax code is not correct. replace your ajax code by below code:
$.ajax({
type: "POST",
url: "dropship_process.php",
dataType: 'text',
data: {"pID": pid,'drop-shipping': dropshippingid},
success: function(returnData) {
alert("success");
}
});

Using AJAX and JSON to display HTML content from PHP

I am trying to retrieve information from my php file which contains the following code. My code contains the colums Email, FirstName, LastName, and State.
$query = 'SELECT * FROM users WHERE LOWER(Email) = :email';
$stmt = $dbh->prepare($query);
$stmt->bindValue(':email', $email);
$stmt->execute();
if ($stmt->rowCount() == 1) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$firstName = $row['FirstName'];
$lastName = $row['LastName'];
$state = $row['State'];
} echo json_encode($row);
My Ajax code is:
$.ajax({
datatype: 'json',
type: "POST",
url: 'json-data.php',
success: function(data) {
//called when successful
$('#firstname').append(data.FirstName);
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
When I type $('#firstname').append(data);, it shows me the following output:
{"FirstName":"Foo","LastName":"Bar","State":"Florida","Email":"foo#bar.com"}
How do I make it so I can get only the first name and append it to a div?
try with:
var obj = jQuery.parseJSON(data);
$('#firstname').append(OBJ.FirstName);

Categories