Using Jquery Ajax to Retrieve Data from MySQL

Using Jquery Ajax to retrieve data from Mysql

For retrieving data using Ajax + jQuery, you should write the following code:

 <html>
<script type="text/javascript" src="jquery-1.3.2.js"> </script>

<script type="text/javascript">

$(document).ready(function() {

$("#display").click(function() {

$.ajax({ //create an ajax request to display.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}

});
});
});

</script>

<body>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Display All Data" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center">

</div>
</body>
</html>

For mysqli connection, write this:

<?php 
$con=mysqli_connect("localhost","root","");

For displaying the data from database, you should write this :

<?php
include("connection.php");
mysqli_select_db("samples",$con);
$result=mysqli_query("select * from student",$con);

echo "<table border='1' >
<tr>
<td align=center> <b>Roll No</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Address</b></td>
<td align=center><b>Stream</b></td></td>
<td align=center><b>Status</b></td>";

while($data = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td align=center>$data[0]</td>";
echo "<td align=center>$data[1]</td>";
echo "<td align=center>$data[2]</td>";
echo "<td align=center>$data[3]</td>";
echo "<td align=center>$data[4]</td>";
echo "</tr>";
}
echo "</table>";
?>

Using JQuery AJAX and php to fetch data to a mysql database

I think you should use PDO, to connect to the database instead of the old driver, which PHP no longer supports. with PDO you can use prepared statements to prevent sql injections

PDO tutorial

filter_var() Constants

dbh.php


$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = 'db';

try {

$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
exit($e->getMessage());
}

?>

serve.php

<?php

include("dbh.php");
if (isset($_POST['done'])) {

$q_no = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$total_no = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);

try {

$stmt = $db->prepare("INSERT INTO variables(id, names) VALUES(?, ?)");
$stmt->execute(array($q_no, $total_no));

echo json_encode(["message" => "success"]); // sends success response to front-end

} catch (\Exception $e) {
echo json_encode(["message" => $e->getMessage() ]); // sends error response to front-end
}


}
?>

in your ajax check if the data was inserted or not.

$("#q_answer1").click(function() {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();

$.ajax({
url: "file.php",
type: "post",
async: false,
data: {
"done": 1,
"username": q_no,
"comment": main_no

},
success: function(data) {

const respose = JSON.parse(data);

if (respose.message === 'success') { // data was inserted

$("#q_no").val('');
$("#total_no").val('');

}else {
alert(respose.message); // some error has occured
}
}
});
});

Get data from mysql database using php and jquery ajax

There are two syntax errors in your ajax call:

$(document).ready(function(){
function showRoom(){
$.ajax({
type:"POST",
url:"process.php",
data:{action:"showroom"},
success:function(data){
$("#content").html(data);
}
});
}
showRoom();
});

Keep in mind that jQuery's ajax expects an object as parameter. Inside an object the syntax is

{ key : value }

You had type="POST" which is correct in declarative syntax, but incorrect when defining an object key.

Second, the data property of the aforementioned object should be an object too. So instead of action=showroom it should be

{action:"showroom"}

Retrieving Data with Jquery, AJAX, and PHP from a MySQL Database

It's nothing different. Just do your stuff for fetching data in ajax.php as usually we do. and send response in your container on page.

like explained here :

http://openenergymonitor.org/emon/node/107

http://www.electrictoolbox.com/json-data-jquery-php-mysql/

PHP AJAX: retrieve data from mysql and show them in form

There are many issues in the logic,

$result = $mysqli->prepare("SELECT * FROM posting WHERE title LIKE ?");
$result ->bind_param("s", $search);
$result->execute();
$result->store_result();
//$result->bind_result($title);
//$data[]=$result;

echo json_encode($data);

You will get multiple columns from your SELECT statement and you're binding just one column in your bind_result($title) that will throw a warning, and also you're not fetching your data which will actually extract the data from result set and bind it to your variable.

Second, if you want to populate the field you would expect one result set right?(judging from your javascript) your query with LIKE clause might probably return more than one result, you will have to modify your query so that you can get a unique result.

Now lastly, what you're trying to achieve in your PHP code can more easily done with PDO rather than mysqli, one of the reasons being, you can easily fetch the result set with fetch_all function and json_encode it directly, mysqli has fetch_all too but I believe that is only compatible with the latest versions.

If you want to keep using MySQLI the solution would be this,

$result->bind_result($title, $total, ...); //bind all your columns here
$data = [];

while($stmt->fetch()){
$data['title'] = $title;
.
.
.
//fetch all the columns you need likewise.
}

echo json_encode($data);

I'd still suggest that you should migrate to PDO, which will help you to do all this stuff with much more ease, read more about PDO here: http://php.net/manual/en/class.pdostatement.php



Related Topics



Leave a reply



Submit