Not able to fetch json data from a php file in localhost - javascript

I am trying to make a client side script to fetch JSON data from a PHP file. I am using XAMPP to run the PHP scripts. When I run the demo_file.PHP, it shows the output. But when I try to fetch the data using the client side script it does not show any result.
The demo_file.php is:
<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
?>
and the demo.html to fetch the json data is:
<!DOCTYPE html>
<html>
<body>
<h2>Get data as JSON from a PHP file on the server.</h2>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "demo_file.php", true);
xmlhttp.send();
</script>
</body>
</html>

You probably getting error:
<b>Warning</b>: Creating default object from empty value in <b>[...][...]</b> on line <b>3</b><br />
You can not create object directly like this.You have create instance of StdClass() first.Like below.
$myObj = new stdClass();//need to create instance first
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";
$myJSON = json_encode($myObj);
echo $myJSON;
For more see here Creating default object from empty value

Related

Facing undefined error in json using javascript

I am using javascript ajax to fetch data from the JSON API server and want to show these data in an HTML table.
But I get an undefined error in HTML data. That is
Name id
undefined undefined
There is my code
<html>
<body>
<table class = "src">
<tr><th>Name</th><th>id</th></tr>
<tr><td><div id="Name"></div></td>
<td><div id="Id"></div></td></tr>
</table>
</body>
</html>
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/users";
xmlhttp.onreadystatechange = function(e) {
if (this.readyState == 4 && this.status == 200) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(this.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Id").innerHTML = jsonObj.id;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
What should I do to resove this? Thanks in advance.
The problem is that you are trying to access an object, but the output of the API is actually an array. You can get the first object by doing jsonObj[0], as follows:
<html>
<body>
<table class = "src">
<tr><th>Name</th><th>id</th></tr>
<tr><td><div id = "Name"></div></td>
<td><div id = "Id"></div></td></tr>
</table>
</body>
</html>
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/users";
xmlhttp.onreadystatechange = function(e) {
if (this.readyState == 4 && this.status == 200) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(this.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").textContent = jsonObj[0].name;
document.getElementById("Id").textContent = jsonObj[0].id;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
See this codesandbox where the code is working.
Edit: As T.J. Crowder has mentioned, it is better to use textContent rather than innerHTML to avoid unwanted HTML to be rendered (never trust user input!).

Passing variables from javascript to php file

I have worked on API (zomato) that gives me restaurant details. I want to insert them into my local database, but I have a problem with passing the variable to PHP because it's too much big for $_GET to handle it. I tried to use $_POST but The output of the post was empty.
// JS code
function showCafes(str){
var xhttp;
xhttp = new XMLHttpRequest();
console.log(str);
xhttp.open("GET","https://developers.zomato.com/api/v2.1/search?entity_type=city&q=t&start="+str+"&count=20" , true);
xhttp.send();
var restaurants="";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var r=JSON.parse(this.responseText);
var rest ={
name : r.restaurant[1].restaurant.name
};
$.post("addFromApi.php", rest);
window.location.href="addFromApi.php";
// PHP code
<?php
print_r($_POST);
?>
I expected from the PHP code to print the name of the first element in it.
// Sample output From API
{"results_found":1,
"results_start":0,
"results_shown":1,
"restaurants":
[{"restaurant":{
"R":{"res_id":18692654},
"id":"18692654",
"name":"East Village"}
I have solved it with making a form from js like this
document.getElementById("cafes").innerHTML += '<form id="rests" action="addFromApi.php" method="post"><input type="hidden" name="q" value="'+restaurants+'"></form>';
document.getElementById("rests").submit();
//resturants is the variable that I wanted to pass to php.

Is it possible to load content and variables via xmlhttprequest?

is it possible to load content AND variables from a *.php-File with xmlhttprequest?
I have a index.php:
<script>
function loadsite() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("divrequest").innerHTML = this.responseText;
}
};
xhttp.open("GET", "siterequest.php", true);
xhttp.send();
}
$(document).ready(loadsite());
</script>
<div id="divrequest"></div>
My siterequest.php:
<?php
echo "some dynamic content";
echo json_encode(array($var1,$var2,$var3));
echo "more dynamic content";
?>
Am I able to get the variables? Or did I misunderstand the function of XMLHttpRequest?
EDIT:
If I use
var myvariable = JSON.parse(JSON.stringify(xhttp.responseText));
console.log(myvariable);
I will get the code of the whole page.
XMLHttpRequest sends an HTTP-request to the server to access the desired page. PHP is executed before the response data is sent back to you, in which case it's translated to HTML. Therefore, you can't get the variables using this approach with JavaScript. That happens before you even receive the data.

AJAX get JSON function not looping

Question: Why the function is not able to retrieve the json object?
I also noticed when debugging the code on my browser that the console does one pass through the code but never comes back! I thought the way this works is by having the function at the bottom of the html code looping back up until the the request status is changed.
I am starting to learn html javascripting. Following a tutorial I have the following code for html page that gets and parse JSON object:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ajax_get_json(){
//crate our XMLHttpRequestobject
var hr = new XMLHttpRequest();
//var p1 = "p1";
//creat some variable we need to sned to our php file
hr.open("GET", "mylist.Json", true);
//set content type information for sending url encoded variables in the
//reqeust
console.log(5+6);
hr.setRequestHeader("Content-type", "application/json", true);
//Acess the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatchange = function(){
if (hr.readyState == 4 && hr.status == 200){
var data = JSON.parse(hr.responseText);
var results = document.getElementsById("results");
results.innerHTML=data.user;
// document.getElementById("results").innerHTML = return_data;
}
}
//send the data to php now and wait for the response to update the
//status div
hr.send();
results.innerHTML = "reqeusting...";
// document.getElementById("results").innerHTML="processing...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type="text/javascript">ajax_get_json();</script>
</body>
</html>
Here is the json object code
{"user":"John", "age":22, "country":"United States" }
Both files are sitting in my ubuntu server that has LAMP enabled. Here is what the directory looks like:
Apparently the problem lies in declaring var results within hr.onreadystatechange function. Moving the declaration to the top fixed the code. Here is the working code:
<!DOCTYPE html>
<html>
<head>
<script>
function ajax_get_json(){
var results = document.getElementById("results");
//crate our XMLHttpRequestobject
var hr = new XMLHttpRequest();
//var p1 = "p1";
//creat some variable we need to sned to our php file
hr.open("GET", "mylist.json", true);
//set content type information for sending url encoded variables in the
//reqeust
//console.log(5+6);
//hr.setRequestHeader("Content-type", "application/json", true);
hr.setRequestHeader("Content-type", "application/json", true);
//Acess the onreadystatchange event for the XMLHttpRequest object
hr.onreadystatechange = function(){
if (hr.readyState == 4 && hr.status == 200){
var data = JSON.parse(hr.responseText);
results.innerHTML=data.user;
// document.getElementById("results").innerHTML = return_data;
}
}
//send the data to php now and wait for the response to update the
//status div
hr.send(null);
results.innerHTML = "reqeusting...";
// document.getElementById("results").innerHTML="processing...";
}
</script>
</head>
<body>
<div id="results"></div>
<script>ajax_get_json();</script>
</body>
</html>

Update a php variable with AJAX Javascript

I have 2 php files, the first is BAConsult.php which is the main file, and the other is BAConsultRecordsAJAX.php. This line of code is in BAConsultRecordsAJAX.php:
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
}
In BAConsult.php I have this:
echo $skincareinuse;
Is it possible to bring over the $skincareinuse value from the BAConsultRecordsAJAX.php page, to the $skincareinuse variable on the BAConsult.php page?
Such that, lets say whenever I do a click on the table row, the value of $skincareinuse will be updated and shown by the echo, without the page refreshing?
[EDITED TO SHOW MORE OF MY CODES]
This is BAConsult.php file, where my main code is.
<?php echo $jsonvariable; ?>//Lets say i want to store the JSON data into this variable
function showconsultationdata(str) { //face e.g and checkboxes for that date selected.
if (str == "") {
document.getElementById("txtHint2").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint2").innerHTML = xmlhttp.responseText;
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse;
//I want to store this ^^ into the php variable of this page.
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
This is my BAConsultRecordsAJAX.php page.
$q = $_GET['q']; //get dateconsulted value
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
$skincondition=explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
echo "<div id='arrayoutput'>";
echo json_encode(array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition));
echo "</div>";
You don't actually want to transfer the variable from BAConsultRecordsAJAX.php to BAConsult.php, but to BAConsult.js (I suppose that's the name of your JS file).
In reality, even that's what you wanted to do, it's impossible, because your main PHP is processed before the page even loads. What you can do, however, is overwrite the rendered value with a new one with the use of JavaScript.
To do that, send an AJAX request to BAConsultRecordsAJAX.php requesting the variable's value as shown below:
In JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
var td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
In PHP:
<?php
echo $skincareinuse;
?>
[EDIT]:
If you are using inline JavaScript use the following code:
<script type = "application/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
</script>
[EDIT 2]:
To pass a JSON object to PHP file via an AJAX request you have to make it a string. That requires the following code:
var JSONstring = JSON.stringify(yourJSONobject);
Then you can pass it in your PHP file with the AJAX request by putting it inside send() as shown:
xhttp.send("json_object=" + JSONstring);
Then in PHP, in order to use it, you have to decode it:
<?php
$json_object = json_decode($_POST["json_object"]);
// Now it's ready to use
?>
[About the code]:
Notes about the first file:
First of all, you have put your plain JavaScript code inside a PHP file and therefore it will not work. You have to wrap it in <script type = "application/javascript></script>
I don't have a clue what you are trying to do here:
Code:
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
It seems like you are trying to filter out and parse the innerHTML of #arrayoutput.
If the response is a JSON string, not HTML, so you absolutely can't do that. The logic of this above line is flawed.
How I would write your code:
function showconsultationdata(str) {
var xmlhttp;
if (!str) {
$("#txtHint2").empty();
} else {
xmlhttp = new XMLHttpRequest();
// Providing support for a 15-year-old browser in 2016 is unnecessary
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#txtHint2").html(xmlhttp.responseText);
var a = JSON.parse(xmlhttp.responseText);
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse; // The variable you want
// Its saved in "text" and can use something like:
// $("#element").html(test); to have it replace your current text
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Notes about the second file:
I don't know if the query works for you, but it probably shouldn't, because:
$_SESSION is an associative array and you pass nric, whereas it should be "nric".
As $_SESSION is an array, the proper method to insert its value to your query is: {$_SESSION["nric"]}.
To ensure that you don't become the victim of an SQL Injection, use parameterised queries or at least sanitise somehow the received data, because GET is relatively easy to hack. Check the improved code later on how to do it.
How I would write your code:
$q = $_GET['q']; //get dateconsulted value
$dbconn = mysqli_connect("localhost", "root", "") or die("Error!");
mysqli_select_db($dbconn, "database") or die("Error!");
$consult = "SELECT * FROM Counsel where nric='{$_SESSION["nric"]}' and dateconsulted = ?";
if ($stmt = mysqli_prepare($dbconn, $consult)) { // By using a prepared statement
mysqli_stmt_bind_param($stmt, "s", $q); // you eliminate the chances to have
if (mysqli_stmt_execute($stmt)) { // an SQL Injection break your database
$consultresult = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($consultresult) > 0) {
while ($row = mysqli_fetch_array($consultresult)) {
$skincareinuse = explode(",",$row['skincarecurrentlyinuse']);
$skincondition = explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
$array = array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition);
echo "<div id='arrayoutput'>";
echo json_encode($array);
echo "</div>";
mysqli_stmt_close($stmt);
mysqli_close($dbconn);
exit;
}
}
}
Obviously you may change the values to suit your requirements, you must have jquery installed, the time value could be anything you want
$.ajaxSetup({ cache: false });
setInterval(function() {
var url = "pagethatrequiresrefreshing.php";
$('#divtorefresh').load(url);
}, 4000);
Using include will most likely work. From the docs:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
BAConsultRecordsAJAX.php
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse[] = explode(",",$row['skincarecurrentlyinuse']);
}
include "BAConsult.php";

Categories

Resources