getting the result of php script called using ajax - javascript

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/

Related

Extract text from DIV on HTML jQuery POST response

I'm coding a website and decided to perform a jQuery POST to call a PHP function, everything worked but instead of only a DIV as a response I got a whole HTML page. My doubt is: how can I extract the text from the DIV I encapsulated it with the id "response"?
Here is the JS and PHP code:
const showModal = (id) => {
$.post("<?php echo SITE_URL;?>/index.php/crewdesk/getFlightInfo/"+id, (data) => {
console.log(data)
});
$("#modalTitle").text(id);
$("#bookModal").modal("show")
}
public static function getFlightInfo($id)
{
$condition = " AND s.id = '$id'";
echo "<div id='response'>";
echo json_encode(CrewDeskData::getFlights(self::$stats['location'], "$condition"));
echo "</div>";
}
And here is the console log of the response->
Change you jQuery code to this below.
Using $.ajax which is similar to $.post
If you just want to return json data from your PHP file just use dataType: 'json' in your $.ajax I am set to receive html as your echo a div only.
const showModal = (id) => {
$.ajax({
type: 'POST',
url: '<?php echo SITE_URL;?>/index.php/crewdesk/getFlightInfo/' + id,
dataType: 'html',
success: function(data) {
console.log(data)
$("#modalTitle").text(id);
$("#bookModal").modal("show")
}
},
error: function(xhr, textStatus, errorThrown) {
//handle error here
}
)
}
}
Change your PHP code to this below
public static function getFlightInfo($id){
$condition = " AND s.id = '$id'";
echo "<div id='response'>".json_encode(CrewDeskData::getFlights(self::$stats['location'],"$condition"))."</div>";
}

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
});

sending a extra parameter in .submit

hello I have a function where I am using ajax to try to do get some value and then submit a php form which looks like this.
/* form-horizontal */
$attributes = array("class" => "form-horizontal", "id" => "register_form");
if (isset($_SESSION['login']))
{
if ($_SESSION['login'] == 'DoBusinessPerformed' || $_SESSION['login'] == 'NormalPerformed') {
echo form_open('myprofile/ManageProcessNew/'.$pathName, $attributes);
} else {
echo form_open('myprofile/RegisterProcessNew/'.$pathName, $attributes);
}
}
else
{
echo form_open('myprofile/RegisterProcessNew/'.$pathName, $attributes);
}
As you can see i have a .$pathname which is the parameter which contains the value 'borrow' and here is the ajax function which I am calling to send this form.
self.checkMangoPayId = function(){
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/checkMangoPayID/' + auth,
contentType: 'application/json; charset=utf-8',
})
.done(function(data) {
console.log(data);
if(data.mangopay_id == null){
alert("going to save page for mango id");
// here is where I submit the form
$("#register_form").submit();
}else{
self.mangoPayIdCheck(true);
self.showModalAddId();
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error code thrown: " + errorThrown);
})
.always(function(data){
});
}
what I want to do is in the .submit function add a way to change the value of .$path name and put borrowed instead of borrow.
I tried a lot of ways like .submit(borrowed), but non of those ways work, so basically all I want to send a different value inside pathname to my controller which receives this parameter.
just before your submit you can add a attribute like this
$("#register_form").attr('action',BASEURL + "index.php/bla/bla/borrowed");
and then when you submit it will attach it at the back as parameter.

PHP INSERT Prepared statement not inserting with ajax

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
}

Categories