Ajax doesn't show PHP data - javascript

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 } ?>

Related

Undefined index:usernames

I’m trying to pass php variable to another class using ajax to another class known as post.php. It keep saying in another class post.php that “undefined index:usernames” when I try to print it in another class as $echo $nameOfUser can anyone reckon what am I doing wrong? Thanks
index.php
<?php
session_start();
?>
<html>
<head>
<script src=“ https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js ”</script>
</head>
<body>
<?php
global $username;
$nameOfUser = $_SESSION['name'];
?>
<script>
var username = '<?php echo $nameOfUser ?>';
console.log(username); //it prints the right username here
$.ajax({
type:'POST',
url: 'post.php',
data: {function : 'testing', usernames: username},
success: function() {
alert('success');
}
});
</script>
post.php
<?php
session_start();
ini_set('display_errors', '1');
ini_set('error_reporting', E_ALL);
?>
<html>
<head>
</head>
<body>
<hr>
<?php
$username = $_POST['usernames'];
echo $username; // it says here undefined index usernames
if ($functionname == 0){
testing($username);
}
function testing($username) {
echo 'my name is: '; //it prints that
echo $username;
}
?>
</body>
</html>
$_POST[...] reads data from the request.
When you make a POST request to the URL, the data in that request will be available to the PHP handling that URL.
When you make another, separate request, to the URL (or another URL that uses some of the same code) then it will have access to that second request.
It won't have access to the data from the first request.
If you want to persist that data between requests then you need to store it somewhere (such as a session or a database) and retrieve it when you want to use it.
Your ajax request type is 'POST' and you should use $_POST instead of $_GET.
Or you can use $_REQUEST variable that containt $_GET, $_POST and $_COOKIE.

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.

Passing PHP variable via AJAX to PHP variable in another DIV

I've been working on this for a whole day but think I'm getting confused on the various methods available while I learn AJAX. I want my website to display the results of Python script. I can do that.
The problem is the script's results change randomly (it's the status of my garage door) and my site is clunky if the garage door's status changes. Usually the user has to keep reloading the page to get a current status. I'm trying to have the DIV that shows the status to update every 5 seconds thus showing the new status.
The Python script takes about 4 seconds to run, so I want to keep calling it as a function and pass it as a DIV on my site where I want to display the results.
If possible, one PHP file (index.php). Here is the skeleton of what I'm looking to do. My get_status function works, but I'm at a loss on the rest of it.
Thank you.
EDIT: Code updated with minor tweaks spotted by the commenters.
<html>
<body>
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
echo $status;
}
?>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
var java_status = <?php echo json_encode(get_status) ?>;
// I have no idea how to pass a variable from PHP thru javascript to PHP on the
// same page. Trying to pass on results of get_status function every 5 seconds.
setInterval(function(){
$.ajax({
url: "index.php"
type: "POST"
dataType: "json"
data: ({status: java_status}),
success: function(data){
$("#status_div").html(data);
}
})
}, 5000);
</script>
<div id="status_div">
<?php
$new_status = json_decode(data);
?>
// I have no idea how to get that status variable here.
The Garage Door Status is: <?php
echo $new_status;
?>
</div>
</body>
</html>
To do this properly you have to have valid HTML and you don't need to send the PHP script any parameters. In addition, you need to separate your PHP from the rest of the code, else you will get back all of the markup in your AJAX response:
PHP Script - php_python.php
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
echo $status;
}
get_status(); // execute the function
?>
HTML Page - index.php (note the use of a document ready handler because the script is at the top of the page)
You also need to separate <script> tags, using one to load the jQuery library and another to describe your JavaScript functions.
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){ // you need a document ready handler if you put the script at the top of the page
setInterval(function(){
$.ajax({
url: "php_python.php",
type: "POST",
dataType: "text",
success: function(data){
$("#status_div").html('The Garage Door Status is: ' + data);
}
})
}, 5000);
});
</script>
</head>
<body>
<div id="status_div"></div>
</body>
</html>
If you're just learning jQuery's AJAX here are some basic tips for setting it up and trouble-shooting problems.
Create a page and named it status.php
status.php include these code:
$status = shell_exec('python /path/to/garage_door/myq-garage.py status');
echo $status;
Make another page index.php and include-
<div id="status_div">
</div>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$.ajax({
url: "status.php",
dataType: "html",
success: function(data){
$("#status_div").html(data);
}
})
}, 5000);
</script>
Hope this will help you
If you are using ajax, you can make your life very easy:
function_status.php:
<?php
function get_status(){
$status = shell_exec('python /path/to/garage_door/myq-garage.py status'); //Equals either 'Open' or 'Closed'
return $status; //avoid echo in such functions, try to not produce side effects
}
ajax_server.php:
<?php
require_once("function_status.php");
echo get_status();
index.php:
<?php
require_once("function_status.php");
?>
<html>
<body>
<div id="status">
<?php echo get_status(); ?>
</div>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
<script type="text/javascript">
( //run function immediatly
function($){ //in this anonymous function, $ is always jQuery
function updateStatus(){
$.ajax({
url: "ajax_server.php"
type: "POST"
dataType: "json"
data: ({status: 1}),
success: function(data){
$("#status").html(data);
}
});
}
//first call it onload
$(function(e){
updateStatus();
}
//and then every 5 seconds
setInterval(updateStatus, 5000);
);
}
)//run function immediatly
(jQuery); //pass parameter jQuery to immediate execution of anonymous function
</script>
</body>
</html>
it is not a very clean way, and i used the <?php echo get_status(); ?> only, because your python script takes 4 seconds, so you would have no status for the first 4 seconds.
else you could change it to index.html and have a nicely seperated html and php, if you anyway want to populate the html with ajax.
if you really want to hack it into one file, you need an
if(isset($_POST['status'])){
echo get_status();
}else{
//output the html around the whole thing
}

How to retrieve specific data from database using ajax

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.

JS ProgressBar update from inside PHP While Loop called by AJAX?

I have a PHP page with a form. Once the form is submitted, it calls another PHP page via AJAX to make calls to MySQL, then process the results, and return them to the first PHP page. The MySQL processing takes place inside a while loop. I wanted to update a progress bar that indicates the progress of the loop. But I get:
parsererror
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
and nothing happens. Any ideas if what I am doing below is wrong? How Can I update a progress bar from an AJAX called while loop?
The following is a rough code:
Main PHP page:
<html>
<head>
<link rel="stylesheet" type="text/css" href="jquery-ui.css">
<script type='text/javascript' src='jquery-1.11.1.min.js'></script>
<script type='text/javascript' src='jquery-ui-1.10.4.min.js'></script>
<script type='text/javascript' src='my.js'></script>
</head>
<body onLoad="onLoad()">
<form action="" method="POST" id="myForm" name="myForm">
<div id="progressBar"></div>
<input class="txt"
id="btnSubmit"
style="margin-top: 12pt; font-family: arial; color: grey; font-weight: bold; font-size: 15pt;"
type="submit"
name="action"
value="SEARCH" />
</form>
</body>
</html>
The my.js has:
function onLoad() {
$('#progressBar').progressbar({ disabled: true });
$('#progressBar').hide();
}
$(document).ready(function() {
$("#myForm").submit(function(event) {
$(function () {
.ajax({
url: 'myCall.php', // the script to call to get data
type: "POST",
data: { data: 'something'}
},
dataType: 'json',
success: function(data) {
// do something
},
error: function (jqXHR, textStatus, errorThrown){
console.log(textStatus, errorThrown);
},
});
});
});
and myCall.php has some calls to MySQL database, then post processing:
$result = mysqli_query($mysqli, $sql);
$j = 1;
// enable and show the bar
echo '<script language="javascript"></script>';
echo '$("#progressBar").show();';
echo '$("#progressBar").progressbar({';
echo 'disabled: false,';
echo 'value: '.$j.',';
echo 'max: '.$result->num_rows.',';
echo '});';
echo '</script>';
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
// doing stuff and then update the bar
// update
echo '<script language="javascript"></script>';
echo '$("#progressBar").progressbar({';
echo 'value: '.$j.',';
echo '});';
echo '</script>';
}
// disable and hide the bar
echo '<script language="javascript"></script>';
echo '$("#progressBar").progressbar({';
echo 'disabled: true,';
echo '});';
echo '$("#progressBar").hide();';
echo '</script>';
It looks like the JSON you are parsing is not valid JSON. I would print out the JSON you are trying to run through the parser and run it through a JSON validator such as http://jsonformatter.curiousconcept.com/.
Also, the following code looks unclean to me, which might cause the problem. I'm not sure if you are using a more standardized JSON parser. If so, it would probably not expect a data object inside a data object. This is a complete guess, but you should probably change
.ajax({
url: 'myCall.php', // the script to call to get data
type: "POST",
data: { data: 'something'}
},
to
.ajax({
url: 'myCall.php', // the script to call to get data
type: "POST",
data: { "key1" : "value1"}
},
I don't think you are actually showing where the JSON is being parsed in your question. Are you able to show exactly how you parse it and what you are parsing?
Thanks!

Categories

Resources