PHP INSERT Prepared statement not inserting with ajax - javascript

I am attempting to create an INSERT statement using ajax and the query in a prepared statement form. I have never used AJAX with PDO before, so please excuse any ignorance.
The way this sits, I get the alert(data); error, but the alert pop-up just says "error | ". Is this referring to the javascript being incorrect or the php file? I believe it is the javascript because I am not even getting the php file to show up within my console network tab.
What is wrong within my AJAX?
<form method="POST" id="pdo-add">
<input name="first" id="pdo-add-first" placeholder="First Name">
<input name="last" id="pdo-add-last" placeholder="Last Name">
<input name="product" id="pdo-add-product" placeholder="Product">
<input name="add" type="submit" value="Add">
</form>
AJAX
$(function() {
$("#pdo-add").on("submit", function (event) {
event.preventDefault();
var add_first = $("#pdo-add-first").val();
var add_last = $("#pdo-add-last").val();
var add_product = $("#pdo-add-product").val();
$.ajax({
url: "pdoAddSend.php",
type: "POST",
data: {
"add_first": add_first,
"add_last": add_last,
"add_product": add_product
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to insert product record!");
alert(data);
} else {
//$("#newsletter-form")[0].reset();
$('.announcement_success').html('Product Successfully Added!');
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP
ini_set('display_errors', 1);
error_reporting(E_ALL);
$add_first = $_POST['add_first'];
$add_last = $_POST['add_last'];
$add_product = $_POST['add_product'];
try {
$host = 'localhost';
$name = '';
$user = '';
$password = '';
$dbc = new PDO("mysql:host=$host;dbname=$name", $user, $password);
}catch(PDOException $e) {
echo $e->getMessage();
}
//if(isset($_POST['add'])) {
if(isset($add_first && $add_last && $add_product) {
$stmt = $dbc->prepare("INSERT INTO users (first, last, product) VALUES (:first,:last,:product)");
$stmt->bindParam(':first', $add_first);
$stmt->bindParam(':last', $add_last);
$stmt->bindParam(':product', $add_product);
$stmt->execute();
}

Use if (!empty($add_first) && !empty($add_last) && !empty($add_product)) { to check empty values
Use dataType json to return array from database
Insert Input dynamically in success of ajax
JS
$.ajax({
url: "pdoAddSend.php",
type: "POST",
data: {
"add_first": add_first,
"add_last": add_last,
"add_product": add_product
},
dataType: "json",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var tr = $('<tr/>');
tr.append("<td><input name='id' value=" + data[i].id + " readonly=''></td><td><input name='first' value=" + data[i].first + "></td><td><input name='last' value=" + data[i].last + "></td><td><input name='product' value=" + data[i].product + "></td><td><input name='save' type='submit' value='Save'></td><td><input name='delete' type='submit' value='Delete'></td>");
$("#tableid").append(tr);
}
console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to insert product record!");
alert(data);
} else {
//$("#newsletter-form")[0].reset();
$('.announcement_success').html('Product Successfully Added!');
}
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});

You'd better test these variables first, so that there is no "Undefined index" Notice occured.
And because you don't have a POST variable called add, if(isset($_POST['add'])) always be FALSE.
code here:
if(isset($_POST['add_product']) && isset($_POST['add_last']) && isset($_POST['add_product'])) {
$add_first = $_POST['add_first'];
$add_last = $_POST['add_last'];
$add_product = $_POST['add_product'];
//then your db execute code here
}

Related

how to get value of each indiviual message using javascript and ajax

i am trying to create a favorite button, that when clicked will favorite the message without reload. everything is coded correctly, except i am having trouble figuring out how i will send each message's individual ID to the ajax response.
my ajax:
$(document).on('submit', '.favourite-form', function(e) {
e.preventDefault();
var data = $(this).serialize();
$.ajax({
data: data,
type: "post",
url: "favorite.php?message=529", // here i put 529 as an example,
i need it to be a variable that changes based on which message has been clicked.
success: function(data) {
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown) //gracefully handle any errors in the UI
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
my HTML.
<form class="favourite-form" method="post">
<a class="msg-icon " href="<?php echo "reply?message=" . $row['msgid'] . ""; ?>"></a>
<button type="submit" name="fav" value="<?php echo $row['msgid'] ?>" ></button>
</form>
My php relies on the id of messages to be sent via $_GET METHOD.
my php :
$user_id = $_SESSION['active_user_id'];
extract($_GET);
$id=$_GET['message'];
$q=$db->prepare("SELECT msgid,date,text
FROM messages
WHERE to_id=? and msgid=?");
$q->bindValue(1,$user_id);
$q->bindValue(2,$id);
$q->execute();
$row2=$q->fetch();
$d=$row2['date'];
$fav_questionq=$db->prepare("SELECT *
FROM messages
LEFT JOIN users
ON messages.to_id=users.id
WHERE users.id=? AND messages.msgid=?
");
$fav_questionq->bindValue(1,$user_id);
$fav_questionq->bindValue(2,$id);
$fav_questionq->execute();
$frow=$fav_questionq->fetch();
$fquestion= $frow['text'];
$result = $db->prepare("SELECT * FROM fav_messages
WHERE username=? AND message=?");
$result->bindValue(1,$user_id);
$result->bindValue(2,$id);
$result->execute();
if($result->rowCount()== 1 )
{
$deletequery=$db->prepare("DELETE FROM fav_messages WHERE message=?");
$deletequery->bindValue(1,$id);
$deletequery->execute();
}
else
{
$insertquery = $db->prepare("INSERT INTO fav_messages (username,message,fav_question,fav_date) values(?,?,?,?)");
$insertquery->bindValue(1,$user_id);
$insertquery->bindValue(2,$id);
$insertquery->bindValue(3,$fquestion);
$insertquery->bindValue(4,$d);
$insertquery->execute();
}
?>
how can i send each message id via ajax this way.
You can do:
$(document).on('submit', '.favourite-form', function(e) {
e.preventDefault();
var data = $(this).serialize();
// Here, you will get the individual id before submiting the form
var mssg_id = $(this).find('button[name="fav"]').val();
$.ajax({
data: data,
type: "post",
url: `favorite.php?message=${mssg_id}`, // It will be added to the url ES6 method
success: function(data) {
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
Edit
url: "favourite.php?message="+mssg_id,
What i would do is just to add a hidden input in the form of the view, try this:
<input type="hidden" name="msgid" value="<?php echo $row['msgid' ?>" />

Ajax post with php-mysql is not working properly

I need a ajax call to post data to the database and fetch the data from database and update in live. I have the following codes
HTML Form
<div class="hover_bkgr_fricc">
<span class="helper"></span>
<div>
<div class="popupCloseButton">×</div>
<p>
<form>
<input type="hidden" name="check_num" value="123" />
<p>Please provide more details</p>
<input type="text" name="reason" />
<a id="submit">Mark Reviewed</a>
</form>
</p>
</div>
</div>
<b id="review_result"></b>
<a class="trigger_popup_fricc">
<button> Mark Reviewed</button>
</a>
Javascript Block
$(document).ready(function() {
$(".trigger_popup_fricc").click(function() {
$('.hover_bkgr_fricc').show();
});
$('.popupCloseButton').click(function() {
$('.hover_bkgr_fricc').hide();
});
$('#submit').click(function() {
var check_num = $('input[name=check_num]').val();
var reason = $('input[name=reason]').val();
var form_data =
'check_num=' + check_num +
'&reason=' + reason;
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(html) {
//if process.php returned 1/true (send mail success)
if (html == 1) {
//hide the form
$('.hover_bkgr_fricc').fadeOut('slow');
$('#review_result').html(data);
} else alert('Sorry, unexpected error. Please try again later.');
}
});
});
And the php block
$link = mysqli_connect($HOST, $USER, $PWD, $DB_NAME);
$check_num = $_POST['check_num'];
$reason = mysqli_real_escape_string($link, $_POST['reason']);
$insert = mysqli_query($link, "INSERT INTO `vloer_paylink_reason` (`id`, `check_number`, `reason`) VALUES (DEFAULT, '$check_num', '$reason')");
$update = mysqli_query($link, "UPDATE vloer_paylink SET reviewed = 1 WHERE check_number ='$check_num'");
$get_check_data = mysqli_query($link, "SELECT reviewed FROM vloer_paylink WHERE check_number = '$check_num'");
$check_data = mysqli_fetch_array($get_check_data);
if($check_data['reviewed']==1){
echo "Reviewed done";
}
else {
echo "Not Reviewed done";
}
Data is inserting and updating to the database but after that not returning to html update. Its returning false (Sorry, unexpected error. Please try again later.)
Add .error : function(e){ console.log(e)} to your ajax call, to return the error.
The function will be:
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(data) {
if(data == "Reviewed done"){
// code goes here
}
},
error : function(e) { console.log(e)} // this will print error
});
You are sending Reviewed done or Not Reviewed done in the php code as a response. Change the javascript code like below.
$.ajax({
url: "loweslinkprocess.php",
type: "POST",
data: form_data,
success: function(response) {
//if process.php returned 1/true (send mail success)
if (response === "Reviewed done") {
//hide the form
$(".hover_bkgr_fricc").fadeOut("slow");
$("#review_result").html(response);
} else alert("Sorry, unexpected error. Please try again later.");
},
error: function(error) {
console.log(e);
} // To catch any network errors
});

Getting undefined value while returning json value from controller

Here I want to get all the values which I inserted into the json data in a table before getting submitted but unfortunately am not getting the results I want. So far I have done this. Please have a look.
<script>
$("#getdata").on('click',function () {
var form_data={
agent_name: $('#agent_name').val(),
number: $('#number').val(),
quantity: $('#quantity').val(),
date: $('#date').val(),
commision: $('#commision').val(),
profit: $('#profit').val(),
agent_amount: $('#agent_amount').val(),
user_id: $('#user_id').val(),
type: name_type.val(),
}
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>admin_control/ajax_data',
data: form_data,
dataType:"json", //to parse string into JSON object,
success: function(data){
if(data){
var len = data.length;
alert(len);
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].number && data[i].type){
txt += $('#table').append('<tr><td>data[i].type</td><td>data[i].number</td><td>data[i].quantity</td><td>data[i].amount</td><td><input type="checkbox" class="add_checkbox" name="layout" id="add_checkbox" value="1" checked></td></tr>');
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
});
</script>
Here I want to pass the values of json_data in to the table i had written and how can we pass that here am getting error like undefined.
Here is my controller
public function ajax_data()
{
$array = array("agent_name" => $_POST['agent_name'],"number"=>$_POST['number'],"type"=>$_POST['type'],"quantity"=>$_POST['quantity'],"date"=>$_POST['date'],"commision"=>$_POST['commision'],"profit"=>$_POST['profit'],"agent_amount"=>$_POST['agent_amount'],"user_id"=>$_POST['user_id']);
$data['json'] = $array;
echo json_encode($data);
}
here is my json_data which looks like this
{"json":{"agent_name":"admin","number":"444","type":"super","quantity":"4","date":"2018-02-14 15:16:27","commision":"10.00","profit":"40.00","agent_amount":"0.00","user_id":"1"}}

favorite button ajax

i have problem with my ajax code it didn't work i don't know why.
here is my code:
this php code is in other page that named favourite.php
i have problem with my ajax code it didn't work i don't know why.
here is my code:
this php code is in other page that named favourite.php
$test = $_SESSION['ww'];
$x = $_SESSION['x'];
$SelectQry2 = "select * from favorites where User_Id = ".$test." and User_Post = ".$x."";
$slc = mysqli_query($link , $SelectQry2);
if (mysqli_num_rows($slc)> 0){
$DeleteQry = "DELETE from favorites where User_Post = ".$x."";
$del = mysqli_query($link , $DeleteQry);
}else{
$url = $_SERVER['REQUEST_URI'];
$InsertQry = "insert into favorites";
$InsertQry .="(`User_Id` ,`User_post`, `url`) VALUES";
$InsertQry .=" ('$test' ,'$x', '$url')";
$fav = mysqli_query($link, $InsertQry);
}
$(document).ready(function(e){
e.preventDefault();
$("button").on("click", function(){
var data = $(this).serialize();
$.ajax({
type: "POST",
data: data,
url: "favourite.php",
success: function(data){
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
});
<button>favorite</button>

getting the result of php script called using ajax

im having problem getting the output of php script passing it to html inputs
this is my php script
$stmt->execute();
if ($stmt->rowCount() > 0){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
echo 'Found: ' . $row['doctitle'] . ' ' . $row['doctype'];
}else {
echo "error";
}
and this is my ajax
$.ajax({
type: "POST",
url: "receive.php",
data: ({dtnum: "00001"})
})
.done(function (msg) {
alert("output: " + msg);
})
.fail(function() {
alert( "Posting failed." );
});
and this is my html
<input type="text" name="doctitle"><br>
<input type="text" name="doctype"><br>
im getting the desired output but
what i want to do is pass the output for each row in php script to each designated html input
Change your JS to the following:
$.post("receive.php", {
data: ({dtnum: "00001"})
})
.success(function (msg) {
alert("output: " + msg);
})
.error(function() {
alert( "Posting failed." );
});
Further reading: http://api.jquery.com/jquery.ajax/

Categories