I need to know what can done to display data from mysql database in cordova app.
I made a php file placed it on the server.
then i made the html with json code to fetch data from mysql database.
The data from mysql database should be displayed in the div with id="demo".
I have done this till now.
My Php file looks like this:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
include "../../webConfig/web.config.php";
$conn = connect();
$q = $conn->query("SELECT name FROM 'online_' ORDER BY DESC");
$rows=$conn->query($cb);
$rows=$conn->query($cb);
foreach($rows as $row){
echo $row["ID"];
echo $row["first_name"];
echo $row["middle_name"];
echo $row["last_name"];
}
echo json_encode($rows);
?>
My HTML file Looks like this.
<div data-role="content">
<div class="container-fluid">
Online Application
<p id="demo">
.....
</p>
<script>
var obj, dbParam, xmlhttp;
obj = { "table":"online", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "http://localhost/admin/notify/test.php?x=" + dbParam, true);
xmlhttp.send();
</script>
</div>
</div>
I have been trying to do this using json But my html file dosen't show anything apart from those dots.
I tried placing the php file on the web server as well, but still it did not show anyhing.
Related
I create articles on an administration and on each article i have a button to like it, at the onclick, the javascript call the php code in an other file to fill the database, and the database should resend the number of like, but the echo on the processing file doesn't fill the reponseText of the XMLHttprequest and I don't know why and that's I'am trying to solve and understand.
I succeeded to do it but I don't want to refresh the page at each like, so i use XMLHttpRequest to display correctly the likes whithout refreshing.
I followed serevals tutoriels, but that doesn't work well.I had to miss something.
First I have a file : index.php with my javascript and php code:
<ul class="ulp">
<li class="lip">
<button class="likebutton" onclick="like('<?= $ipclient ?>','<?= $event->getID()?>')" style="color:#5B5A57">
<i id="coeur<?= $event->getID()?>" class="<?= $classlike ?>">
<span id="nblike<?= $event->getID()?>">
<?= $tableLikes->countLike($event->getID()) ?>
</span>
</i>
</button>
</li>
</ul>
<script>
function like(ipclient,eventid)
{
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200)
{
document.getElementById("nblike" +eventid).innerHTML = this.responseText;
};
xhttp.open("GET","event/" + ipclient + "-" + eventid, true);
xhttp.send();
}
</script>
When I am cliking on this button that send correctly the request.
I have a second file that processes the data:
<?php
use App\Model\Likes;
use App\Table\LikesTable;
use App\Connection;
$pdo = Connection::getPDO();
$like = new Likes();
$tableLike = new LikesTable($pdo);
$ip = $params['ip'];
$id_event = $params['id'];
if($tableLike->likeIp($ip,$id_event) === true){
$like->setId_article($id_event);
$like->setIp($ip);
$tableLike->newLike($like);
}else if($tableLike->likeIp($ip,$id_event) === false){
$tableLike->dislike($ip,$id_event);
}
echo $tableLike->countLike($id_event);
I would like to have the content of the last echo in the reponseText of my object XMLHttpRequest.
How can I do ?
Thanks you in advance .
So I am writing a API, on the front-end it uses HTML, JS and CSS, and on the back end it uses PHP which will have access to my SQL database.
My task is once a button is clicked, create a function that will send information that is encoded in JSON off to the .php file, there I need to decode that object from JSON to PHP, then connect to the SQL database, and return relevant information encoded in JSON back to the HTML page, and later functionality will be able to update/delete certain data.
This API uses two main pages being the HTML and PHP files, along with the SQL database. Can somebody tell me why this is not working and how I can fix it? To clarify I would like to be able to select a radio button option, then press the app_list_button, which will return all Applications sorted by app_name or their review rating. Any help will be greatly appreciated and if I am able to structure anything better please let me know.
index.html
<div id='app_content'>
<label>Refine search by</label>
</br>
<input type="radio" id="name_radio">
<label>Name</label>
</br>
<input type="radio" id="rating_radio">
<label>Rating</label>
</br>
<button id="app_list_button" onclick="load_list_function()">View App List</button>
</br>
<p id='app_list_p'></p>
<input type="submit" name="app_detail_button" value="View App
Details">
</br>
</div>
</div>
</body>
<script>
var app_list_bttn = document.getElementById('app_list_button');
var radio = {};
//List apps
function load_list_function() {
var xhr = new XMLHttpRequest();
//name radio checked
radio.sortByName = document.getElementById('name_radio').checked;
//rating radio checked
radio.sortByRating =
document.getElementById('rating_radio').checked;
document.getElementById('app_list_p').innerHTML = this.responseText;
xhr.open('GET', 'API.php', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(radio));
}
</script>
API.php
<?
$conn = mysqli_connect('localhost', '30319329', 'password', 'Application');
$errors = array();
$json_response = array();
$radio_req = file_get_contents('php://input');
$radio_result = json_decode($radio_req);
//get a list of all apps
//encode into json to send back
if ($radio_result - > sortByName == true) {
//order by name
$results = mysqli_query($conn, "SELECT app_name FROM App");
while ($row = mysqli_fetch_assoc($results)) {
// You can modify the $row here as well, or filter out certain rows
$json_response[] = $row;
}
header("Content-Type: application/json");
echo json_encode($json_response);
} else($radio_result - > sortByRating == true) {
//order by rating
//order by name
$results = mysqli_query($conn, 'SELECT app_name, rating FROM App, App_Review ORDER BY rating ');
while ($row = mysqli_fetch_assoc($results)) {
// You can modify the $row here as well, or filter out certain rows
$json_response[] = $row;
}
header("Content-Type: application/json"); echo json_encode($json_response);
}
$conn - > close();
?>
Most likely the issue is this:
file_get_contents('php://radio');
That will not give you anything, it needs to be:
file_get_contents('php://input');
Also, when you do:
document.getElementById('app_list_p').innerHTML = this.responseText;
you are setting the innerHTML before you've even done the ajax request - this in this context is the window, so this.responseText will always be undefined.
You need to do it more like:
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
document.getElementById('app_list_p').innerHTML =xhr.responseText;
}
}
I am a beginner and I am trying to echo arrays and append them into a html division i created. The AJAX call I made was successful but the response was not appearing inside the division i assigned it to. Upon further inspection, I found out that the response I have received has an array length over 600 ( I am expecting 10 records). So there must be something wrong with my echo PHP file or the receiving end of the HTML file but just cannot figure out what that is.
Here are my codes:
listdiscount.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "root", "bencoolen");
$userid = $_GET['userid'];
$result = $conn->query("select userid, codename from discountcode where userid ='" . $userid . "' ");
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
printf("Userid: %s '' Codename: %s", $row["userid"], $row["codename"]);
}
$conn->close();
?>
index.html ( with js codes )
<html>
<script>
function mydiscount(){
var userid = "jimmy";
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/listdiscount.php";
url += "?userid=" + userid;
alert(url);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("readystate=4 and status =200");
mydiscountresult(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function mydiscountresult(response) {
var arr = response;
alert(arr); //alerted
alert(arr.length); //alerted 600+ arrays
alert("mydiscountresult working"); //alerted
var i;
$("#discountcontent").empty();
for(i = 0; i < arr.length; i++) {
$("#discountcontent").append("<b>" + arr[i].userid + "</b>"+ arr[i].codename + "<hr>");
}
}
mydiscount();
</script>
<div data-role="content" class="ui-content" id="discount">
LIST OF DISCOUNT CODE:<br>
<div id="discountcontent" class="ui-grid-solo">
</div>
</div>
</html>
Here is what my response look like when alerted:
addition note: my php files are in different folder so serverurl() is declared and used here.
the get request returns a json array so you need to convet it in to normal array using json parse. you may please change the line of code as
mydiscountresult(JSON.parse(xmlhttp.responseText));
It will work fine.
The Function xmlhttp.responseText retun a String, right?
You gave this string into function mydiscountresult and copy it into variable var. It is still a string, isn't it?
So the alerts work fine and do there jobs on the string (length 600 and so on)
Then you walk over this string letter by letter (this is what your for-loop is doing). On every letter var[i] you try to read a property userid. I think no normal letter (calld char) hav a property called userid. So this result in an empty string.
I think you would like to get the array from the string xmlhttp.responseText. To do so you just let JSON parse this string and it gave you an Object.
JSON.parse(xmlhttp.responseText)
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I have a main file
index.php
in which I include four other files like
header_get_started.php,
content_main.php,
right_sec_home.php,
footer.php.
Here is my code
"index.php"
<script src="js/ajax.js"></script>
<?php include_once('header_getstarted.php'); ?>
<?php include_once('content_main.php'); ?>
<?php include_once('right_sect_home.php'); ?>
<?php include_once('footer.php'); ?>
"header_getstarted.php"
<span class="select_input">
<?php
$sqlCmd = "some query";
echo combo('cmb_command','custom-class1 custom-class2','cmd_name','cmd_id','0',$sqlCmd,'sendpostmtu()' $width="style='width:250px;cursor:pointer;'")
?>
<input type="submit" name="" class="sub_bg" value="" onclick="get_request_by_command($('#cmb_command').val());">
</span>
In header_get_started.php
When select any command from select box, I want to assign it's id to $_SESSION['id'].
Onclick of selection box I have an ajax request which can refresh the main content (content_main.php). Also I want that selected id in another page in right_sec_home.php to refresh it's content.
How can I assign the php session id in JS file for 2nd page?
My JS file is
function get_request_by_command (commandId) {
var cmdTitle=$('#cmb_command :selected').text();
if(cmdTitle=="") {
cmdTitle='ABC';
}
$("#main_wrap").hide();
if(cmdTitle=='--Select--'){
$("#cmdTitle").html("");
}else{
$("#cmdTitle").html(cmdTitle);
}
$("#cmbs_cmd").val(commandId);
document.getElementById('request_list').innerHTML='<img src="images/loader.gif" />';
var strURL="request_by_command_tbl.php?id="+commandId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var ret = req.responseText;
$("#requestTitle").html("<span id='cmdTitle'>"+cmdTitle+"</span>);
$('#request_list').html('');
$('#request_list').html(ret);
$('#main').show();
$("#searchDiv").show();
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
With using this jQuery function, I have created an ajax request, and send the id to the "request_by_command_tbl.php" file.
In "request_by_command_tbl.php" file i assigned,
$_SESSION['id'] = $_REQUEST['id'];
Also I want this $_SESSION['id'] in right_sec_home.php at same instant.
So is their any way to assign php $_SESSION['id'] in the jQuery script file before sending ajax request.
My other files
"content_main.php"
<div id="request_list"> </div>
<div> </div>
<div id="add_space"></div>
Right section home file in which i need session id
"right_sec_home.php"
<?php
function getRequestByMonth($month, $year, $id){
$que ="SELECT distinct(MS.date) FROM commands AS MC , ranks AS MR ,steady_tours AS MST, preferred_tours AS MPT, registration AS MMS where date_format(rm_date, '%c-%Y') = '".$month."-".$year."'
AND MMS.cmd_id ='".$_SESSION['id']."'
order by MMS.date";
$res = mysql_query($que);
while($rows[]=mysql_fetch_array($res)){}
foreach ($rows as $res):
if($res['date'] == "") continue;
$dt = date("Y-n-j", strtotime($res['date']));
$return[getDateB($dt)] = $res['date'];
endforeach;
return $return;
}
I hope that this is clear enough.
Any ideas?
Please help.
there is no way for you to access the session information with jquery ..
explanation
sessions are files stored on the server --> where is java script is only a client side language ..
there is always a work around .. but i guess you should explain more about what exactly you want to achieve
<?php $sessionId = session_id(); ?>
<input id="session_id" name="session_id" type="hidden" value="<?php echo $sessionId; ?>" />
Get the value of the hidden field using jquery.
You can use some hidden fields or script variables inside the php file.
example :
<script>
var id = <?php echo $_SESSION['id']; ?>;
</script>
varible id can be accessible using the javascript or jquery
I am busy learning Ajax and need to use Postgres for the backed DB. I found an example for Mysql which works but when I convert it to Postgres, it stops working. I have not made any changes to the HTML code when swapping from Mysql to Postgres.
When I execute the php code at command line (php test.php), it works and outputs the correct number of rows and data.
Here is the php
<?php
$dbh = pg_connect("host=192.168.0.8 dbname=test user=test password=test");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "SELECT * FROM users";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
// iterate over result set
// print each row
while ($row = pg_fetch_array($result)) {
echo "Name: " . $row[1];
echo "<BR />";
}
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
?>
And here is the html
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "test.php";
var fn = document.getElementById("name").value;
var vars = "name="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
document.getElementById("name").value = "";
}
</script>
<script type="text/javascript">
function setFocus()
{
document.getElementById("name").focus();
}
</script>
</head>
<body onload="setFocus()">
<div>
<form name="input" action="" onsubmit="ajax_post(); return false;">
Barcode : <input type="text" id="name" size="30"><br />
</form>
</div>
<div style="background-color: lightyellow; border: 1px solid black; width: 400; height: 300;">
<div id="status"></div>
</div>
</body>
One thing I have noticed is that when I run the test.php file at command line with postgres, anew-line character is always appended to the end of the data.
Thanks
O
Install Firefox and the Firebug add-on. In Firebug, you can conveniently watch the whole communication between your HTML and PHP page, and there's also a great JS debugger with breakpoints etc. included. You don't seem to have a good idea what the error exactly is, but you should still be able to spot it with these tools.