I'm learning Javascript and JSON at the moment but really confused by it all.
I'm trying to extract data from a JSON array, I've got to this point
$(function(){
var $reviews = $('#reviews');
$.ajax({
type: 'GET',
url: "https://api.feefo.com/api/10/reviews/all?merchant_identifier=pub-insurance-4u-co-uk&fields=reviews.service.rating.rating,reviews.service.review,reviews.customer.display_name",
success: function(reviews) {
$.each(reviews, function(i, review) {
$reviews.append('<li>name: '+ review.display_name +', review: '+ review.review + ', rating: '+ review.rating + '</li>');
});
}
});
});
I can't seem to get much further at the moment. I've read about JSON.parse(), perhaps that is what I need. Any help / advice GREATLY appreciated thanks!
$(function(){
var $reviews = $('#reviews');
$.ajax({
type: 'GET',
url: "https://api.feefo.com/api/10/reviews/all?merchant_identifier=pub-insurance-4u-co-uk&fields=reviews.service.rating.rating,reviews.service.review,reviews.customer.display_name",
success: function(reviews) {
//console.log(reviews);
$.each(reviews.reviews, function(i, review) {
$reviews.append('<li>name: '+ review.customer.display_name +', review: '+ review.service.review + ', rating: '+ review.service.rating.rating + '</li>');
});
}
});
});
It is helpful to log the object and take a look at it in the console. Then you can see the structure and print what you like.
That's what I did :)
Here is a screenshot:
And here is the fiddle:
Fiddle
Related
I am quite new to to ajax, just learning it, and made a simple page on localhost to test gets and posts from/to json file in the same folder.
While GET is working smoothly, I cannot figure out, why post doesn't happen if I click the button I assigned this function to.
Pls take a look into my code and help.
element = $("#mylist");
var item2 = $("#mytable");
$.ajax({
type: "GET",
url: "data.json",
success: function(response) {
$.each(response, function(i, item) {
element.append("<li>" + item.fname + " " + item.lname + "</li>");
item2.append("<tr><td>" + item.lname + "</td>" + "<td>" + item.fname + "</td></tr>");
});
},
error: function() {
alert("error");
}
});
$("#additem").on('click', function() {
var $fname = $("#fname");
var $lname = $("#lname");
var $city = $("#city");
var order = {
fname: $fname.val(),
lname: $lname.val(),
city: $city.val()
};
console.log(order);
$.ajax({
type: "POST",
url: "data.json",
data: order,
succes: function() {
console.log("succes");
},
error: function() {
console.log("no success");
}
});
});
JSFiddle
The problem is you are trying to post to a .json file, like Patrick Evans says in the comments. You need to do the post to a script, in PHP you could do something like this:
$order = $_POST['order'];
// Do something with order...
echo $order; // or echo success message
Of course for this to work you will need PHP to be running on your server (localhost).
I started to develop an app with Cordova for android and I'm now searching around google for a solution(Whitelist) to get the JSON data from the URL.But I cannot find a simple tutorial. Most of the tutorials I found are not so beginner friendly. I'm thinking about trying to get the JSON data with pure javascript, but I think it's not a good idea. Are there some simple tips or tutorial that can solve this problem? I love to hear from you!
Like this? Assuming that hello.php returns your JSON data.
$.ajax({
url: "yourwebsite.com/hello.php",
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getdata(arr);
},
error: function () {
validationMsg();
}
});
function _getdata(arr){
//your JSON resuls are now in arr. Do what you need with the array.
}
This example could be very helpful.
You should try ajax calls in order to fetch data from the server, jQuery makes it very easy. Here is the function used in the example that loads the data from the server :
function getEmployeeList() {
$('#busy').show();
$.getJSON(serviceURL + 'getemployees.php', function(data) {
$('#busy').hide();
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
I hope it help.
fetch('/echo/json', {
method: 'get'
}).then((JSONresponse) => {
// do whatever you want with your
// JSONresponse here
})
i am trying to fetch google contact list using contact api. i got the result and its showing in chrome and firefox console. i want to print the data in php. on the same page
<script type="text/javascript">
function auth() {
var config = {
'client_id': 'xxxxxxxxxxxxxxxxxxxxx',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json",
dataType: "jsonp",
success:function(data) {
//alert(JSON.stringify(data));
// display all your data in console
console.log(JSON.stringify(data));
}
});
}
</script>
i tried ajax but not worked. is there any best way to do it. JSON.stringify(data) is a array
You have nothing to do with PHP here. You are receiving a callback from $.ajax and the only way to show that data on ur page is to use JavaScript/jQuery.
See example below on how to parse $.ajax callback and .append() the data to some element on ur page:
<div id="contacts"></div>
function fetch(token) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json",
dataType: "jsonp",
success:function(data) {
$.each(data.feed.entry,function(){
$('#contacts').append('<div>Name: ' + this.title.$t + ' Phone: ' + this.gd$phoneNumber[0].$t + '</div>');
console.log('Name: ' + this.title.$t + ' Phone: ' + this.gd$phoneNumber[0].$t);
});
}
});
}
Note: if You need to parse ur data with PHP then You have to use curl.
How can I fix the code below to read the IsPublic data in the xml file and when IsPublic is equal to 1 ...print the Name and Url... else do nothing.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(xml) {
$(xml).find("Form").each(function (if "$this.IsPublic"==1) {
$("#container").append('<div>' +
$(this).find("Name").text() + '<br/>' +
$(this).find("Url").text() +
'</div>');
}else{});
}
</script>
//Example data in data.xml
<?xml version="1.0" encoding="UTF-8"?>
<Forms>
<Form>
<Name>BRIO Tuscan Grille</Name>
<Description>Event descript Hosts: Persons name </Description>
<RedirectMessage>Great! Thanks for filling out my form!</RedirectMessage>
<Url>brio-tuscan-grille</Url>
<Email>email#email.com</Email>
<IsPublic>1</IsPublic>
<Language>english</Language>
</Form>
</Forms>
Your code have some syntax errors. When you fix them, it would be look like this:
function xmlParser(xml) {
$("Form", xml).each(function () {
if ($("IsPublic", xml).text()==1) {
$("#container").append('<div>' +
$(this).find("Name").text() + '<br/>' +
$(this).find("Url").text() +
'</div>');
};
});
};
http://jsfiddle.net/sKy4k/
Kreozot, you were very close and gave me the direction I needed Thx.
the only problem was IsPublic wasn't actually reading the individual items.
I jumped over to your jsfiddle link and came up with this and it seems to work now.
Thanks again!
function xmlParser(xml) {
$("Form", xml).each(function () {
if ($(this).find("IsPublic").text()==1) {
$("#container").append('<div>' +
$(this).find("Name").text() + '<br/>' +
$(this).find("Url").text() +
'</div>');
};
});
};
Script:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
$.load("#BuildedBox")
}
});
}
build.php:
include_once("$_SERVER[DOCUMENT_ROOT]/db.php");
$block_id = $_GET['block'];
$building = $_GET['building'];
$nick = $_GET['nick'];
echo"$block_id - $building - $nick";
index.php:
<a href=\"#\" onClick=\"buttonBuild(k152, digger, Name);\" >[BUILD]</a>
<div id="BuildedBox"></div>
seems my script wont work. what i have done wrong?
check this out
function buttonBuild(id, building, nick)
{
$.ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
/***************/
$("#BuildedBox").html(response);
/***************/
}
});
}
var weightd = $("#weight").val();
var user_id = 43;
$.ajax({
type: "POST",
url:"<?php bloginfo('template_directory')?>/ajax/insert.php",
data: { weight:weightd,user_ids:user_id},
success:function(result){
$("#result1").html(result);
});
<div id="result1">Result div</div>
change $.load("#BuildedBox") to $("#BulderBox").html(response).
When you ask the script for data via ajax, the data provided gets into the "response" variable. As you want to write this data into the div, you must use the ".html" method.
Easier using "load" in this way:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php?block_id=" + id + "&building=" + building + "&nick=" + nick);
}
The "load" method loads data from the server and writes the result html into the element: https://api.jquery.com/load/
EDIT:
As #a-wolff says in the comment, to use POST in load, you should construct like this:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php",{
block_id:id,
building:building,
nick:nick
});
}