jQuery Parse Twitter jSON but not Parse my same PHP document - php

I've a function that parse Twitter search result and put into my HTML document. The code works!
Here is the code.
<script>
$(function update_twit(){
$("#notice_div").html('Updating..');
$.ajax({
url: "http://search.twitter.com/search.json?q=stackoverflow&rpp=2",
dataType: 'jsonp',
success: function(json_results){
$("#notice_div").html('');
$("#twitList").html('');
console.log(json_results);
$('#twitList').append('<ul data-role="listview" data-inset="true" data-theme="c"></ul>');
listItems = $('#twitList').find('ul');
$.each(json_results.results, function(key) {
html = '<p class="ui-li-bside">'+json_results.results[key].text+'</p>';
html += '<p class="ui-li-aside">Gönderen: <strong>'+json_results.results[key].from_user+'<strong></p>';
listItems.append('<li>'+html+'</li>');
});
// Need to refresh list after AJAX call
$('#twitList ul').listview();
window.setTimeout(update_twit, 10000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html(errorThrown+'Error..'+textStatus);
window.setTimeout(update_twit, 60000);
}
});
})
</script>
The problem is I copy the Twitter url and paste into my browser. After getting response. I make a PHP document (getmyjson.php) like that
<?
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$json='{"completed_in":0.021,"max_id":158455057786998785,"max_id_str":"158455057786998785","next_page":"?page=2&max_id=158455057786998785&q=erhan&rpp=2","page":1,"query":"erhan","refresh_url":"?since_id=158455057786998785&q=erhan","results":[{"created_at":"Sun, 15 Jan 2012 07:46:44 +0000","from_user":"_VCG_","from_user_id":169112180,"from_user_id_str":"169112180","from_user_name":"vedat can g\u00FCm\u00FC\u015F","geo":null,"id":158455057786998785,"id_str":"158455057786998785","iso_language_code":"tr","metadata":{"result_type":"recent"},"profile_image_url":"http://a3.twimg.com/profile_images/1710193374/bb_normal.png","profile_image_url_https":"https://si0.twimg.com/profile_images/1710193374/bb_normal.png","source":"<a href="http://twitter.com/">web</a>","text":"#erhan_ordu ben gidemiyom ya ama ke\u015Fke bi ihtimal olsa da gitsem :D bi de VGC DE\u011E\u0130L VCG VCG :d","to_user":"erhan_ordu","to_user_id":458677081,"to_user_id_str":"458677081","to_user_name":"ERHAN ORDU"},{"created_at":"Sun, 15 Jan 2012 07:39:34 +0000","from_user":"hannyfaarah","from_user_id":199700684,"from_user_id_str":"199700684","from_user_name":"H\u2639","geo":null,"id":158453256241168384,"id_str":"158453256241168384","iso_language_code":"in","metadata":{"result_type":"recent"},"profile_image_url":"http://a2.twimg.com/profile_images/1736543252/cats_normal.jpg","profile_image_url_https":"https://si0.twimg.com/profile_images/1736543252/cats_normal.jpg","source":"<a href="http://twitter.com/">web</a>","text":"\"mantan bebep erhan tersayang selalu dihati\" HAHAHAHA emir emir ngakak weeey","to_user":null,"to_user_id":null,"to_user_id_str":null,"to_user_name":null}],"results_per_page":2,"since_id":0,"since_id_str":"0"}';
echo $json;
?>
Now i am trying to change Twitter URL in the first code to www.mywebiste.com/getmyjson.php
But it does not work!
Error message is : jQuery164018531796569004655_1326623562322 was not calledError.parsererror

For you local server testing switch to usual json instead of jsonp. So it becomes:
$.ajax({
//url: "http://search.twitter.com/search.json?q=stackoverflow&rpp=2",
//dataType: 'jsonp',
url: 'getmyjson.php',
dataType: 'json',
...
});
Or if you still want to use jsonp change your php script as follows:
$json = '{...}';
echo $_GET['callback'] . '(' .$json . ')';

Related

Why isn't my Ajax call Asynchronous

I'm using JQuery and AJAX to call a slow function in a PHP file, but I don't get a response until the PHP function is complete. I can't figure out why, despite 2 days of searching. I've shrunk it down to two test files, that exhibit exactly the same behaviour. My php function is thus, in a file called "ajaxfuncs.php":
<?php
Class AjaxFuncs{
public function __construct() {
$this->testbuffer ();
}
function testbuffer(){
echo 'Starting Test Buffer Output. There should be a 2 second delay after this text displays.' . PHP_EOL;
echo " <br><br>";
echo '<div id="testdata" class="testdata">0</div>';
// The above should be returned immediately
flush();
// Delay before returning anything else
sleep(2);
for ($a = 0; $a < 3; $a++) {
echo '<script type="text/javascript">document.getElementById("testdata").innerHTML="' . (int)($a + 1) . '"</script>';
flush();
// Delay for 1 second before updating the value
sleep(1);
}
}
}
$AjaxFuncs = new AjaxFuncs();
?>
The above works if I open the "ajaxfuncs.php" file in the browser. It does exactly as I'd expect, and the output updates every second until complete. So I know I've buffering sorted on the server.
But when I call it using the following $.ajax it's not right. I've put everything except the php for the ajax function into another php file called "testindex.php" for convenience. This is it:
<?php
header( 'Content-type: text/html; charset=utf-8' );
header("Cache-Control: no-store, must-revalidate");
header ("Pragma: no-cache");
header("Expires: Mon, 24 Sep 2012 04:00:00 GMT");
?>
<body>
<a>Test Page. Wait for it...</a>
<div id="maincontent">
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
console.log ('Document Ready');
function callajax(){
var ajaxfilepath = "ajaxfuncs.php";
return $.ajax({
url: ajaxfilepath,
data: {action: 'testbuffer'},
type: 'get',
cache: false,
dataType: "text",
beforeSend: console.log('Starting Ajax Operation')
})
.done(function(result){
processajaxcalloutput(result);
})
.always(function(){
console.log(' Ajax Internal Complete Detected');
})
.fail(function( jqXHR, textStatus ) {
console.log( "Ajax Request failed: " + textStatus );
});
}
function processajaxcalloutput(result){
var message = 'Processing Ajax Response' ;
console.log(message);
$("#maincontent").append(result);
}
callajax();
});
Everything works without error. Console is clear - no errors (I'm testing with Chrome & Firefox). But I can't seem to get a response until the entire PHP function is done. I've tried everything I can find, in particular hundreds of different things to force caching off, but to no avail. Any help is much appreciated. Thanks.
Update:
So based on the feedback so far, it's clear the call is asynchronous and the code is fine, but asynchronous does not mean I'll get a continuous stream of output data from the php function as it executes. Instead the entire response will be returned at the end of the execution. Rather than divert this question into one about streaming, I'll leave it at this until I resolve the streaming issue.

Send html answer from PHP to Ajax

Here is what I'm trying to do:
I use an Ajax call to select messages from my database, I echo the content in my PHP and i try to get the echoed html in the Ajax success. But it does not work. Here is the code.
JQUERY:
function SelectMessages()
{
console.log("Selecting messages");
console.log("Talk = " + talk);
$.ajax({
url: "select_messages.php",
type: "GET",
data: "talk=" + talk,
success: function (html) {
alert(html);
console.log("In success");
$("#message_box").prepend(html)
},
error: function (html) {
alert(html);
console.log("In error");
}
});//ajax()
}//SelectMessages()
PHP:
<?php
//SELECTING MESSAGES
require 'dbconnect.php';
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
if ($_GET['talk'] != "") {
$request = $bdd->prepare('SELECT AUTHOR,CONTENT FROM MESSAGE WHERE TALK = :talk');
$request->execute(array("talk"=>$_GET['talk']));
while ($data = $request->fetch(PDO::FETCH_ASSOC)) {
echo' <p> '.$data['CONTENT'].'</p>';
}
}
?>
Using this code, I get "In error" displayed on the console and the code in the alert is "[object Object]". However, the status of my query is "OK" in my browser and the echoed result in the network window is the one expected with all the right values of messages.
I just don't understand why I get through the error instead of success.
Please do not mark this as a duplicate as I have already checked and tested the Ajax/PHP solutions and did not get any result.
In your php file you have set content type header as follows
header('Content-type: application/json');
but normally echoed the response as plain text/html. Either you have to send the response in json.
echo json_encode($data['CONTENT']);
Or remove content-type header as json.

Can't echo Ajax variable pass

I'm passing 2 variables with ajax to the same .php file. I see them in the console.log but I can't seem to echo them. I already tried several things I found in other questions but it doesn't seem to work. What do I need to add/change?
My code:
<script>
$(document).ready(function () {
$("#slider").bind("valuesChanged", function (e, data) {
$.ajax({
type : "POST",
url : "../wp-content/themes/twentytwelve/fields/test.php",
data : {
minValue : data.values.min,
maxValue : data.values.max
},
cache : true,
async : false,
success : function (data) {
console.log(data);
},
error : function (xhr) {
alert('fail')
}
});
});
});
</script>
and the php part:
<?php if ( $_POST ) {
echo $_POST['minValue'];
}
?>
Btw: it only passes the first value (minValue) and not the other one. How to pass them both? Thanks!
Maybe by printing both values?
<?php
if (!empty($_POST)) {
echo $_POST['minValue'];
echo $_POST['maxValue'];
}
?>
Can you see your request details in the Debug panels like Firebug in FF or (I don't know how it called) in Chromium-based browsers?
Are there all the passed data?
If no then the error in JS.
Also print out the whole POST data on server side to see the POST content.
To pass more values try something like this on php side:
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/json");
echo json_encode(array(
'a' => 1,
'b' => 2
));

JSONP data in PHP to JS

I'm using JSONP to dynamically add data into my Android Phonegap app. Since Phonegap 2.5 (and upwards) allows application cache, I would like to use that. Only problem is that at this moment, my data is in a php-file. I read that data from a php-file cannot be cached by the cache manifest, so I'm thinking about changing it to js or something. Any idea how I would do this? I already tried a lot of tutorials on JSONP, but the only way I can get JSONP to work is in PHP. They are also quite vague about how I should save my data file (currently called home.php).
home.php
<?php echo $_GET["callback"] ?> (
[
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"exp1_index.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"exp2_index.html"
}
]
);
script in index.html that calls data from home.php
<script type="text/javascript">
$.ajax({
type: 'GET',
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
url: 'http://mllsdemode.be/Ex-cache/home.php',
success: function(json) {
var $home = $("#home");
$home.empty();
$.each(json, function(i, el) {
$home.append("<td><div class='dsc'>" + el.expo + "<br><em>" + el.datum + "</em></div></td>");
});
},
error: function() { alert("Error reading jsonP file"); }
});
</script>
Well, if I understood well, this is cached, you want it to be cached but not to develop? Then add some headers to develop!
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
To easily forge your JSON, you can use Simple JSON for PHP, it allows you to build complex JSON/JSONP.

jQuery POST handling errors

Explanation
I am sending a POST, and in PHP I am checking if username already exists in database.
If yes, return an error.
But the thing is, I can't use the same function(data) because I want the error to be located in another div.
$.post("events.php?action=send", { data : $(this).serialize() }, function(data)
{
$("#processing").html('');
$("#comments").html(data);
});
Problem
I can't have two variables in anonymous function, like function(data, error), then how am I supposed to fetch the 'error' PHP printed e.g 'User already exist's in database', and then put it in the #errors div?
It depends on how you are handling the error in your PHP code.
In order to even end up in the error handler you need to set the HTTP statuscode to "5XX".
What you probably want to do is to serialize an error object in case the user already exists, and handle it in the success handler like you are doing now:
PHP:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$data = array('error' => 'something went wrong');
echo json_encode($data);
JS:
function(data){
if(data && data.error){
//there was an error, handle it here
console.log(data.error);
} else {
//do something else with the user
console.log(data);
}
}
In PHP you can return json error, like print '{"error":'.json_encode($error).'}' and then, in your js put in desired div
$.post("events.php?action=send", { data : $(this).serialize() }, function(data)
{
$("#processing").html('');
$("#comments").html(data);
$("#error").append(data.error);
});
I suggest you to return data as a json string from your server. If you do that, you can get an object from $.parseJSON(data);
// In your php code
$result = new stdClass();
$result->userExists=false;
echo json_encode($result);
Now inside your anonymous function:
// Javascript
data = $.parseJSON(data);
console.log(data);
if (data.userExists) alert("User exists!");

Categories