How to add element in XMLHttpRequest echoed from PHP? - javascript

at my controller side I have three data being echoed..
echo $variant->Field1;
and at my client side , I have the below ajax code,
function variants(master_id,sku)
{
if(master_id=="")
{
document.getElementById("variants").innerHTML = "";
return false;
}
else
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("variants").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "{{ url('/getVariants') }}"+'/'+master_id+'/'+sku, true);
xhttp.send();
}
Now I have `
<div class="column">
<div class="ui fluid image">
<div class="ui black ribbon label">
<i id="variants"></i> <!-- displaying variants -->
</div>
<img src="/images/wireframe/image.png">
</div>
</div>`
I dont want names to be displayed all in one tag...instead...for every echoed data I want new column element..How should I do that?
Any answer to this is much appreciable..

Instead of echoing each data you should put all the data in an object or an array and echo a json:
echo json_encode($data_array);
From the client side then you can get the answer and iterate it to put the content in different elements.
if (xhttp.readyState == 4 && xhttp.status == 200)
{
var jsonResponse = JSON.parse(xhttp.responseText);
var text = '';
for(var key in jsonResponse)
{
text += '<p>'+jsonResponse[key]+'</p>';
}
document.getElementById("variants").innerHTML = text;
}

Related

Parsing JSON Array to print specific elements

Im currently trying to parse JSON data from this api in JS but im not sure how to. As of right now when I press any buttons to give me the data, it prints the arrays out rather than the specific data I want. Ive tried to use the JSON Parse function to retrieve the specific data but it seems its not working. Any help would be greatly appreciated! URL to the API docs: https://www.balldontlie.io/#get-all-players
//Loads Player Data
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("players").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
var data = JSON.parse(xhttp.responseText);
console.log(data["last_name"])
xhttp.send();
}
//Loads Game Data
function loadGames() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("games").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/games", true);
xhttp.send();
}
//Loads Team Data
function loadTeams() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("teams").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/teams", true);
xhttp.send();
}
<!DOCTYPE html>
<html>
<body style="background-color:peachpuff;" >
<center>NBA STATS</center>
<center><marquee behavior="scroll" direction="right" scrollamount="12.5">Data Extracted From BDL API</marquee></center>
<center> View API Docs </center>
<script src="main.js"></script>
<div id="players">
<button type="button" onclick="loadPlayers()">View Players</button>
</div>
<div id = "teams" >
<button type="button2" onclick="loadTeams()">View Teams</button>
</div>
<div id ="games">
<button type="button3" onclick="loadGames()">View Games</button>
<div>
</body>
</html>
You should parse JSON in xhttp.onreadystatechange, that's a callback when request data success.
For the players data as example, it is an object with data and meta, and the players is in data key which is an Array, so you need to loop inside the array to print the values that you needed.
Here's the example for loadPlayers(). You can apply the same concept to loadGames and loadTeams, please let me know if you still having questions.
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// parse JSON after response
var players = JSON.parse(this.responseText);
// get 'data' key inside response
var playersData = players.data;
// loop all the players
for (var player of playersData) {
// print last_name to the #players element
document.getElementById("players").innerHTML += "<br />" + player['last_name'];
}
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
xhttp.send();
}
In function loadPlayers()
data is an array not object

How to parse json using ajax script in ESP32 app

I am working on a project using ESP32, I get some data from some sensors and send it to a webpage hosted in the same board.
I read some info on the web and understood that is "better" to send all data from several sensors using json method, so my function to get and send data is this:
void handle_leituras()
{
String results_json = "{ \"data\": " + Data +
"," + "\"hora\": " + Hora +
"," + "\"temp_amb1\": " + Tout + " }";
server.send(200, "application/json", results_json);
}
Testing above function in serial monitor I have this data:
{"data": Domingo, 12/4/2020,"hora": 20:53,"temp_amb1": 25.75}
I found a script that can get only one data and print it on that page, this is the script:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("DATA").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "leituras", true);
xhttp.send();
}
Its my index page code that shows data on webpage:
const char pag_inicial[] PROGMEM = R"=====(
<!DOCTYPE html>
<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">
<title>My 1st test</title></head>
<html>
<body>
<div id="pagina">
<h1>System XPTO</h1>
<div>
Data: <span id="DATA">ND</span><br>
Hora: <span id="HORA">ND</span><br>
Temperatura Ambiente: <span id="TEMPAMB1">ND</span>
</div>
<div id="botoes">
<button type="button" onclick="sendData(0)" style="width: 80px; height: 30px; margin: 30px;">ON</button>
<button type="button" onclick="sendData(1)" style="width: 80px; height: 30px; margin: 30px;">OFF</button><BR>
</div>
<script>
setInterval(function() {
// Call a function repetatively with 1 Second interval
getData();
}, 1000); //2000mSeconds update rate
//function to set on / off a LED on my board
function sendData(led) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("LEDState").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "setLED?LEDstate="+led, true);
xhttp.send();
}
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
</script>
</div>
</body>
</html>
)=====";
My problem is...I don't know how to modify this script to get more sensors values from the described above function.
Anybody can save me please?
Thanks in advance ;)
The standard XMLHttpRequest only supports responseText and responseXML, it does not support responseJSON property. However, as long as your server is sending a valid serialised JSON string, the responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse(), and then you can access each JSON element with dot notation:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
This piece of code works for all browsers that supports XMLHttpRequest and JSON as long as the server is sending a valid JSON object.

Do a javascript redirect after an ajax call

I'm trying to use ajax to parse data to be processed on a php page and have php echo a javascript redirect to another page but it is not working. I have read that js does not work after running an ajax call so I will like to know if there s a way around it. This is my code:
html
<form>
<div class="depart_time bottom_white w-40 ml-auto">
<p>Time</p>
<input type="time" name = "return_time" id = "rt">
</div>
<div class = "search_button r_search">
<button id = "r_search" onclick = "return false" onmousedown = "rent()">SEARCH</button>
</div>
</form>
ajax call is a normal xhttp request that gets sent to php for processing after which a redirection should occur:
if(isset($_POST['return_time'])){
echo '<script type="text/javascript">window.location.href="link.html"</script>';
}
Please an help is appreciated. I'm new to using ajax.
EDIT
the ajax code:
gid("r_search").addEventListener("mousedown", rent);
function rent(){
rt = gid('rt').value;
r_search = gid('r_search').value;
form_array = '&rt=' + rt +
'&r_search=' + r_search;
send_data = form_array;
ajax_data('app/rent.php', 'error', send_data);
//gid('error').innerHTML = send_data;
}
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
gid(getId).innerHTML = xhttpReq.responseText;
}
};
xhttpReq.send(send_data);
}
please note that 'gid' is for getelementbyid
You have to make bit alteration to your way of redirection.
First you need to make changes in your PHP response
if(isset($_POST['return_time'])){
...
// If you get your process success return 1
if(success) {
echo 1; die();
} else {
// else set some flag that you could get on your AJAX response
echo 0; die();
}
}
Now, get this flag on your AJAX and make changes to your below functions:
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if( xhttpReq.responseText == 1 ) window.location.href="URL where you wish to redirect page";
}
};
xhttpReq.send(send_data);
}
I've written this answer for others who come here for help.

Can someone help me parse value of element from nested JSON response. I want to display value or "priceInCents" on html page here is my script

Can someone help me parse the value of an element from nested JSON response. I want to display value or "priceInCents" on HTML page here is my script
<!DOCTYPE html>
<html>
<body>
<div id="demo1">
<h1>Product price</h1>
<button type="button" onclick="loadDoc1()">check price</button>
</div>
<script>
function loadDoc1() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("demo1").innerHTML = obj.results.price.priceInCents;
}
};
xhttp.open("GET", "http://search.mobile.walmart.com/search?query=329264833&store=148", true);
xhttp.send();
}
</script>
</body>
</html>
results is an array, so you have to specify that you want the first element of the array.
function loadDoc1() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("demo1").innerHTML = obj.results[0].price.priceInCents;
}
};
xhttp.open("GET", "https://search.mobile.walmart.com/search?query=329264833&store=148", true);
xhttp.send();
}
<div id="demo1">
<h1>Product price</h1>
<button type="button" onclick="loadDoc1()">check price</button>
</div>

Single ajax request to update 2 different <DIV>

Is it possible to update 2 different targeted DIV simultaneously using 1 ajax?
Let say I have index.html below:
<script>
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("main_body").innerHTML = xmlhttp.responseText;}
}
xmlhttp.open("GET","some_page.php",true);
xmlhttp.send();
</script>
<div id="main_body">
<div id="update_1"></div>
<div id="dont_ajax">A big size of html content....</div>
<div id="update_2"></div>
</div>
In above case, all I know is the some_page.php has to be written like below:
<php
echo "<div id="update_1"><h1>Apple</h1></div>
<div id="dont_ajax">A big size of html content....</div>
<div id="update_2"><h1>Orange</h1></div>";
?>
I don't want the some_page.php to load the content of id="dont_ajax" due to its large html content. I am looking for some kind of solution like:
<script>
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("update_1").innerHTML = xmlhttp.responseText(1);
document.getElementById("update_2").innerHTML = xmlhttp.responseText(2);}
}
xmlhttp.open("GET","some_page.php",true);
xmlhttp.send();
</script>
<div id="main_body">
<div id="update_1"></div>
<div id="dont_ajax">A big size of html content....</div>
<div id="update_2"></div>
</div>
so that the some_page.php can be as simple as:
<php
echo "<h1>Apple</h1>"; //(become respondtext(1))
echo "<h1>Orange</h1>"; //(become respondtext(2))
?>
I know my example above won't work, I just want to show you the problem and what I want to achieve. Pls give me some ideas, thanks. Or if u have other way to achieve this, pls suggest.
I need solution in native JS.
Yes, it's possible. You can update any number of elements.
It depends on the way you're preparing and parsing your response.
This code is awful as ajax response has only one responseText:
<php
echo "<h1>Apple</h1>"; //(become respondtext(1))
echo "<h1>Orange</h1>"; //(become respondtext(2))
?>
You'll receive <h1>Apple</h1><h1>Orange</h1> in the response and you'll produce more ugly code trying to split it in parts.
The best solution is preparing JSON string:
<php
echo "{update_1: '<h1>Apple</h1>', update_2: '<h1>Orange</h1>'}";
?>
Then parsing the response and updating the document:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
['update_1', 'update_2'].forEach(function(i){
document.getElementById(i).innerHTML = data[i];
});
}

Categories