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

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' ?>" />

Related

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>

I want to post data from HTML file to php and how to redirect to the php and show data in php

I would like to post data from the html file to the php file and how to redirect to the php file and see the data in the console page.
I am a beginner and not very good in ajax. Please check below code I have used.
I want to send json data to the php file. My question is how to post json data to php and see the data in php file. I got error which states undefined index postcountry.
My another question is how to solve the error. Please help me correct the mistake.
Thank you.
In ajax.html
<html>
<head>
<title> NEW AJAX</title>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-
1.11.3.min.js"></script>
</head>
<body>
<h2>Show Data in PHP</h2>
<br />
<br />
<form>
<input type="hidden" id="country" value="singapore" readonly>
<input type="hidden" id="time" value="141253" readonly>
<input type="button" value="submit me" onlcick="showData();">
</form>
<div id="resulte"></div>
<h3>Look at the console. Click Ctrl + Shift + J to VIEW THE CONSOLE PAGE.
</H3>
<script type="text/javascript">
var country = document.getElementById("country");
var time = document.getElementById("time");
function showData() {
$.ajax({
type: "POST",
dataType: "json",
url: "abdullahpass.php",
//async: false,
data: JSON.stringfy({postcountry: country,
posttime: time}),
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or
Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p>
<p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p>
<div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
}
</script>
</body>
</html>
In another file
<?php
echo json_decode($_POST['posttime']);
echo json_decode($_POST['postcountry']);
echo var_dump($_POST);
?>
//In your ajax call data no need to strigyfy data.
<script type="text/javascript">
var country = document.getElementById("country");
var time = document.getElementById("time");
function showData() {
$.ajax({
type: "POST",
dataType: "json",
url: "abdullahpass.php",
//async: false,
data: {postcountry: country,posttime: time},
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or
Ctrl+Shift+I, Console tab) for more information!');
$('#resulte').html('<p>Status Code: '+jqXHR.status+'</p>
<p>ErrorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p>
<div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
},
});
}
</script>
I got error which states undefined index postcountry is not error its a warning, Using isSet function you can overcome the same and $_POST['posttime'] and $_POST['postcountry'] are values. You should to use json_encode on array only.
<?php
echo (isSet($_POST['posttime']) && $_POST['posttime']) ? $_POST['posttime'] : 'No value for posttime';
echo (isSet($_POST['postcountry']) && $_POST['postcountry']) ? $_POST['postcountry'] : 'No value for postcountry';
//this will print total post data with type
echo var_dump($_POST);
?>

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
}

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/

Ajax result show undefined

I want to ues ajax polling for show user update by followers like facebook.
So I collect this code and apply in my page, Which append only 'undefined' one after one.
What is my wrong here in my code please.
At below I give my full polling script and related file
my Table name: updateside
id - work_id - parent_id - from_id - to_id - sub - detail - img - created
..........................................................................
AI - work_id, parent_id etc. all data submit by user post form
My JavaScript
function waitForMsg(){
$.ajax({
type: "GET",
url: "upsidenew.php",
async: true,
cache: false,
timeout:50000,
success: function(data){
if(data) {
$("#updatetime").append('<div class="upbox1">' + data.detail + '</div>');
}
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
}
$(document).ready(function () {
waitForMsg();
});
upsidenew.php
$parent = //collect from other query
date_default_timezone_set('Asia/Dhaka');
$timestamp = date("M j, y; g:i a", time() - 2592000);
$u = mysqli_query($dbh,"SELECT * FROM updateside WHERE `parent_id`='".$parent."' AND `created` > '".$timestamp."' ORDER BY created DESC") or die(mysqli_error($dbh));
$response = array();
while ($row = mysqli_fetch_array($u)) {
$response['from_id'] = $row['from_id'];
$response['parent_id'] = $row['parent_id'];
$response['to_id'] = $row['to_id'];
$response['sub'] = $row['sub'];
$response['detail'] = $row['detail'];
$response['img'] = $row['img'];
$response['time'] = $row['created'];
?><script><?php echo '(Content-Type: application/json)';?></script><?php
echo json_encode($response);
exit;
}
Add your ajax request dataType as "dataType: 'json'"
$.ajax({
type: "GET",
url: "upsidenew.php",
async: true,
cache: false,
timeout:50000,
dataType: 'json'
success: function(data){
if(data) {
$("#updatetime").append('<div class="upbox1">' + data.detail + '</div>');
}
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
if you don't set the datatype of your ajax call explicity to json you need to parse the result with:
jsondata = $.parseJSON(data);
alert(jsondata.detail);
as shown in
http://api.jquery.com/jquery.ajax/
If you're returning JSON, you shouldn't output anything other than echo json_encode($response). This line:
?><script><?php echo '(Content-Type: application/json)';?></script><?php
should be:
header('Content-type: application/json');

Categories