How to parse data from external API into HTML using AJAX - php

I'm new to wordpress and I have little coding knowledge.I wanted to get few data from external API and display those data in my wordpress site html area.
here is external API: https://www.hpb.health.gov.lk/api/get-current-statistical
API contains lot of details.I dont want all of them.I just need 4,5 of them..
(eg:local_new_cases,update_date_time,local_total_cases,local_deaths,local_recovered)
here is the details :https://www.hpb.health.gov.lk/en/api-documentation
here is external web site :https://www.hpb.health.gov.lk/en
I created some code by using stackoverflow,but I don't know how to parse few data into my html area.some tutorial teaching button event.I'dont want button click event.
I have created below code:(It means ,I took data from API )
var data;
$( document ).ready(function() {
getHealthData();
});
/**
*Gets data from API
**/
function getHealthData(){
$.ajax({
type : "GET",
dataType : "json",
url : "https://www.hpb.health.gov.lk/api/get-current-statistical",
data : {action: "get_data"},
success: function(response) {
alert(response);
data= response.data;
}
});
}
Now I want to parse few data(eg:local_new_cases,update_date_time,local_total_cases,local_deaths,local_recovered) from API, into html code.
How to do that? please help me to save my life.Thank you.

You can get data using response.data and get respective value using value['something'] like below :
var data = "";
$(document).ready(function() {
getHealthData();
});
/**
*Gets data from API
**/
function getHealthData() {
$.ajax({
type: "GET",
dataType: "json",
url: "https://www.hpb.health.gov.lk/api/get-current-statistical",
data: {
action: "get_data"
},
success: function(response) {
//getting value from server
var value = response.data;
data = "local_total_cases : " + value['local_total_cases'] + "<br/>local_deaths : " + value['local_deaths'] + "<br/>local_new_deaths : " + value['local_new_deaths'] + "<br/>local_recovered : " + value['local_recovered'] + "<br/>local_new_cases : " + value['local_new_cases'];
//putting values in div with id="data"
$("#data").html(data);
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="data">
</div>
Update 1 :
Here in below code i have added some html tag ,you can add more tag to your data like below and do changes as per your requirement
var data = "";
$(document).ready(function() {
getHealthData();
});
/**
*Gets data from API
**/
function getHealthData() {
$.ajax({
type: "GET",
dataType: "json",
url: "https://www.hpb.health.gov.lk/api/get-current-statistical",
data: {
action: "get_data"
},
success: function(response) {
//getting value from server
var value = response.data;
data = "<h5>local_total_cases :</h5><b>" + value['local_total_cases'] + "</b><br/><h5>local_deaths :</h5><b> " + value['local_deaths'] + "</b><br/><h5> local_new_deaths : </h5><b>" + value['local_new_deaths'] + "</b><br/><h5>local_recovered : </h5> <b>" + value['local_recovered'] + "</b><br/><h5>local_new_cases :</h5> <b>" + value['local_new_cases']+"</b>";
//putting values in div with id="data"
$("#data").html(data);
//adding value separately
$("#something").text("local_total_cases :" + value['local_total_cases'])
}
});
}
h5{
font-size:20px;
color:blue;
}
b{
font-size:25px;
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div id="data">
</div>
<h3 id="something"></h3>

Related

How to display tree view using AJAX php

I am trying display data from database based on parent in tree view using AJAX PHP.
I have followed below example .
https://www.w3schools.com/howto/howto_js_treeview.asp
It is working .but after expanding it is not closing .
Here is my script
$(document).ready(function() {
//$(".parent").click(function(){
$(document).on("click", ".box" , function() {
var comp = $(this).text();
const myArray = comp.split("(");
var compnumber=myArray[0];
var model=decodeURIComponent(compnumber);
//alert(part);
if(compnumber){
$.ajax({
url:"ajax_getBomLineDetailsInfo.php",
type : "POST",
data: {
// func:'getdowntimeline',
compnumber: compnumber
},
dataType : "json",
success:function(response)
{
//alert('success');
if(response){
var len = response.length;
// $(".sub").empty();
$('.' + model).empty();
// $(".sub").prepend("");
for( var i = 0; i'"+PartNumber+"'");
var part=decodeURIComponent(PartNumber);
// var test='123';
$('.' + model).append(""+PartNumber+"");
}
//$(".sub").append("");
//$(".GSX130181").show();
//$('.' + model).addClass('active');
//$(this).toggleClass('box check-box');
//$(this).toggle();
// childclick();
//$(".child").show();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
}
});
}
else{
}
});
});
I am getting box class text values on click and getting child values for that text using ajax and appending as li .I need to execute the javascript code in the https://www.w3schools.com/howto/howto_js_treeview.asp in above script .but it is not working .
How to fix the issue ?

sending already used variable via ajax

I'm using jquery datepicker on a page. Next to datepicker i have a section which will show events on mouseenter of the datepicker. I have figured out a way to get the date into the header of this section. The problem i am having is getting that variable over to the php page that will be displayed on mousenter.
Below is the page that the datepicker and events will be shown:
<div id=events>
<div id=eventcontent>
</div>
</div>
<div id=eventsheading>
<div id=headingcontent>
</div>
</div>
<div id = "datepicker">
</div>
This is the Jquery i am using to fill in the header with the date (which works), send the same variable to events.php (which doesnt work), and show events.php in the content div (which does work as when i highlight a date, hello is shown):
$(document).on('mouseenter', '.ui-datepicker-calendar .ui-state-hover', function(e){
var daynum1 = $(this).text();
var month1 = $('.ui-datepicker-month').text();
var year1 = $('.ui-datepicker-year').text();
var Date = daynum1 + " " + month1 + " " + year1;
$('#headingcontent').html(Date);
//ajax call with date information
var request = $.ajax({
url: "events.php",
type: "POST",
data: {Date: Date},
dataType: "html"
});
$.ajax({
url: "events.php",
cache: false,
success: function(html){
$("#eventcontent").append(html);
}
});
});
Below is events.php:
if(isset($_POST['Date']))
{
$date = $_POST['Date'];
echo <<<_END
<p>$date</p>
_END;
}
else
{
echo <<<_END
<p>hello!</p>
_END;
}
once i get this bit working, events PHP will be changed to select events from mysql.
To clarify, the problem i am having is getting variable date to send via ajax with this code:
//ajax call with date information
var request = $.ajax({
url: "events.php",
type: "POST",
data: {Date: Date},
dataType: "html"
});
i cant seem to find anywhere that explains how data: {...}, should be used and I'm guessing this is my problem.
Sorry if the code is just completely wrong i'm very new to learning it all and thanks for any help.
you must not use variable names which collide with inbuilt objects as #CBroe said.
and rest like this
var myDate = daynum1 + " " + month1 + " " + year1;
$('#headingcontent').html(myDate);
$.ajax({
url: "events.php",
type: "POST",
data: {myDate: myDate},
dataType: "html",
success: function(html){
$("#eventcontent").empty();
$("#eventcontent").append(html);
}
});
no need for second ajax call

JQuery + ajax + json fail to show response

I'm trying to do something like user click on button, it sends request to json, and i want it shows the response of json, but i have some errors that i can't figure it out how to solve it.
HTML:
<a class="backLink" id="target_button" onclick="insertText('target_', 'AA', 'NN')"><div class="fa fa-external-link"></div>Show</a>
JS + ajax:
<script type="text/javascript">
function insertText(elemID, text, text2) {
$.ajax({
url: "https://myserver.com/jsons.php?request=getTargets&tar="text"&bar="text2"",
beforeSend: function (xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
})
.done(function (data) {
if (console && console.log) {
console.log(data);
var getValue = $("#" + elemID).val() == "" ? data : "";
$("#" + elemID).val(getValue);
}
});
}
</script>
I'm not sure if im doing it in the better way.
It is something simple. User click on button, call the function with that parameters, make a request to json , receive answer and display it on the elemID.
Thanks
EDIT:
changes i made
<script>
console.log('called');
function insertText(elemID, product, country) {
"use strict";
console.log('called2');
$.ajax({
url: 'https://myserver.com/jsons.php?request=Targ&country=" + country + "&product=" + product +".",
beforeSend: function (xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
})
.done(function (data) {
if (console && console.log) {
console.log(data);
}
});
console.log('called3');
}
console.log('called4');
</script>
result on console:
called
called4
it looks like i can't enter on function
Write console.log('called'); in your insertText() function right before the line contains $.ajax({
So you can see the function is called on click or not.
If the Console tab of the Developer Tools throws JavaScript errors, this could brake further JavaScript execution too.
Replace your double quotes with single quote.
URL should be
url: 'https://myserver.com/jsons.php?request=getTargets&tar='+ text +'&bar='+ text2
How I did it:
<script type="text/javascript">
function insertText(elemID, p, c) {
var server = window.location.hostname;
$.ajax({
url: "https://" + server + "/jsons.php?request=Target&c=" + c + "&p=" + p +"",
beforeSend: function (xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
})
.done(function (data) {
console.log(data)
var tmp = data.replace('"',"");
var tmp2 = tmp.trim();
var getValue = $("#" + elemID).val() == "" ? tmp2 : "";
$("#" + elemID).val(getValue);
});
}
</script>
HTML:
<a id="t_button" onclick="insertText('t_d', '<?php $c ?>', '<?php $p ?>');" > show</a>
Hope it helps someone another !

jQuery Ajax is not Working what is the Issue

jQuery for Updating Database table entry using PHP. after ajax code is not working for me please help.
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var allottedValue = $(this).parent().find('input').val();
alert('Row id = ' + rowID + ' Enrollment no = ' + allottedValue);
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
// After this line it is not working
$.ajax({
type: "POST",
url: "request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
$(this).parents(".success1").replaceWith(html);
}
});
//$(this).parents(".success1").animate({backgroundColor: "#003"}, "slow").animate({opacity: "hide"}, "slow");
});
// HTML to Show Multiple Inputbox for multiple upload with link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dynamic-table">
<div class="success1">
<input name="enrollNo" type="text" value="" class="postEnroll"/>
<br/>
Allot Enrollment No
</div>
</div>
You are trying to replace with parent, it must be child. Use below code
success: function (html) {
$("#dynamic-table .success1").replaceWith(html);
}
OR
success: function (html) {
$("#dynamic-table").find(".success1").replaceWith(html);
}
This code works great i have used similar.... try this one..
function FormSubmit() {
$.ajax(
type: "POST",
url: 'success1.php',
data: $("#attend_data").serialize(),
async: false
}).done(function( data ) {
$("#attend_response").html(data);
});
}
I have updated your code snippet below... tested offline and the code is working:
A few pointers:
Instead of this: request/allot_enrollmentNo_gov.php
Try this: /request/allot_enrollmentNo_gov.php
Notice the forward slash ( / ) This indicate that the Ajax path must start from the root directory depending on your server settings.
Use this: $(".success1").html(html); instead of $(this).parents(".success1").replaceWith(html);
Working code below:
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var allottedValue = $(this).parent().find('input').val();
alert('Row id = ' + rowID + ' Enrollment no = ' + allottedValue);
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
// After this line it is not working
$.ajax({
type: "POST",
url: "/request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
$(".success1").html(html);
alert('Response from the POST page = ' + html + ');
}
});
//$(this).parents(".success1").animate({backgroundColor: "#003"}, "slow").animate({opacity: "hide"}, "slow");
});
// HTML to Show Multiple Inputbox for multiple upload with link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dynamic-table">
<div class="success1">
<input name="enrollNo" type="text" value="" class="postEnroll"/>
<br/>
Allot Enrollment No
</div>
</div>
Now it is working Perfectly by setting parent:
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var rowParent = $(this).parent('.success1');
var allottedValue = rowParent.find('input').val();
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
$.ajax({
type: "POST",
url: "request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
rowParent.replaceWith(html);
}
});
return false;
});

jQuery lightbox from database through PHP/Ajax forces to double click the first time

It's a weird issue. I've to click on certain buttons (having some ids). The id is passed through Ajax in a PHP script. That id is searched in the database, and the matching entries are passed as data in which is shown in my jQuery lightbox. However, I have to double-click on the button for the first time.
My HTML structure is as follows:
<div class="boxes">
Show it
</div>
<div class="boxes">
Show it
</div>
And the Javascript function is:
$('.button').click( function() {
$.ajax({
type: 'POST',
url: 'functions/db.php',
data: {id: this.id},
dataType: 'json'
}).done(function(data) {
$('#'+data[0]).avgrund({
//data [0] is both the id being clicked and that stored in the database
height: 200,
holderClass: 'custom',
showClose: true,
template: '<p>'+data[2]+'</p>' +
'<div>' +
''+data[0]+'' +
''+data[1]+'' +
'More' +
'</div>'
});
});
});
My relevant PHP script:
$id = $_POST['id'];
$result = mysql_query("SELECT * FROM `eventdetails` WHERE `id` = '".$id."'");
$array = mysql_fetch_row($result);
echo json_encode($array);
I'm running the files on an XAMPP server on Windows 7. Is it normal that I've to double click for the first time? How can I improve it?
EDIT #1
One of the users suggested of using success instead of done in Ajax. Still, it requires a double-click. Here's the javascript code using success in Ajax.
$('.button').click( function() {
$.ajax({
type: 'POST',
url: 'functions/db.php',
data: {id: this.id},
dataType: 'json',
success:(function(data) {
$('#'+data[0]).avgrund({
height: 200,
holderClass: 'custom',
showClose: true,
template: '<p>'+data[2]+'</p>' +
'<div>' +
''+data[0]+'' +
''+data[1]+'' +
'More' +
'</div>'
});
})
});
});
to init avgrund with ajax data set its special param called "openOnEvent" to "false"
it will look like
$.ajax({
type: 'POST',
url: 'testpost.php',
dataType: 'json',
data: { id: this.id },
success: function(id) {
$('#' + id).avgrund({
openOnEvent: false,
height: 200,
template: '<p>content <b>' + id + '</b> here!</p>'
});
}
});
docs - https://github.com/voronianski/jquery.avgrund.js#update-sep-30-2012
test page - http://labs.voronianski.com/test/test-avgrund.html

Categories