Getting callback results to send to AJAX from php and update table - javascript

I am updating a database table via AJAX and PHP right now, but I want my page to be more responsive and update my table in my file after the data has been inserted into the database table.
I am not sure how to send info from my php file to AJAX and then how to get AJAX to update the table. How can I call back the data from my PHP file in order to make my table interactive?
The table
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
}
</table>
<?php
}
}
AJAX
$(document).ready(function(){
$("#submit_announcement").on("click", function () {
var user_message = $("#announcement_message").val();
//$user = this.value;
$user = $("#approved_id").val();
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: {
"user_id": $user,
//"message": user_message
"user_message": user_message
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to get user info!");
alert(data);
} else {
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP file
$announcement_user_id= $_POST['user_id'];
$announcement_message= $_POST['user_message'];
$test = print_r($_POST, true);
file_put_contents('test.txt', $test);
//var_dump($announcement_user_id);
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('is', $announcement_user_id, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
//echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}

I think to do this, the following steps is what you need:
Write a new php script that gets the items form the database (like in 'the table' script) and echo these items in the table format you want. So when you call this script, it echo's only a table containing the rows.
Remove the dynamic rows part from the 'the table' script.
On success of your ajax request, make a new request to the new php script
Place the output of that script in the html using jQuery (.html(), insertAfter(), appendTo(), or anything like that).
`

Related

cannot receive json in js ajax request from php file

onclick onto a button the js starts an ajax request to the php file. The php file then gets all entries of one table of a database with php-loop. adding them to an array then the php file parse it to a JSON and echos it back to the ajax request. on success the ajax request should output an alert but neither do i get an error nor a alert.
After adding some changes according to the comments. it is now showing the error message 2 error messages randomly:
Fehler: {"readyState":0,"responseText":"","status":0,"statusText":"error"}
Fehler: {"readyState":4,"responseText":"<br />\n<b>Fatal error</b>: Uncaught Error: Cannot use object of type mysqli_result as array in C:\\xampp\\htdocs\\integration\\get.php:32\nStack trace:\n#0 C:\\xampp\\htdocs\\integration\\get.php(13): getLevel1()\n#1 {main}\n thrown in <b>C:\\xampp\\htdocs\\integration\\get.php</b> on line <b>32</b><br />\n","status":200,"statusText":"OK"}
php request (mysqli attributes are left out on purpose):
$func = $_POST['func'];
if ($func == "getLevel1"){
getLevel1();
}
$result = array();
function getLevel1(){
// Create connection
$conn = new mysqli(servername, username, password, dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM capability_level1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$result[] = '<button onclick="capability('. $row["id"] .')">' . $row["name"]. '</button></br>';
}
echo json_encode($result);
} else {
echo json_encode("0 results");
}
$conn->close();
}
js ajax call:
async function getLevel1() {
return $.ajax({
type: "POST",
dataType: "json",
url: "get.php",
data: {
func: "getLevel1"
},
success: function(data) {
alert(JSON.stringify(data));
console.log(data);
},
error: function(data) {
alert("Fehler: "+ JSON.stringify(data));
}
});
}
You need to put the json encoding when you have a complete array to be encoded: after the while:
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$result[] = '<button onclick="capability('. $row["id"] .')">' . $row["name"]. '</button></br>';
}
echo json_encode($result);
} else {
Also note that you probably have to change your data type to Json (and send a json to php) to be able to return it. Actually your Ajax is waiting for text to be returned (based on the data type)
For your further error: it is related to the point that you are fetching the rows from mysql using the wrong function. See this question for more details on how to fix it.

What is wrong with my Javascript and $POST concatenation?

I am using Ajax to add 3 values to my database, and then immediately append them at the bottom of my Table using the following:
**EDIT: Added the full code, and I currently only adding 1 value to the database, leaving the others empty (Adding only Text1)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
$("#Submit").click(function (e) {
e.preventDefault();
if($("#Text1").val()==='')
{
alert("Please enter some text!");
return false;
}
var myData = 'txt1='+ $("#Text1").val(); //build a post data structure
jQuery.ajax({
type: "POST",
url: "ajax.php",
dataType:"text",
data:myData,
success:function(response){
var row_data = "";
row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt1'];?></td><td><?php echo $_POST['txt1'];?></td></tr>";
$("#mytable").append(row_data);
$("#responds").append(response);
$("#Text1").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$('table').html(data);
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
alert(thrownError);
}
});
});
});
</script>
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "test_database";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
echo "Connected successfully";
if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0)
{
$contentToSave = filter_var($_POST["txt1"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$insert_row = $mysqli->query("INSERT INTO test_table(fname) VALUES('".$contentToSave."')");
if($insert_row)
{
$mysqli->close(); //close db connection
}else{
header('ERROR');
exit();
}}
?>
<div class="form_style">
<textarea name="content_txt" id="Text1" cols="45" rows="1"></textarea><br>
<button id="Submit">Add record</button>
</div><br>
<table class="table" id="mytable" style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
//initially filling the table with db data
<?php
$sql = "SELECT fname, lname, age FROM test_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["fname"] . "</td><td>" . $row["lname"] . "</td><td>" . $row["age"] . "</td></tr>";
}
} else {
echo "0 results";
}
$mysqli->close();
?>
</table>
</body>
</html>
The posting does work: txt1, txt2 and txt3 are inserting into the database, but what I see at the bottom of the table is '.$_POST['txt1'].' and so on, instead of the actual POST data
if you want to use php code in javascript then try below ==>
success:function(response){
var row_data = "";
row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt2'];?></td><td><?php echo $_POST['txt3'];?></td></tr>";
The argument you named response in the declaration of the function for success setting of the ajax call (I assume you are using jQuery's $.ajax) contains whatever your Web server sent to you.
In your case if you send AJAX request to the code you provided, that is, if the code you provided is exactly that ajax.php you referenced in the url setting of the jQuery.ajax call, THEN THE response VAR WILL CONTAIN FULL HTML TEXT RENDERED, which is probably absolutely useless to you.
Proper usage of the AJAX would be like this:
$.ajax({
// ...
dataType: 'json', // I can remember incorrectly here. It assumes your PHP backend sends JSON-encoded string.
success: function (data) { // data will be an object already parsed from JSON string sent by server.
var row_data = "";
row_data += "<tr><td>";
row_data += data.txt1;
row_data += "</td><td>";
row_data += data.txt2;
row_data += "</td><td>";
row_data += data.txt3;
row_data += "</td></tr>";
}
});
Move the block of code starting with if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0) to the very beginning of the file and do the following on successful insert to the database:
header("Content-Type: application/json");
echo json_encode(['txt1' => $_POST['txt1'], 'txt2' => #$_POST['txt2'], 'txt3' => #$_POST['txt3']);
die();
This way when handler registered in success will be entered, the response will contain the proper JSON block. You don't need to re-render the whole page on AJAX requests.
You don't need the $("#responds").append(response); block because it'll lie to you due to rendering of the response contents according to HTML rendering rules. Just use the F12 in browser and inspect the server response directly.

I am not getting response from ajax request

I am getting no response from ajax request . i am posting a ajax call to processor.php file and the processor.php file is processing the file and sending the processed file back to javascript i am gerring my result in my console log but it is not showing in the html.
My javascript code is :
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$(".cart-show-product").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$(".cart-show-products").html(response);
}
});
}
and my php is :
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
{
$sql = mysqli_query($conn,
'SELECT * FROM
products_added
where
username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
and
item_added="'.mysqli_real_escape_string($conn, $_POST['item_name']).'"'
);
if(mysqli_num_rows($sql) < 1)
{
mysqli_query($conn,
"INSERT INTO products_added values(
'',
'".mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR'])."',
'".mysqli_real_escape_string($conn, $_POST['item_name'])."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."',
'".mysqli_real_escape_string($conn, '1')."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."'
'".mysqli_real_escape_string($conn, date("d-m-Y"))."')"
);
?>
<table class="cart-show-products">
<thead>
<tr>
<td>Sl.No</td>
<td>Item</td>
<td>Qty</td>
<td>Price</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
$sl_no = 1;
$sql = mysqli_query(
$conn,
'SELECT sum(amount) as grandtotal
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$grandtotal = strip_tags($row['grandtotal']);
$sql = mysqli_query(
$conn,
'SELECT
id,
item_added,
price,
quantity
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$item_id = strip_tags($row['item_id']);
$item_name = strip_tags($row['item_added']);
$item_price = strip_tags($row['price']);
$quantity = strip_tags($row['price']);
?>
<tr class="items_wrap items_wrap<?php echo $item_id; ?>">
<td><?php echo $sl_no++; ?></td>
<td><?php echo $item_name ?></td>
<td><?php echo $quantity ?></td>
<td><?php echo $item_price ?></td>
<td><i class="fa fa-times"></i></td>
</tr>
</tbody>
</table>
<?php
}
If you're getting a response in the console, then the issue must be with your HTML. I think part of the problem is you've created a section on the HTML page wiht a class that is the same as the table the AJAX call is bringing into the page. I would suggest changing the HTML element to us an ID instead. Something like
<div id="products-table"></div>
And then change your JavaScript to
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$("#products-table").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$("#products-table").html(response);
}
});
}
If you stay with the class names you've used, subsequent updates are going to have problems because you'll have 2 elements on the page with the same class. Your script could potentially be confused about which one to change.
If this is your actual code, then you have a syntax error in your PHP file. There are a missing close bracket for:
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
The second problem is, you are not print anything, if this condition has failed.
Note
You do not need to use isset, if you are checking empty. empty will return false, if the variable not set.
You can debug your respons by check NET tab in your web developer tools, or see, what is the response of the AJAX.

Passing a AJAX Variable to PHP

Hi wondering how to send a AJAX variable to php, I thought I had it but apparently not. In my console I get the error "Uncaught TypeError: Illegal invocation line 6"
Im taking it there is something wrong with my code straight after the alert?
(NOTE where it say "jquery" is in replace of $ simply because joomla does not like $ in scripts for some reason)
UPDATED, Pay attention to
Script to click and get rowID
<script language="javascript" type="text/javascript">
jQuery(document).ready(function()
{
jQuery("tr.getRow").click(function()
{
rowID = jQuery(this).find("td.idCell");
alert(jQuery(rowID).text());
//Send the row ID to ajaxupdate.php
jQuery.post("ajaxupdate.php", { submit: "update", ID_ID: rowID})
.done( function(data) {
var results = jQuery.parseJSON(data);
console.log( results );
})
.fail( function() {
console.log("AJAX POST failed.");
});
});
});
</script>
Load first table(the one thats being clicked)
<table border="",th,td, width="500", align="center">
<tr>
<th>TP ID</th> <th>Permit Deny</th> <th>Level</th> <th>Session</th> <th>Information Specialist</th>
</tr>
<?php foreach ($results as $row): ?>
<tr class="getRow">
<td class="idCell"><?php echo $row->TP_ID ?></td>
<td><?php echo $row->Permit_or_Deny ?></td>
<td><?php echo $row->Level ?></td>
<td><?php echo $row->Session ?></td>
<td><?php echo $row->Information_specialist ?></td>
</tr>
<?php endforeach ?>
<br>
</table>
Second table, the one that im trying to get to load
<?php
// In ajaxupdate.php file
if( (isset($_POST['ID_ID'])) || (isset($_POST['submit']))) //im Sure this part is wrong
{
$ID_ID =($_POST['ID_ID']); // pass JS var as a PHP var
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select($db->quoteName(array('CV_ID', 'Classifier', 'Value', 'TP_ID')))
->from($db->quoteName('sessionta'))
->where($db->quoteName('TP_ID') . ' LIKE '. $db->quote('".$ID_ID."'));
$db->setQuery($query);
$results = $db->loadObjectList();
}
?>
3425742,
I rewrote your script and tested it with this JSfiddle. Try it out.
I see that you are using Joomla. Diving into Joomla as a novice is daunting. Within ajaxupdate.php the script is expecting to see a $_POST['submit'] variable. Either remove that requirement or add it like I did below. At the bottom of ajaxupdate.php add this line so that jQuery has something to test.
echo $results ? json_encode("succeeded") : json_encode("failed"); die();
Here is the jQuery ajax code:
//Send the row ID to ajaxupdate.php
$.post("ajaxupdate.php", { submit: "update", TP_ID: rowID})
.done( function(data) {
var results = $.parseJSON(data);
console.log( results );
})
.fail( function() {
console.log("AJAX POST failed.");
});
Edit "ajaxupdate.php" to the correct location of that file. If ajaxupdate.php is in a different directory you have to tell jQuery to look there. For example, if your $.post is in index.php in the root of your webserver and ajaxupdate is in the /js directory change "ajaxupdate.php" to "js/ajaxupdate.php".
you are passing rowID as an object, not as a single text-variable. You'd need
$.post("ajaxupdate.php", ({ TP_ID: rowID.attr('id') }), function( data )
...

How to load data from sql through ajax using php variable?

My HTML/PHP code:
<br/><br/><div id="dialog-modal"></div><br/><br/>
<?php foreach (range(0, 29) as $rs) { ?>
<a data-toggle="modal" href="#" data-href="rsc1<?php echo $rs;?>" class="link">pvz - rsc1<?php echo $rs;?></a><br/>
<?php } ?>
My JavaScript code:
$('.link').on('click',function(e){
var linkValue = $(this).attr('data-href');
$.ajax({
cache: false,
type: 'GET',
//url: 'details.php',
//data: 'i=' + linkValue,
success: function(data) {
$('.ui-dialog-title').html(linkValue)
$('#dialog-modal').html(linkValue).dialog();
}
});
e.preventDefault();
});
The details.php code:
$i = $_GET['i'];
echo $i;
This script opens only new dialog with my sent data from url data-href. All I want to do is to take some data from sql db into that dialog window by variable $i…
I think you want to know how to get data from sql database and show it in your ajax response.
If so then try something like this:
details.php code:
$i = $_GET['i'];//getting your data
$link = mysqli_connect("localhost", "my_user", "my_password", "db name");//set your correct database connection string
//check if connection errors
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//make a query with valid table name
$result = mysqli_query($link, "SELECT * from your_table ");
if($result->num_rows){ //check if any data found
while ($row = mysql_fetch_assoc($query)) {
echo $row['id'];// echo this data
}
}
else{
echo "no data found!";//echo no data found
}
mysqli_close($link); // close mysql connection
In this php page what ever i have echoed it will send as ajax response in your success call back's data. that will display in your modal. I just tried to give you a basic idea. I think it will help you.
Some good resource links: http://www.phptutorialforbeginners.com/2013/01/jquery-ajax-tutorial-and-example-of.html
http://www.cleverweb.nl/php/jquery-ajax-call-tutorial/

Categories