how to print or echo JSON.stringify data i php - javascript

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.

Related

Jquery-ajax doesn't succeed

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).

Javascript AJAX request - check for success action

I have a Javascript that is called from a button which makes an HTTP GET request. At the moment when it encounters an error it shows a hidden div with the request error, which is all working well. Here's the script:
$("#callContact1").click(function() {
console.log('starting event');
$.ajax({
url: "<?php echo $eventURL ;?>" + eventID + "<?php echo $eventURL ;?>",
data: {},
type: "GET"
})
.then(function(data, status, xhr) {
$('#ajaxResponse1').html(data).show();
var httpStatus = status;
var httpResponseCode = (xhr.status);
console.log('httpStatus: ' + httpStatus);
console.log('httpResponseCode: ' + httpResponseCode);
})
.fail(function(xhr) {
var httpStatus = (xhr.status);
var httpResponseCode = (xhr.getAllResponseHeaders);
var ajaxError = 'There was an requesting the event. HTTP Status: ' + httpStatus;
console.log('httpStatus: ' + httpStatus);
console.log('httpResponseCode: ' + httpResponseCode);
//make alert visible
$('#ajaxResponse1').html(ajaxError).show();
})
})
I now need to extend this slightly to, when it is successful, show a different hidden div with a success message, e.g.:
$('#ajaxResponseSuccess1').html('Event Update in Progress').show();
I'm just not sure how to extend this script - fairly new to JS and jQuery at this point.
There is a success function in JQuery AJAX:
Use it like so:
.success(function(response) {
//DO stuff here.
})
A better simpler code can be like:
$.ajax({
url: 'http://example.com',
method: 'GET',
success: function (response) {
},
error: function (e) {
}
});
View the full documentation of JQuery ajax functions is at
http://api.jquery.com/jquery.ajax/
OR at
https://www.w3schools.com/jquery/ajax_ajax.asp
$.ajax({
url: "<?php echo $eventURL ;?>" + eventID + "<?php echo $eventURL ;?>",
data: {},
type: "GET",
success : function(data)
{
$('#ajaxResponseSuccess1').html('Event Update in Progress').show();
},
error:function(xhr,status)
{
alert(xhr.statusText);
}
});
Using short form of ajax:
$.get("www.xyz.com/abc",{eventId: eventId},callbackFunction);
You are registering two callbacks with the Ajax call. You seem to know that fail is executed on error. That leaves that the .then callback is executed on success. Just add the call there:
.then(function(data, status, xhr) {
$('#ajaxResponse1').html(data).show();
$('#ajaxResponseSuccess1').html('Event Update in Progress').show(); // <--
// ...
})

How to get json data from url with Cordova?

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
})

How to correctly post data with ajax into 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
});
}

accessing variables outside ajax

I have the following code:
var src, flickrImages = [];
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
}
});
// undefined returned here for flickrImages
map.setZoom(13);
map.setCenter(new google.maps.LatLng(xmlLat,xmlLng));
infowindow.setContent('<strong>' + xmlTitle + '</strong><br>' + xmlExcerpt + '<br><br>' + flickrImages.join(''));
infowindow.open(map,this);
I am trying to access flickrImages variable outside the ajax so I am able to put it inside a infowindow for google maps. Unfortunately outside the ajax it returns undefined.
I tried moving the flickr things into the ajax but unfortunately it then loses some of the other information such as xmlTitle and xmlExcerpt.
Any help is much appreciated.
Thanks in advance,
Dave.
The reason why flickrImages is undefined where your comment is, is because the call to $.ajax is asynchronous, which means it does not block until your request completes.
That's why there is a success function that gets "called back" when the underlying HTTP request completes. So, you need to handle your flickrImages variable from your success function, or alternatively, from your success function, pass flickrImages to some other function which does your processing.
The ajax call is asynchronous, so it won't wait around for an answer - it will just go ahead and run the rest of the script. Passing async:false in the settings (see http://api.jquery.com/jQuery.ajax/) should solve your problem, though it will make it a lot slower as the script will have to wait for the ajax call to return.
It would be neater for the rest of the script to be called from the success callback as you tried to do - how is it that xmlTitle and xmlExcerpt are unavailable there?
Define a global variable outside of your ajax call and assign it a value
var myData
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
myData = data
myFunction()
}
});
As said by Karl Agius a "The ajax call is asynchronous". For this you just have to add
async: false,
to your ajax request. Here is you code looks after adding this:
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
async: false,
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
}
});
But its not a good practice to stop asynchronous in ajax call. But will work for you. Use Ajax callback on success instead (check here).
Here is another option. You create a function that return an ajax call like this.
function flickrImages (){
return $.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json"
});
}
Then on your code somewhere, you call this function an retrieve the success or in my case the .done() function like this
var result= flickrImages ();
flickrImages = [];
result.done(function(data){
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
});
console.log (flickrImages);

Categories