Whats the JQuery equivalent to the following PHP code? (JSON) - php

I got the following code in PHP:
<?php
$json = file_get_contents('https://graph.facebook.com/192655950766049');
$data = json_decode($json, true);
echo $data['description'];
?>
and I want the equivalent code in JQuery.
I tried to do it myself but I had no luck.
Here's one of my many tries:
<script type="text/javascript" src="../scripts/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$.getJSON("https://graph.facebook.com/192655950766049", function(json) {
alert("JSON Data: " + json.description);
});
</script>
I read the explanation from http://api.jquery.com/jQuery.getJSON/, but yet I dont really understand it..
anyway, if you can help me it'll be very nice!
Thanks

You're violating the Same origin policy by requesting a different domain with Javascript. You'll need to do this server side (i.e. with PHP in your case).

You need to use jquery's jsonp request. See this short discussion on how to interface with facebook using this. JSONP allows for XSS ignoring the same origin policy.
Basically your code would then look similar to this:
<script type="text/javascript" src="../scripts/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$.getJSON("https://graph.facebook.com/192655950766049?callback=?", function(json) {
alert("JSON Data: " + json.description);
});
</script>

You won't be able to directly download data from facebook on the client side due to cross site scripting limitations.

$(document).ready(function(){
var url = "https://graph.facebook.com/192655950766049?limit=3&callback=?";
$.getJSON(url,function(json){
var html = "<ul>";
$.each(json.data,function(i,fb){
html += "<li>" + fb.message + "</li>";
});
html += "</ul>";
$('.facebookfeed').html(html);
});
});
You can also check this url.
http://www.prettyklicks.com/blog/making-a-facebook-feed-using-the-graph-api-json-and-jquery/291/
Also check this link using the same method as i have specified.
using $.getJSON within a loop

In the event anyone is interested in using jquery locally IE: WAMP, here is a tested example.. The z.txt file it is reading has a simple single number in it..
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("z.txt", function(json) {
alert(json);
});
});
</script>

Related

Getting output of PHP script using JQuery

I am trying to load the output of a PHP script into a using JavaScript and JQuery. The JavaScript function I am using uses the $.get function in JQuery to call a php script, which I want to display in another division. The script I wrote is:
<script type="text/javascript">
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("uname").html(data);
});
});
}
</script>
The PHP script (dbtest.php) uses a simple echo statement:
echo "hello, world!!!";
I am getting the first alert here, but not the second. What Can I be doing wrong here?
I suppose uname is a ID, in that case you should use:
$("#uname").html(data);
You can add this to your php for debugging:
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors", 1);
Try also to remove http:// from your ajax call and use relative path instead.
The guys below pointed out that the selector is wrong. Indeed that's a problem, but I think that the real issue is that you don't get the second alert. Probably your php file localhost/dbtest.php is not accessible. What happen if you open localhost/dbtest.php in a new tab?
I think the problem is the path to your dbtest.php file. You are saying you seecond alert will not be displayed so your request must be wrong.
Try to copy your page into the same folder like dbtest.php open the page in your browser with http://localhost/yourfile.php
If this does not display both alert-boxes try the same with an open developer console (Chrome/IE = F12) and look if there are errors.
You say you are trying to make ajax requests to your localhost from a Phonegap application. Phonegap prevents making ajax requests to other domains by default. You must add localhost to whitelist. Here is more detail: http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html
Here you have a working example:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div id="uname"></div>
<script>
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("#uname").html(data);
});
});
}
on_load();
</script>
Beware of the same-origin-policy. The page loading dbtest.php must be from the same origin, unless you grant other origins by adding a header from dbtest.php.
Try add some error handling to your code to better see what´s happening.
<script type="text/javascript">
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("uname").html(data);
}).fail(function () {
alert("failed");
});
});
}
</script>

Response from Server using Jquery and Ajax

im having a problem with getting any response from my server using Jquery and Ajax.
Server side:
$data = strtotime("now");
echo $data; // $data
Client side:
html code...
<script type="text/javascript" src=".../modjpicker2.js"></script>
</body>
</html>
modjpicker2.js:
$(function() {
$.ajax({
type: "GET",
url: "ajaxtime",
data: "{}",
success: function(response) {
var currentTime = new Date();
}
});
});
And var currentTime is just not being created... Some how request doesn't go through...
Forgot to note that jQuery is working fine all scripts are attached in header and php is working good as well, link ajaxtime is live also.
In your html
<script type="text/javascript" src=".../modjpicker2.js"></script>
It should be
<script type="text/javascript" src="../modjpicker2.js"></script>
I had kind of the same problem: My servers responses won't get handled by jQuery or JavaScript. It seems that nothing were transmitted.
I solved the issue by enabling HTTP access control on my server( More here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)
Here's my solution:
jQuery client won't accept my server responses
Hope I can help! Let me know if it worked

JQuery / PHP call with AJAX not working

I've been trying to get this really simple example of using AJAX with JQuery and PHP to work with no luck (here's the page for the sample). I've had a look at quite a few posts with similar discriptions and none have helped...
I've copied the code exactly but my function that should be run on success is never called. As an experiment, in the call to $.post I commented out the data part ({sendValue:str}) and the JSON part and added an alert into the body of the success function to see if it was called and it was. So I'm guessing there's something wrong with how I've created my data? I also tried to display the data returned from the AJAX call in the alert and it came out as 'undeclared' (data.returnValue).
This is a copy of my code, you can see the full example via the link above and also a working example from the author of the tutorial here: http://www.devirtuoso.com/Examples/jQuery-Ajax/
JQuery:
$(document).ready(function(){
$('#txtValue').keyup(function(){
sendValue($(this).val());
});
});
function sendValue(str){
$.post("ajax.php",
{ sendValue: str },
function(data){
$('#display').html(data.returnValue);
},
"json"
);
}
PHP:
<?php
//Get Post Variables. The name is the same as
//what was in the object that was sent in the jQuery
if (isset($_POST['sendValue'])){
$value = $_POST['sendValue'];
}else{
$value = "";
}
//Because we want to use json, we have to place things in an array and encode it for json.
//This will give us a nice javascript object on the front side.
echo json_encode(array("returnValue"=>"This is returned from PHP : ".$value));
?>
HTML:
<body>
<p>On keyup this text box sends a request to PHP and a value is returned.</p>
<label for="txtValue">Enter a value : </label><input type="text" name="txtValue" value="" id="txtValue">
<div id="display"></div>
</body>
Thanks!
EDIT:
I rewrote my $.post into a $.ajax with an error function in it. I'm definitely hitting the error function and the error is a parse error - I'm guessing it's coming from my PHP script when I call json_encode... here's a screenshot from firebug - anyone got any more ideas?:
Screenshot 1 - firebug console
Screenshot 2 - firebug watch window
Thanks for all the help so far by the way, really appreciate it.
I noticed that var str = $('#txt').val(); would give you an error because $('#txt') does not exist, it should be $('#txtValue').
After looking at your code, everything looks as it should, my next step would be trying to debug your code by using some console.debug() in JavaScript and some echo in PHP. I recommend you get Firebug for Chrome/Firefox and if using IE upgrade to IE9 and use their developer tools. Using the mentioned tools will give you a better idea of how your code is executing.
My first step would be to make sure that the keyup is firing:
$(document).ready(function(){
$('#txtValue').keyup(function(){
alert('keyUp');
sendValue($(this).val());
});
});
Second step would be to make sure sendValue is firing:
function sendValue() {
alert('sendValue');
var str = $('#txt').val();
tmr = null;
$.post(
'test.php',
{ sendValue: str },
function(data) {
alert('inside post');
$('#output').html(data.returnValue);
},
'json'
);
}
Without seeing more of what your various elements are outputting, I don't think I can tell you what to fix, but this example is similar to yours (although it's an all-in-one PHP file rather than two, as in your example). I also added a 350ms timeout to allow the user to type without having the page do an AJAX request every keystroke. As soon as they pause, it'll fetch the data.
Source to test.php
<?php
if(isset($_POST['sendValue']))
{
echo json_encode(
array('returnValue' =>
'Returned: ' . $_POST['sendValue']));
exit();
}
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX Sample</title>
</head>
<body>
<input type="text" id="txt" />
<div id="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
var tmr = null;
$(function () {
$('#txt').keyup(function() {
if(tmr != null)
clearTimeout(tmr);
tmr = setTimeout("sendValue()", 350);
});
});
function sendValue() {
var str = $('#txt').val();
tmr = null;
$.post(
'test.php',
{ sendValue: str },
function(data) {
$('#output').html(data.returnValue);
},
'json'
);
}
</script>
</body>
</html>
To anyone who gets here looking for an answer to a similar question:
I tried a few things to figure out what was going on, debugging the messages etc and everything looked fine. I then deployed my code to a virtual box running apache and to my web server to see if it was an environmental thing. My code worked on my web server and on the virtual box. I then realised that I had two conflicting installs of PHP on my dev system. I'm not sure why but this was causing the problem but rolling them both back and reinstalling WAMP on the dev system did the trick.
try this
$(document).ready(function(){
$('#txtValue').keyup(function(){
$.post("ajax.php",{ sendValue: str }, function(data){
$('#display').html(data.returnValue);
},
"json"
);
});
});

Modify html via php

Hello I'm doing this to add a string after a div in an html page with jquery:
Prepend items
<script type="text/javascript">
function PrependItemsToList()
{
$("#content_gallery").prepend($("<li></li>").text("prepend() item"));
}
</script>
Now I need to do it server side, any idea on how to implement it in php? I found phpquery but didn't find good docs about it.
So you're saying you want to do an AJAX call that returns HTML to be prepended to your content_gallery div?
<a class="prependLink" href="#">Prepend items</a>
<script type="text/javascript">
function PrependItemsToList()
{
var url="yourpage.php";
$.ajax(url, {
success: function(data, textStatus, jqXHR){
$("#content_gallery").prepend(data);
});
});
}
$('.prependLink').click(function(e){
PrependItemsToList();
e.preventDefault();
});
Of course, this approach is pointless if you aren't loading any information that isn't context-sensitive (ie. you pass some parameters to your remote page through your ajax call).
Posting more information will help us better answer your question.

Pass PHP output to jQuery

I have got this code
/* Popup for hot news */
$(document).ready(function() {
var $dialog = $('<div></div>')
.html('text to be shown')
.dialog({
autoOpen: false,
title: 'Table'
});
This code is in my JavaScript files which are included by header.php.
How to pass PHP output to this function?
Inputing <?php echo($mydata)?> in .html('') above does not solve anything.
Any reason why this gives an error?
Thanks for helping!
First of all your code is having some problem, $ in php is a prefix of variable and $ in jQuery is a selection sign. You can view the html source(the output) on browser for debug.
I can think of three ways to do so:
(1)The way you have mentioned should work, see the code below
<?php $foo='hi'?>
<script>
alert("<?php echo $foo?>");
</script>
(2)Another way is to separate server side and client slide code clearly for better maintenance
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<?php echo"<div id='foo' style='visibility:hidden;'>HI</div>"?>
<script>
alert($('#foo').text());
</script>
(3)The last way is by passing variable from the URL http://example.com/example.php#hi
<script>
var foo= location.href.split('#')[1];
alert(foo);
</script>
Adding <?php //code?> to your JS files do nothing because JS files are not executed by Apache. You can either use Ajax to request for data once your page loads (if the data doesn't need to be there at start) or you can add those PHP code blocks to your HTML code.
Using Ajax (goes in your JS file)
$(document).ready(function(){
var u = 'data.php';
var d = {};//data
$.get(u, d, function(data){
//got by data. lets invoke some methods here
});
});
Putting it in your HTML (goes in your HTML file)
var __DATA = '<?php //output some data I prepared earlier ?>';
//I'm using __ and capitol case to denote a global variable. Just personal preference
<script src='myjsfile.js' type='text/javascript'></script>
//the variable __DATA is available to your JS file and you can use it

Categories