PHP : get response fro $.ajax call - javascript

I want to fetch data based on ajax call
this is my code to get the id
<h3> <a class='click' data-id='<?=$rows["id"];?>'><?=$rows['title'];?></a</h3>
This is my jquery code
$(document).ready(function() {
$(".click").on('click',function() {
var id= $(this).attr("data-id");
alert(id);
$.ajax({
type: "POST",
url: "getevents.php",
data: {id:id},
dataType: "html",
success: function(response){
console.log(response);
}
});
})})
</script>
getevents.php
<?
if(isset($_POST['id'])){
echo $_POST['id'] ;
}
$singleevent = mysqli_query($link, 'SELECT * FROM `events` WHERE `id`=."'$id'" ') or die('error');
while($row= mysqli_fetch_array($link , $singleevent)){
print_r($row);
}
?>
$_POST['id']; gets printed in console but not the response . i tried echo and print_r() both in while loop but nothing is in response .
Please help me with this

There are a couple of problems in your PHP. First, you forget to reassign the variable, then you improperly concatenate the variable in your query. You also probably do not want the query to run if the id is not set, so you need to re-arrange your brackets:
<?
if(isset($_POST['id'])){
$id = $_POST['id'] ; // set the variable for the query
$singleevent = mysqli_query($link, "SELECT * FROM `events` WHERE `id` = $id") or die('error');
$row= mysqli_fetch_array($singleevent, MYSQLI_ASSOC);
print_r($row);
}
?>
I am assuming that your $link is a good and correct connection to your database. You also do not need a while loop, assuming that the id selects a single row of data. You also need to fetch the array properly, using the result of the query and MYSQLI_ASSOC like this:
$row= mysqli_fetch_array($singleevent, MYSQLI_ASSOC);
Which I have included in the code block.
NOTE
If PHP short tags are not enabled you will need to change <? to <?php
WARNING
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!

Related

Update MYSQL Table On Div Click using Ajax - No Page Refresh?

I have a MYSQL Table called users.
I also have a column called online_status.
On my page I want a user to be able to toggle their status as 'Online' or 'Offline' and have this updated in the database when they click on the div using Ajax, without refreshing the page.
Here's my PHP/HTML code:
<?php if ($profile['online_status'] == "Online") {
$status = "Offline";
}else{
$status = "Online";
} ?>
<div id="one"><li class="far fa-circle" onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"/></li><? echo 'Show as ' .$status; ?></div>
My Ajax:
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "update_status.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
update_status.php
<?php
$var = #$_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = 1";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//added for testing
echo 'var = '.$var;
?>
I am currently getting no alert, nothing is being updated in my database either. Please can someone help me improve/fix the code to get it to work? Also, if there's a way of eradicating the need for the update_status.php file and have the ajax self post then this would be preferred.
Thank you in advance.
From what i see, the reason why no alert pops up nor nothing gets updated is because of the onclick() on button you have. Add quotes around the parameter to the update function. As you have it, javascript sees the parameter as a javascript variable as $profile['online_status']; is a string.
If you had debugged your code, you should see an error pointing towards the onclick() line
Change this
onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"
To
onClick="UpdateRecord('<? echo $profile['online_status']; ?>');"
Also you are hardcoding the where clause in your update statement. You should be using the $_POST['id'] variable via prepared statements
pass data to PHP file
data: { id: id },
add a database connection to your PHP file
<?php
$var = $_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = '$var'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
?>
If you still see any errors then press F12 and go to network tab, then click on that div, network tab will record your ajax file returns, you can check there on by selecting your php file's response, hope it helps

ajax get empty array from json_encode()

So I have this php class where i have a function that get users from a PSQL database but the AJAX keep loging empty array in the console:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
return $result;
}
I use a phphandler file to call the function from ajax
:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
echo json_encode($module -> getUsers());
?>
and finaly there is the AJAX call
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
dataType: 'json',
success: function(response) { console.log(response); }
});
});
});
The problem is that js keep showing empty array in the console.
The json_encode works fine as json_last_error = 0.
I Tried replacing the return of my getUsers() function by
echo json_encode($result);
to test if the function manage to encode my array and it did show up like a JSON on the page so this is not a encoding of my array problem. Still when AJAX get the result of the json_encode function it display an empty array.
Thanks for any help !
Necro.
Solution 1
You have to set content type of header in your php file before echo
header('Content-type: application/json');
Solution 2
change dataType in your ajax code to html
or remove it to return default dataType (default: Intelligent Guess (xml, json, script, or html))
and then convert returned string to json using javascript JSON.parse() method .
It turned ou the problem was not json_encode at all, it was a problem with my static DB class wich I was includong twice with the AJAX call.
Thanks anyway for the support

How can I send javascript values to PHP script?

this is my php code that creates a table using the results of a mysql query:
echo "<table id='table' class='selectQuery'>
while($row = mysqli_fetch_array($slctQuery)) {
// ; echo $row['id']; echo
echo "<tr class='someClass' idNumber="; echo $row['id']; echo ">
<td>";
echo $row['fname'];
echo "</td>
<td>";
echo $row['lname'];
echo "</td>;
</tr>";
}
echo "</table>";
and this part is my jquery code for changing style on click on table row:
<script>
$(document).ready(function(){
$("#table tr").click(function(){
$('.someClass').removeClass('selected');
$(this).addClass('selected');
idNum = $(this).attr('idNumber');
});
$("#table tr").click(function(){
$("#DelEdtQuestion").addClass('selected1');
});
});
</script>
and this part is for style:
<style>
tr.selected {
background-color: brown !important;
color: #FFF;
}
</style>
and this is my php code for button
if(#$_POST['Search']){
/// what should I do?
}
So, now I want have my idNum value when my search button in form was clicked.
thanks for attentions
You can use ajax. If you have a form with id="myform" and (example) input fields: firstname, lastname, username and password, the following script should send data to the php:
$(document).ready(function(){
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'ajaxfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res);
alert(res);
});
});
The ajaxfile.php can be something like that:
<?php
$firstname = mysql_real_escape_string($_POST["firstname"]);
$lastname = mysql_real_escape_string($_POST["lastname"]);
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
//here you have the variables ready to do anything you want with them...
//for example insert them in mysql database:
$ins = "INSERT INTO users (firstname, lastname, username, password ) VALUES ( '$firstname', '$lastname', '$username', '$password' )";
if(mysql_query($ins)){echo "SUCCESS";}else{echo "FAILURE";}
?>
Another example, similar to yours, is to take the row id from your table, pass it to ajax, have ajax (for example) make a query to the database and return the results:
// your script, modified for ajax:
$(document).ready(function(){
$("#table tr").click(function(){
$('.someClass').removeClass('selected');
$(this).addClass('selected');
var idNum = $(this).attr('idNumber'); //use "var" to -initially- set the variable
$.ajax({
type: 'POST',
url: 'ajaxfile.php',
data: 'id='+idNum
}).done(function(res){
var res = $.trim(res);
alert(res);
});
});
$("#table tr").click(function(){
$("#DelEdtQuestion").addClass('selected1');
});
});
Modified ajaxfile.php to suit the above example:
<?php
$id = mysql_real_escape_string($_POST["id"]);
//query database to get results:
$result = "SELECT * FROM `users` WHERE `id` = '$id' LIMIT 1";
$row = mysql_fetch_assoc($result);
echo "Username: ".$row["username"]."Password: ".$row["password"]."Firstname: ".$row["firstname"]."Lastname: ".$row["lastname"].
?>
Since your question was rather ambigious, I put more effort to give you an idea about the basics of ajax so that you work out your own solution, rather than to suggest a potential solution -that at the end could not be what you were looking for...
And since we are talking about ajax basics, it is a good practice to secure your ajax files since they are accessible from any browser:
in the very beginning of any ajax file, right below the "?php" tag, you can add these lines below, to protect the file from being accessed by browser -but remain accessible to ajax calls:
//protect the file from un-authorized access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}
Hope that helps you and others. T.
UPDATE:
It is ALWAYS a good practice to keep your php and javascript files separately... In the above examples there are ideally 3 files involved: the main php file, the scripts file and the ajax-php file.
So -preferably after the "body" tag of your "main" php file- you should include the scripts-file (after the jquery ofcourse!). Like that:
<!-- jQuery v.1.11.3-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- include scripts file -->
<?php include("scripts.php"); ?>
(notice that for jquery I use the regular "script" tags but for the scripts file I just do a "php include").
As you see above, the javascript file has also ".php" extension (not ".js"). This is a "trick" I like to do because it gives me the ability to execute php code within the js file. Of course, all javascript code in that file is included between "script" tags.
example of a hypothetical "scripts.php":
<script>
// I create a js variable that takes value from php
var phpDate = '<?php date("Y-m-d"); ?>';
alert(phpDate);
//or pass the contents of another php variable in your app to javascript:
var myPhpVar = '<?php echo $my_php_var; ?>';
//or put a php SESSION to a js variable:
var mySess = '<?php echo $_SESSION["my_session"]; ?>';
</script>
The above comes quite handy sometimes when you want to pass to javascript php variables that already exist in your application.
It is a very long answer (more like a tutorial!)... But now should be quite clear to you how to pass values not only from js to php but also vice versa!!!

How do I get JSON from URL and set its value to texfield?

I have some URL mysite.com/json.php, which returns something like this : [{"invoice_number":"INV#20101"}]
on another page I have a <input type="hidden" id="myinvoice" />
I just wanted to set that invoice_number value to this hidden field withJQuery. How can I do this?
on JSON page I have converted JSON with this code :
<?php
$return_arr = array();
$fetch = mysql_query("SELECT invoice_number FROM db_stocks ORDER BY stock_id DESC LIMIT 1 ");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['invoice_number'] = $row['invoice_number'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
You can use jQuery.ajax() to get the returned array then set the value.
$.ajax({
url: "json.php",
success: function(data) {
$("#myinvoice").val(data[0].invoice_number);
}
});
You can use the following jquery:
$.get('mysite.com/json.php', function(data){
$('#myinvoice').val(data[0].invoice_number);
} 'json');
Also please don't use mysql but use pdo or mysqli instead, see why-shouldnt-i-use-mysql-functions-in-php for more information about this.

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

Categories