How to retrieve specific data from database using ajax - javascript

this is my ajax code to retrieve all data from a php file:
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "read.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<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>
And this is part of my php file witch retrieves data from database and stores it into variables :
<?php
while($row = mysqli_fetch_assoc($result)){
$user_id = $row["user_id"]
$user_name = $row["user_name"]
$user_text = $row["user_text"]
}
?>
If I echo the above variables then they will be shown in my html page whitch contains ajax codes but I want to get each variable with ajax and do some operations on them and then show them in my html page
There is Simple html dom in php to get one page's html elements is there anything like php simple html dom for ajax? if not then how is it possible to do the things I said?
I'll be appreciate that if someone can help me with this:)

Server side
$array = array();
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
array_push(//what you need);
}
echo json_encode($array);
And on the client side
success: function(response){
data = $.parseJSON(JSON.stringify(returnedData));
}
Note that JSON.stringify is not needed however I like it
data is now an object and you can access its properties with data.propertyname

You have to return a JSON object with the variables. Make an array outside the while loop, and then on each while loop do array_push to the main array. After the loop echo the array through json_encode and then decode it on the ajax end.

Related

Dynamic Array in HTML Datalist

I want to dynamically refresh the php code in this datalist, without reloading the whole page.
<form id="form1" action="1.5-unterseite-nach-Eingabe.php" method="post" enctype="multipart/form-data">
<tr>
<td>Lecture auswählen: </td>
<td><input list="files" name="unterlage"></td>
</tr>
<datalist id="files">
<?php
$files = array_diff( scandir("/srv/www/htdocs/share/"), array(".", "..") );
foreach ($files as $option) {
echo '<option value=\''.$option.'\'>';
}
?>
</datalist>
I hope you can help me out.
You can write your html form in a "index.html" file. And uses javascript intervals request the data which provide by PHP in data.php. The pseudo-code will be something like this:
// index.html
<html>
<form id="form1" action="1.5-unterseite-nach-Eingabe.php" method="post" enctype="multipart/form-data">
<tr><td>Lecture auswählen: </td><td><input list="files" name="unterlage"></td></tr>
<datalist id="files">
</datalist>
</form>
<script>
window.setInterval(function(){
function request_data(){
$.ajax({
url: 'data.php',
method: "post",
success: function (data) {
// Do something here
$("#files").html(data);
}
})
}
},2000); // 2 secends request a time
</scirpt
</html>
// data.php
<?php
$files = array_diff( scandir("/srv/www/htdocs/share/"), array(".", "..") );
return json_encode($files);
?>
Not entirely sure what your end goal is.
But one course of action is to set up an AJAX GET method that calls that PHP snippet in it's own file. Grab all the returning data and insert it into the page using JS.
Start learning JS because that's the only way you're going to be able to pull off dynamic content without page reloads.
To fetch the data using AJAX, use something similar:
<script>
$(document).ready(function(){
$.ajax({
url: 'URL_TO_PHP_FILE/scanFiles.php',
dataType: 'text',
success: function(data)
{
$("#files").html(data);
}
});
});
</script>
Now move your PHP snippet to it's own file simply as such:
$files = array_diff( scandir("/srv/www/htdocs/share/"), array(".", "..") );
foreach ($files as $option) {
echo '<option value=\''.$option.'\'>';
}
?>
Provided your only echos are what you would like to receive in your AJAX call, you should be good.
Also make sure you have the jQuery library linked to your page so that you can use AJAX. Take a look into jQuery a bit more. It'll make your life a lot easier.
You will also want a method to execute your JS code either every few seconds or a trigger based on previous user interaction.

Ajax doesn't show PHP data

I'm in a little trouble here. I'm trying to use ajax to get data from PHP server, that it gets from Mysql database; and then display into a specific html tag place. But, for some reason, nothing is showed off to html. I tested the PHP page and it works correctly. The point is, when ajax should get the data and display, it seems that there's nothing at database.
This is my html target :
<div class="container">
<table>
<thead>
<tr>
<th>Título</th>
<th>Curiosidade</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
This is my Ajax Script:
function readData() {
$.ajax({
type: "POST",
dataType: "html",
url: 'http://localhost/Gravidapp/php/read.php',
success: function(data){
$('tbody').html(data);
},
error: function(xhr,desc,err){
ajax.error(xhr);
ajax.error(desc, err);
}
});
};
This is my PHP file:
<?php
require("bdconn.php");
$pdo = new db();
$pdo->mysql->beginTransaction();
$rs = $pdo->mysql->query("select * from timeline");
$rs->execute();
while($row = $rs->fetch()){
?>
<tr>
<td><?php echo $row['titulocuriosidade']?></td>
<td><?php echo $row['curiosidade']?></td>
</tr>
<?php
}
?>
Any suggests?
Thanks in advance
If the php response doesn't have the data type on headers ajax response could send an error.
Try setting dataType="text html" on your ajax request this will try to convert the response from text to html
also try to print errors on console to show whats is going wrong.
error: function(xhr,desc,err){
console.log(desc);
}
see dataType on: JQuery ajax
What's happening is: when you make an ajax call you must have a return of some data in the php called. When you need to include html you can call a method that return to you a template already ready to be included in the current html page. You can have for example an index.html that will be included when you load your page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="data-ajax"></div>
<script type="text/javascript" src="node_modules/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="js/timeline.js"></script>
</body>
</html>
In you js timeline.js you will include in the current html page what has returned in the data of the ajax:
$.ajax({
type: "GET",
dataType: "html",
url: 'timeline.php',
success: function (data) {
$('#data-ajax').html(data);
}
});
You will have also your php returning the html to be used in the ajax:
<?php
getTimelineData();
function getTimelineData() {
//here you retrieve data from database
$results = array(0 => 'first-result', 2 => 'second-result', 3 => 'third-result');
include_once 'timeline-data.php';
}
And finally your timeline-data.php file:
Here is your data!
<?php foreach($results as $result) { ?>
<?= $result ?>
<?php } ?>

How to do a AJAX click post on every PHP foreach result

I have read multiple sorts of answers but none works.
what i try to do is to make every result from a PHP foreach loop clickable and then send that data with AJAX to a other PHP file, the problem now is that whatever i do, only the last foreach result always get send and not the result that i clicked on? (without Database)
the loop exist in a function functions.php:
public function getForeachResult ()
{
$response = $this->GetObject($parameters);
include 'template.php';
}
the template that handles the result template.php:
<?php
foreach ($response->Result->List as $key =>$value) {
?><table id="mytable"><tr>
<th>ID</th>
<th>Date</th>
<th>firstname</th>
<th>lastname</th>
</tr>
<?php foreach ($value as $key=>$value) {?>
<tr class="myrow">
<td><?php echo $value->ID; ?></td>
<td><?php echo date("d-m-Y", strtotime($value->Time)); ?></td>
<td><?php echo $value->FullName; ?></td>
<td><?php echo $value->LastName; ?></td>
</tr>
<?php } ?>
</table><br />
<?php } ?>
In template.php the AJAX script is called at the bottom:
<script>
$('.myrow').click(function() {
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value: <?php echo $value->ID ?>}
}).done(function( msg ) {
$('.Data').html(msg);
});
});
In post.php where the dat is send i only get the last result of the foreach loop
post.php:
if($_POST['action'] == 'goTo') {
var_dump ($_POST);
}
so how can i make sure AJAX sends the data that i clicked on?
Try:
`<td class="id"><?php echo $value->ID; ?></td>
<script>
$('.myrow').click(function() {
var id = $(this).find('.id').text();
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value: $(this).find(td:first).text().trim()}
}).done(function( msg ) {
$('.Data').html(msg);
});
});`
I think your php expression in the data field just hold the last id because you looped in your html but in your ajaxcall your are already in the end of the loop.
Edit: took the comment
So, to explain the why, i think you mess up a little things in your head and that causes a confusion. Your PHP file does send nothing in Ajax to another PHP file. Your PHP file builds an HTML page, and the Javascript in this page sends data in Ajax.
Keep that in mind, that in PHP you build a future JS code that is executed later. If dynamic variables have to be retreived during the Ajax call or for its data to send, it will be JS that will do it, not PHP.
So like others answers suggest, you have to retreive the id in JS, not PHP.
Only you need to do is get the clicked id just like this
$('.myrow').click(function() {
var id = $(this).children("td.first").text();
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value: id}
}).done(function( msg ) {
$('.Data').html(msg);
});
It will work fine no need to change your table html
You need use traverse to find the each row value dynamically on click like this
var clicked_row_id = $(this).find('td:first').text().trim();
Data should be send like this
data: { action: 'goTo', value: clicked_row_id }
Update 1 :
$('.myrow').click(function() {
var clicked_row_id = $(this).find('td:first').text().trim();
$.ajax({
type: "POST",
cache: false,
url: "post.php",
data: { action: 'goTo', value:clicked_row_id }
}).done(function( msg ) {
$('.Data').html(msg);
});
});
At the end of foreach loop you will only have last iteration value only in $value->ID; . so when you echo it in js. so it will echo only last value .

Correct method of sending a variable from a html form to a php function via ajax

I'm coding a voting system for multiple uploads; each uploaded image is in a foreach statement with a form attached to each, with three buttons to vote up, down or none, each associated with an INT in my mysql database.
I got it to work by submitting the form data straight to the PHP function that 'UPDATE's the database. To avoid a page refresh, I attach ajax. I got the ajax to send the two variables needed for the PHP function to update the correct "image" row and INT in the db.
Question: The ajax function works, but the PHP function doesn't seem to update.
SUSPECTED PROBLEM: I'm pretty sure it's the way I'm defining the variables in ajax that I want to pass, I was trying to grab the ID of the "image" it's handling, but I don't know how to translate this data to the PHP function so that it UPDATE's correctly.
Here's the form, javascript, and php:
// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this
// hidden input, to send unique ID
<input type="hidden" name ="input_id"
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answer_L" id="<?php echo $row['id']; ?>"
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
type: 'POST',
url: 'feed.php', //name of this file
data:input_id,post_answer1,
cache: false,
success: function(result)
{
alert ('It worked congrats');
}
});
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
$current_id = $_POST['input_id'];
$vote_1 = "UPDATE decision_post set " .
"post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
$run_vote1 = mysqli_query($conn2, $vote_1);
if($run_vote1){ echo 'Success'; }
}
?>
Here a simple answer, just serialize all your form data!
$('form').submit(function(){
$.post('feed.php', $(this).serialize(), function(data){
console.log(data);
}, 'json');
return false;
});
var post_answer1 = $("input[name='post_answer1']").val();

Sending Variable from php inside javascript

I have web ecommerce, and it use an API from delivery agent website rajaongkir.com,
I want to use the price of delivery agent to be a variable in my database.
Her is file order.php
<script type="text/javascript" src="js/script.js"></script>
<form action="input.php?input=inputform" method="post">
<table class="zebra-table">
<thead>
<tr>
<th>Kurir</th>
<th>Servis</th>
<th>Deskripsi Servis</th>
<th>Lama Kirim (hari)</th>
<th>Total Biaya (Rp)</th>
<th>Opsi</th>
</tr>
</thead>
<tbody id="resultsbox"></tbody>
</table>
script.js
function cekHarga(){
//var origin = $('#oricity').val();
var origin = 35;
var destination = $('#descity').val();
var weight = $('#berat').val();
var courier = $('#service').val();
$.ajax({
url:'process.php?act=cost',
data:{origin:origin,destination:destination,weight:weight,courier:courier},
success:function(response){
$('#resultsbox').html(response);
},
error:function(){
$('#resultsbox').html('ERROR');
}
});
}
process.php
if(isset($_GET['act'])):
switch ($_GET['act']) {
$cost = $IdmoreRO->hitungOngkir($origin,$destination,$weight,$courier);
//parse json
$costarray = json_decode($cost);
$results = $costarray->rajaongkir->results;
if(!empty($results)):
foreach($results as $r):
foreach($r->costs as $rc):
foreach($rc->cost as $rcc):
echo "<tr><td>$r->code</td><td>$rc->service</td><td>$rc->description</td><td>$rcc->etd</td><td>".number_format($rcc->value)."</td> <td></td></tr>";
$bayarr=$rcc->value;
endforeach;
endforeach;
endforeach;
endif;
}
endif;
I can access variable $bayarr at form in order.php.
How can I send variable $bayarr at process.php to order.php ?
use json to send more than 1 value from ajax call.
$arr['html'] = "<tr><td>$r->code</td><td>$rc->service</td><td>$rc->description</td><td>$rcc->etd</td><td>".number_format($rcc->value)."</td> <td></td></tr>";
$arr['price'] = $bayarr=$rcc->value;
echo json_encode($arr);
In ajax success,
success: function(response){
var content = JSON.parse(response);
$('#resultsbox').html(response.html);
alert(response.price);// will have your price here.
}
If you want to get some specific value with the same request which gives you HTML you can add the param inside some of the HTML tags at your response and after that to parse it..
Something as:
foreach($rc->cost as $rcc):
echo "<tr data-bayarr=\"{$rcc->value}\"><td>$r->code</td><td>$rc->service</td><td>$rc->description</td><td>$rcc->etd</td><td>".number_format($rcc->value)."</td> <td></td></tr>";
endforeach;
After that just proceed it at your ajax succes as:
success:function(response){
$('#resultsbox').html(response);
/* Because its in a foreach there will be multiple bayarrs .. */
$('#resultsbox').find('[data-bayarr]').each(function( i ) {
alert($(this).data('bayarr'));
});
},
The other way is to convert the response into json array where you have both HTML and bayarr values..
You can encode your entire $results array, which you're looping, if you had to:
<input type="hidden" id="data_clustor" name="data_clustor"
value="<?php echo base64_encode(json_encode($results)); ?>">
Then just reference $('#data_clustor').val(); and pass it to your next PHP page where you'd simply do:
$results=json_decode(base64_decode($_POST['data_clustor']));
and loop it all over again. Or pass along only the data you're interested in rather than the whole entire massive array.
Without seeing your code which calls cekHarga() or the elements you're referencing with:
var destination = $('#descity').val();
var weight = $('#berat').val();
var courier = $('#service').val();
It becomes a bit difficult to see what you're trying to do, since it's unclear where you're pulling these fields with these ids from if none of the code you've showed us contains it.
Alternatively, just use PHP sessions, and keep the information loaded on the server for the specific user in $_SESSION. Write to it whatever you want to remember, then read from it when you need it on the other page.

Categories

Resources