How to get passed parameter of Json_encoded using php - php

I am passing a parameter to a php url. For example, name.local.test/api.php?id=5&name=test. I was then getting the data from the url using the GET method and was saving it into a mysqlite database. After saving I am displaying the saved data with Json_encoded format.
[{"time":"1561384655","ip":"192.168.103.151","waterlevel":"85","station":"Near the Training Center","humidity":"39","temperature":"26"}
what is the easiest way to print such values in the json format on php page?
I am expecting something like:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Push the data in array
var time = new Date().toLocaleTimeString();
var txt = this.responseText;
var obj = JSON.parse(txt); //Ref: https://www.w3schools.com/js/js_json_parse.asp
ADCvalues.push(obj.waterlevel);
Tvalues.push(obj.temperature);
Hvalues.push(obj.humidity);
timeStamp.push(time);
showGraph(); //Update Graphs
//Update Data Table
var table = document.getElementById("dataTable");
var row = table.insertRow(1); //Add after headings
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = time;
cell2.innerHTML = obj.waterlevel;
cell3.innerHTML = obj.temperature;
cell4.innerHTML = obj.humidity;
}
};
xhttp.open("GET", "http://abdikani.local.abaarsoschool.org/json.php", true); //Handle readADC server on ESP8266
xhttp.send();
}

Related

Error arises when javascript code is executed

I changed the database columns to be not nullable and not it works find. But still, no values are received. here is the console error: 4abdikani.local.ask.org/json.php:1 Failed to load resource: net::ERR_NAME_NOT_RESOLVED 4graphs.html:153 GET abdikani.local.ask.org/json.php net::ERR_NAME_NOT_RESOLVED –
what will be the solution for such an error. The code answer for the question How to turn a json files into a graph? returns this error
Here is the main part of the code. I want it to return the value from the local php page and display it on a graph.
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Push the data in array
var time = new Date().toLocaleTimeString();
var txt = this.responseText;
var obj = JSON.parse(txt); //Ref: https://www.w3schools.com/js/js_json_parse.asp
console.log(obj);
obj.forEach(function(element_data){
console.log(element_data);
ADCvalues.push(element_data.waterlevel);
Tvalues.push(element_data.temperature);
Hvalues.push(element_data.humidity);
timeStamp.push(time);
showGraph();
var table = document.getElementById("dataTable");
var row = table.insertRow(1); //Add after headings
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = time;
cell2.innerHTML = element_data.waterlevel;
cell3.innerHTML = element_data.temperature;
cell4.innerHTML = element_data.humidity;
});
}
};
xhttp.open("GET", "http://abdikani.local.ask.org/json.php", true); // Works fine with me using the same json document locally - Handle readADC server on ESP8266
xhttp.send();
}
</script>
</body>
</html>

How to fix this Firebase data retrieval?

I need some help in displaying all the values in a Firebase database, in a table.
As is, it is just displaying the first value in the table alone
Results:
var tblCodes = document.getElementById('tbl_qrcode_list');
var databaseRef = firebase.database().ref('qrcode/');
var rowIndex = 1;
databaseRef.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
var row = tblCodes.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellName = row.insertCell(1);
cellId.appendChild(document.createTextNode(childKey));
cellName.appendChild(document.createTextNode(childData.qrcode_desc));
rowIndex = rowIndex + 1;
});
});
function save_code(){
var qrcode_desc = document.getElementById('qrcode_desc').value;
var qrcode_grp = document.getElementById('qrcode_grp').value;
var qrcode_stg = document.getElementById('qrcode_stg').value;
var qrcode_img = document.getElementById('qrcode_img').value;
var qrid = firebase.database().ref().child('qrcode').push().key;
var data = {
qrcode_id: qrid,
qrcode_desc: qrcode_desc,
qrcode_grp: qrcode_grp,
qrcode_stg: qrcode_stg,
qrcode_img: qrcode_img,
}
You need to create a cell for each value here :
you need to create cells for each data
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cellName.appendChild(document.createTextNode(childData.qrcode_desc));
cellName.appendChild(document.createTextNode(childData.qrcode_grp));
cell3.appendChild(document.createTextNode(childData.qrcode_id));
cell4.appendChild(document.createTextNode(childData.qrcode_img));
cell5.appendChild(document.createTextNode(childData.qrcode_stg));

With jQuery how I assign the json array to the index of the jquery array

Suppose I am retrieving the data(in json form) from the first.php and second.php(coding in php). I want to assign this json data in the array of the jQuery array. let the array is var total = [index1,index2] the first json data coming from the first.php will assign to the first index of the total and the second json data coming from second.php assign to the second index of the total. how will I do this. I have tried the following code. I am the bigner so if there is any mistake then sorry. for replying me thank you.
jquery
var total = ['index1','index2'];
var ajax = new XMLHttpRequest();
var method = "GET";
var url = "first.php";
var asynchronous = true;
ajax.open(method,url,asynchronous);
//sending ajax request.
ajax.send();
//receiving response from the first.php
ajax.onreadystatechange = function(){
if(this.readyState== 4 && this.status == 200){ //readyState==4 means request is finish and response is ready
//status==200 is 'OK'
var data = JSON.parse(this.responseText);
for(var a=0; a<data.length; a++){
total['index1']=data[a];
}
}
}console.log(total['index1']); //i want the output here
var url="second.php";
ajax.open(method,url,asynchronous);
ajax.send();
ajax.onreadystatechange = function(){
if(this.readyState== 4 && this.status == 200){ //readyState==4 means request is finish and response is ready
//status==200 is 'OK'
var data1 = JSON.parse(this.responseText);
for(var a=0; a<data1.length; a++){
total['index2']=data1[a];
}
}
}
first.php
include 'connection.php';
$data = array();
$query=mysqli_query($con,"select * from tabel_name ORDER BY id ASC");
if(mysqli_num_rows($query)){
while($row = mysqli_fetch_assoc($query)){
$data[] =$row;
};
echo json_encode($data);
}
second.php
include 'connection.php';
$data = array();
$query=mysqli_query($con,"select * from tabel_name ORDER BY id ASC");
if(mysqli_num_rows($query)){
while($row = mysqli_fetch_assoc($query)){
$data[] =$row;
};
echo json_encode($data);
}
I just wan to assign the first json array to index1 and show in console.log and second json array to the index2.
I found the problem. You use "this" in onreadystatechange callback, but "this" don't design your "ajax" variable.
I have renamed your "ajax" variable in "ajax1" and I have created a second "ajax2".
Please try this code :
var total = {index1: [], index2: []};
var ajax1 = new XMLHttpRequest();
var method = "GET";
var url = "first.php";
var asynchronous = true;
ajax1.open(method,url,asynchronous);
//receiving response from the first.php
ajax1.onreadystatechange = function(){
if(ajax1.readyState== 4 && ajax1.status == 200){ //readyState==4 means request is finish and response is ready
//status==200 is 'OK'
var data = JSON.parse(ajax1.responseText);
for(var a=0; a<data.length; a++){
total['index1'].push(data[a]);
}
console.log('=== index1 ===');
console.log(total['index1']); //i want the output here
}
}
//sending ajax request.
ajax1.send();
var ajax2 = new XMLHttpRequest();
var url="second.php";
ajax2.open(method,url,asynchronous);
ajax2.onreadystatechange = function(){
if(ajax2.readyState== 4 && ajax2.status == 200){ //readyState==4 means request is finish and response is ready
//status==200 is 'OK'
var data1 = JSON.parse(ajax2.responseText);
for(var a=0; a<data1.length; a++){
total['index2'].push(data1[a]);
}
console.log('=== index2 ===');
console.log(total['index2']); //i want the output here
}
}
ajax2.send();
You use a wrong property "lenght". A correct property is "length" in your "for" statements.
ajax.onreadystatechange = function(){
if(this.readyState== 4 && this.status == 200){ //readyState==4 means request is finish and response is ready
//status==200 is 'OK'
var data = JSON.parse(this.responseText);
for(var a=0; a<data.length; a++){
total['index1']=data[a];
}
// Here, server has returned response
console.log(total['index1']); //i want the output here
}
}
// Here, server has not yet returned response

Creating a loading image while ajax function loads [duplicate]

This is the code I have. I'm trying to insert a image to show that ajax is loading but I just can't get this right; I tried a lot of possible ways but it just isn't working. Any suggestions on what to do?
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('main_result');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
$("#main_result").empty().html('<img src="loading.gif" />');
var category = document.getElementById('category').value;
var brand = document.getElementById('brand').value;
var item = document.getElementById('item').value;
var queryString = "&category=" + category + "&brand="+ brand +"&item="+ item;
ajaxRequest.open("GET", "main_search_special.php?section=special" + queryString, true);
ajaxRequest.send(null);
You can approach this in a couple of different ways, you can either
Preload image and create the element when the request is sent and destroy it after it's done
Create it along with the document and then hide it until the request is sent, and then hide it again when it's done
A combination of the two: Preload and create element in javascript, and from there just hide/show the element at each request/completion.
#1 Is probably most preferred when the request is rarely sent, since it doesn't interfere with the document's load, but rather loads after everything else is done. Since creating/destroying an element takes up more processing time than simply hiding/showing the element, this is not a recommended approach.
#2 Is preferred when the request is sent frequently, since you'll be using the loader image often, there is no need to create/destroy it and just have it available from the start. I recommend this approach.
#3 Is preferred when you want to play it safe. This doesn't load the image until the page is done loading and requires very little processing time.
Example #1 | Code
HTML
<div id='content'></div>
Javascript
var PreloadIt = new Image(441,291);
PreloadIt.src="loader.gif";
var http = new XMLHttpRequest();
var url = "thepage.php";
var params = "whatever=you&want=in+here";
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById('content').removeChild(document.getElementById('ajaxloader'));
document.getElementById('content').innerHTML = http.responseText
}
}
function BeginLoading(){
var eLoader = document.createElement("img");
eLoader.src = "loader.gif";
eLoader.alt = "";
eLoader.id = "ajaxloader";
document.getElementById('content').appendChild(eLoader);
http.send(params);
}
BeginLoading();
Example #2 | Code
HTML
<div id='content'>
<div id='ajaxloader'><img src="loader.gif" style="display: none"/></div>
</div>
Javascript
var http = new XMLHttpRequest();
var url = "thepage.php";
var params = "whatever=you&want=in+here";
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById('ajaxloader').style.display = "none";
document.getElementById('content').innerHTML = http.responseText
}
}
function BeginLoading(){
document.getElementById('ajaxloader').style.display = "block";
http.send(params);
}
BeginLoading();
Example #3 | Code
HTML
<div id='content'></div>
Javascript
function CreateLoader(){
var img = document.createElement("img");
img.id = "ajaxloader";
img.src = "loader.gif";
img.alt = "";
document.getElementById("content").appendChild(img);
img.show = function(){ img.style.display = "block"; }
img.hide = function(){ img.style.display = "none"; }
img.hide();
return img;
}
var eLoader = CreateLoader();
var http = new XMLHttpRequest();
var url = "thepage.php";
var params = "whatever=you&want=in+here";
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
eLoader.hide();
document.getElementById('content').innerHTML = http.responseText
}
}
function BeginLoading(){
eLoader.show();
http.send(params);
}
BeginLoading();
Misc
I would recommend keeping track of the returned status. When a request fails, your code will return an error, since you're not handling it. Make sure that the request was a success and handle your errors.
You should also consider using encodeURIComponent(), if you've got data with special characters, like spaces and such.
var category = document.getElementById('category').value;
var brand = document.getElementById('brand').value;
var item = document.getElementById('item').value;
var url = "main_search_special.php"
var parameters = "section=special&category=" + encodeURIComponent(category) + "&brand=" + encodeURIComponent(brand) + "&item=" + encodeURIComponent(item);
ajaxRequest.open("GET", url+"?"+parameters, true);
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && http.status == 200){
var ajaxDisplay = document.getElementById('main_result');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}else{
console.log("Request for \""+url+ "\" failed.");
}
}
ajaxRequest.send();
Just add the image to your display area before you send the request. The results will overwrite it when the request completes.
...
var ajaxDisplay = document.getElementById("main_result");
ajaxDisplay.innerHTML = "<img src='loading.gif' />"
ajaxRequest.send(null);
I'd recommend putting the return action into its own function to make it look a little cleaner
But all you have to do to add an image is:
Before you do your send (basically anywhere in the function), create the image element and append to whatever element in your html you like
When you get a return from your ajax call, delete the image element.
this is what you can do-
set an image at your favorite position.make it's visibility to hidden.before making a call to php make it's visibility to visible and again after response from php file you can make your image's visibility to hidden.
This is one of the way you can do this,there are also other ways.
search.onclick = function()
{
var ajaxRequest;
document.getElementById("image_loading").style.visibility = "visible";
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("image_loading").style.visibility = "hidden";
var ajaxDisplay = document.getElementById('main_result');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
$("#main_result").empty().html('<img src="loading.gif" />');
var category = document.getElementById('category').value;
var brand = document.getElementById('brand').value;
var item = document.getElementById('item').value;
var queryString = "&category=" + category + "&brand="+ brand +"&item="+ item;
ajaxRequest.open("GET", "main_search_special.php?section=special" + queryString, true);
ajaxRequest.send(null);
}

Setting up the default value in a new textbox

I am trying to make a form in which there will be a button, when clicking on it a Javascript function will be called and a new row with a textbox will be added. In simple words, when clicking on the button, new text will be added. Here is the function:
function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
// right cell
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.name = 'txtRow' + iteration;
el.id = 'txtRow' + iteration;
el.size = 40;
cellRight.appendChild(el);
// select cell
var cellRightSel = row.insertCell(2);
var sel = document.createElement('select');
sel.name = 'selRow' + iteration;
sel.options[0] = new Option('text zero', 'value0');
sel.options[1] = new Option('text one', 'value1');
cellRightSel.appendChild(sel);
}
Now please guide me: how can I set the default value of the text box and drop down box? I mean in this code where should I put <?php echo $data['pno'];?>
I have tried putting in the HTML form; for the first row it works but for the second row it doesn't work. Thanks.
i have solved in this way
<input type="button" value="Add" onClick="addRowToTable(<?php echo $data['pno'];?>);" />
and on the javascript side
function addRowToTable(a)
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// left cell
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
// right cell
var cellRight = row.insertCell(1);
var el = document.createElement('input');
el.type = 'text';
el.value=a; // here i have achived the value
el.name = 'txtRow' + iteration;
el.id = 'txtRow' + iteration;
el.size = 40;
}
might be its not a good solution but for my case it works
How about you save the default value in a separate JS variable in your html like:
var defaultValue = "<?php echo $data['pno'];?>";
Or try this:
var defaultValue = "<?= $data['pno'] ?>";
Then when you are adding new input you can use it like this:
el.value = defaultValue;

Categories