How to send json_encode data with HTML5 SSE - javascript

I have a script that fires an SSE event for fetching json encoded data from online.php.
On googling, I found ways to send JSON data with sse, by introducing line-breaks.
What I am looking for is how to send JSON over SSE when the JSON array is created using PHP's json_encode() function.
I have written the following lines of code, but could anybody help me with where to add the "data: \n\n" required for SSE?
<script>
if(typeof(EventSource)!=="undefined")
{
var source=new EventSource("online.php");
source.onmessage=function(event)
{
var data=JSON.parse(event.data);
$("#new_message").html("Inbox"+data['total']);
};
}
else
{
$("#new_message").html("HTML5 not supported");
}
</script>
online.php
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$data["total"]="hello";
echo json_encode($data);
ob_flush();
flush();
?>

You need to send it in EventStream format, which in this case is just prepending it with data:
echo 'data: ' . json_encode($data) . "\n\n";

You can encode the $data array like Ryan said:
echo 'data: ' . json_encode($data) . "\n\n";
Then, client side, event.data will be viewed as a string, which you can then easily parse to json using query's jQuery.parseJSON(). so your client-side code will look something like this:
// Check if the browser supports SSE
if (typeof (EventSource) !== "undefined") {
var source = new EventSource("script.php");
// Handle evetns
source.onmessage = function(event) {
// parse the data that has an object as a string
var msg = $.parseJSON(event.data);
// Do awesome code with the values inside msg
};
} else {
alert("Sorry, your browser doesn't support this awesome feature!");
}
Source: http://api.jquery.com/jquery.parsejson/

Your script will only show output once as it needs to have some kind of a loop to keep running (conditionally of course or you'll have millions of instances running!!).
I've chopped up an implementation I wrote earlier today which demonstrates this and also added some additional javascript/jquery to help manage the streams better. The below will also work on a single threaded PHP installation like Xampp (for local development)
Notes on Xampp: As the PHP script is in a loop and doesn't terminate immediately it will stop a new php or agax script from running. If you're using ajax as well to call PHP call stream_close() in the beforesend and stream_open() in the success callbacks.
The below is untested but it's mainly grabbed from working code so it should be fine.
<?
//stream.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
stream();
function stream(){
$data = array();
//collect data from database or wherever to stream to browser
//example data
$data[0]["name"] = 'Bob';
$data[0]["total"] = rand(0,100);
$data[0]["name"] = 'Jane';
$data[0]["total"] = rand(0,100);
//maybe there is no new data so just send one new line
//this is required to check if the connection is still alive
if(!empty($data)){
echo "\n";
}else{ //Otherwise json encode the data for output
echo 'data: '.json_encode($data)."\n\n";
}
flush(); //Flush the result to the browser
sleep(1); //Wait a second (or what ever you like)
//If the browser is still connected
if(!connection_aborted() && connection_status()==0){
stream(); //recurse the function
}
}
?>
<script>
var webstream = false;
function stream_open(){
stream_close(); //Close the stream it (in case we got here weirdly)
if(!!window.EventSource){ //Test compatibility
webstream = new EventSource('./stream.php');
console.log("Stream Opened"); //Log event for testing
webstream.addEventListener('message', function(e){
var data = JSON.parse(e.data); //Parse the json into an object
process_stream(data);
},false);
//Cleanup after navigating away (optional)
$(window).bind('beforeunload', function(){
webstream.onclose = function(){}; //delete onclose (optional)
webstream.close(); //Close the stream
});
}
}
function stream_close(){
if(typeof(webstream)=="object"){
webstream.close();
webstream = false;
console.log("Stream Closed"); //Log event for testing
}
}
function process_stream(data){
//do something with the new data from the stream, e.g. log in console
console.log(data);
}
//Optional:
//Toggle stream on blur/focus
//Good if the user opens multiple windows or Xampp?
$(window).on("blur focus", function(e) {
//get the last blur/focus event type
var prevType = $(this).data("prevType") || null;
if (prevType != e.type){
console.log(e.type); //Log event for testing (focus/blur)
switch (e.type){
case "blur":
stream_close(); //Close stream on blur
break;
case "focus":
stream_open(); //Open stream on focus
break;
}
}
//Store the last event type to data
$(this).data("prevType", e.type);
});
// Optional:
// Using idletimer plugin to close the stream in times of inactivity
// https://github.com/thorst/jquery-idletimer/blob/master/src/idle-timer.js
$(document).on("idle.idleTimer", function (){
stream_close();
});
$(document).on("active.idleTimer", function (){
stream_open();
});
$(document).idleTimer({timeout:5000}); //5 second idle timer
</script>

Related

How to get PHP array as responseText in ajax to pass it to certain div from ajax later

I have a general info form. When I click on submit, all values are got using javascript and send it to PHP function using ajax.
The PHP function validates the form and returns
EITHER form errors as an array
OR successful message.
I want to get the array generated by PHP on ajax side and pass it to the form to display the errors on respective form fields.
I have successfully generated the array of errors in PHP.
print_r($arrayname) shows all the values as an array.
But I don't want to show instead I want to pass it to ajax and retrieve the array in a div and do work on that array.
--------- AJAX ------
function general()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('POST','addGeneral',true);
var data = new FormData();
data.append('title',document.getElementById('title').value);
data.append('firstname',document.getElementById('firstname').value);
data.append('middlename',document.getElementById('middlename').value);
data.append('surname',document.getElementById('surname').value);
xmlHttp.send(data);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState==4)
{
var status = xmlHttp.responseText;
document.getElementById('responseG').style.display="block";
if(status=='true')
{
document.getElementById('responseG').className="alert alert-success";
document.getElementById('responseG').innerHTML="<p>Successfully Updated</p>";
}
else
{
document.getElementById('responseG').className="alert alert-danger";
document.getElementById('responseG').innerHTML=status;
}
}
}
}
---- PHP FUNCTION ---
public function addGeneral()
{
$status=array();
extract($_POST);
$this->form_validation->set_rules('title','Title','required',array('required' => 'You must provide a %s.'));
$this->form_validation->set_rules('firstname','First Name','required');
$this->form_validation->set_rules('middlename','Middle Name','required');
$this->form_validation->set_rules('surname','Surname','required');
if($this->form_validation->run()===FALSE)
{
$status=$this->form_validation->error_array();
}else
{
$data=array(
'title'=>$title,
'firstname'=>$firstname,
'middlename'=>$middlename,
'surname'=>$surname
);
$this->Manage_employee_model->update_employee($data);
$status=array('true');
}
}
Once a PHP script finished running and the browser receives the end of the HTML response, it's over, you can't directly modify the output already sent with more PHP. What you can do it use AJAX to get the data and render it on the client side using JS, or render it on the server side and just inject the result with JS.
Client rendering
For this you just need your PHP script to return the data, then loop over it and append each item to your div in JS. It's a bit awkward to render things with native JS but this approach keeps the presentation in one place instead of having HTML code on your backend.
Server side
$data=array(
'title'=>$title,
'firstname'=>$firstname,
'middlename'=>$middlename,
'surname'=>$surname
);
echo json_encode($data);
Client side
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4) {
var data = JSON.parse(xmlHttp.responseText);
document.getElementById('responseG').style.display="block";
if(data.status=='true') {
document.getElementById('responseG').className="alert alert-success";
document.getElementById('responseG').innerHTML="<p>Successfully Updated</p>";
}
else {
document.getElementById('responseG').className="alert alert-danger";
for(var i = 0; i < data.length; i++){
document.getElementById('responseG').innerHTML+= '<p>'+data[i]+'</p>;
}
}
}
}
Server rendering
Here we use PHP to generate the HTML string on the backend, send it back via AJAX and just append it to the div on the client side. The disadvantage here is mixing HTML templates with your backend code.
Server side
$data=array(
'title'=>$title,
'firstname'=>$firstname,
'middlename'=>$middlename,
'surname'=>$surname
);
$html = '';
foreach ($data as $key => $item) {
$html += '<p>'.$item.'</p>';
}
echo json_encode(array('html' => $html));
Client side
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4) {
var data = JSON.parse(xmlHttp.responseText);
document.getElementById('responseG').style.display="block";
if(data.status=='true') {
document.getElementById('responseG').className="alert alert-success";
document.getElementById('responseG').innerHTML="<p>Successfully Updated</p>";
}
else {
document.getElementById('responseG').className="alert alert-danger";
document.getElementById('responseG').innerHTML = data.html;
}
}
}
In your php code after you have done all the checks and populated your response array just do a simple echo to return that data to ajax.
Example in php: echo json_encode($status);
The best place to put this code is under your if statement
Print error message on form
<?php
if(!empty(validation_errors())) {echo
validation_errors();}
?>

Returning value to Javascript from PHP called from XMLHttpRequest

I am attempting to add an "Upload Image" feature to my AjaxChat window. The upload to the server works great, but now I need to be able to return the tmp_name/location of the file that was uploaded. In my Javascript I have the following (main) code (some setup code has been omitted because it is unnecessary -- The upload works as expected):
// Set up request
var xhr = new XMLHttpRequest();
// Open connection
xhr.open('POST', 'sites/all/modules/ajaxchat/upload.php', true);
// Set up handler for when request finishes
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
uploadButton.innerHTML = 'Upload';
} else {
alert('An error occurred!');
}
};
// Send data
xhr.send(formData);
My PHP code ("upload.php") is as follows:
<?php
$valid_file = true;
echo '<script type="text/javascript">alert("PHP Code Reached");</script>';
if($_FILES['photo']['name']) {
//if no errors...
if(!$_FILES['photo']['error']) {
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) { //can't be larger than 1 MB
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
exit("$message");
}
//if the file has passed the test
if($valid_file) {
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], '/var/www/html/images'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
exit("$message");
}
}
//if there is an error...
else {
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
exit("$message");
}
}
?>
I can tell my PHP code is being run because the image uploads to the server. However, I read that I could generate a Javascript "alert" popup from within the PHP using the following code:
echo '<script type="text/javascript">alert("PHP Code Reached");</script>';
But the above line does not seem to be doing anything. Is this expected since I'm using an XMLHttpRequest, rather than running the PHP directly?
Ultimately my goal is to pass the name of the uploaded file back to the Javascript that called the PHP so that I can create the image url, put it in img tags, and send it to the chat window using ajaxChat.insertText() and ajaxChat.sendMessage(). I'm not sure if this is possible the way I'm running my PHP, though. How would one go about doing this?
When you use XMLHttpRequest, the output of the server script is in the responseText of the object. So you can do:
xhr.onload = function () {
if (xhr.status === 200) {
//File(s) uploaded
uploadButton.innerHTML = xhr.responseText;
} else {
alert('An error occurred!');
}
};
If you want to send back multiple pieces of information, such as an informative message and the name of the file, you can use JSON to encode an associative array, which will become a Javascript object when you parse it.

jQuery open page in a new tab while passing POST data

I have a javascript variable called "list". I need to send it as a POST data to another page and open that page in a new tab (with the POST data present).
This code:
jQuery.post('datadestination.php', list);
sends the data all right, but ofcourse it opens the page in the same tab.
I saw some solutions to similar problems using invisible form and things like that, but I could not get them to work. Is there any simple solution?
You can send a form using the target="_blank" attribute.
<form action="datadestination.php" method="POST" target="_blank" id="myform">
<input type="hidden" name="list" id="list-data"/>
<input type="submit" value="Submit">
</form>
Then in JS:
jQuery('#list-data').val(list);
jQuery('#myform').submit();
This is an implementation of Sergey's solution.
<?php // this is save.php
session_start();
// DO NOT just copy from _POST to _SESSION,
// as it could allow a malicious user to override security.
// Use a disposable variable key, such as "data" here.
// So even if someone passed _POST[isAdmin]=true, all that he would do
// is populate _SESSION[data][isAuthenticated], which nobody reads,
// not the all-important _SESSION[isAuthenticated] key.
if (array_key_exists('data', $_POST)) {
$_SESSION['data'] = $_POST['data'];
$_SESSION['data.timestamp'] = time();
// Let us let the client know what happened
$msg = 'OK';
} else {
$msg = 'No data was supplied';
}
Header('Content-Type: application/json; charset=utf8');
die(json_encode(array('status' => $msg)));
?>
In the first page:
$.post('save.php', { data: list }, function(response){
if (!response.status) {
alert("Error calling save");
return;
}
if (response.status !== 'OK') {
alert(response.status);
return;
}
// We had a response and it was "OK". We're good.
window.open('datadestination.php');
});
And in datadestination.php add the fix:
if (!array_key_exists('data', $_SESSION)) {
die("Problems? Did you perchance attempt to reload the page and resubmit?");
// For if he did, then yes, $_SESSION would have been cleared.
// Same if he is operating on more than one window or browser tab.
}
// Do something to validate data. For example we can use data.timestamp
// to assure data isn't stale.
$age = time();
if (array_key_exists($ts = 'data.timestamp', $_SESSION)) {
$age -= $_SESSION[$ts];
}
if ($age > 3600) {
die("Data is more than one hour old. Did someone change server time?!?");
// I actually had ${PFY} do that to me using NTP + --hctosys, once.
// My own time zone is (most of the year) exactly one hour past GMT.
}
// This is safe (we move unsecurity-ward):
$_POST = $_SESSION['data'];
unset($_SESSION['data'], $_SESSION['data.timestamp']);
// keep things clean.
// From here on, the script behaves "as if" it got a _POST.
Update
You can actually merge save.php and datadestination.php and use a "saving stub" savepost.php that you can recycle in other pages:
<?php
session_start();
// DO NOT just copy from _POST to _SESSION,
// as it could allow a malicious user to override security.
// Use a disposable variable key, such as "data" here.
if (array_key_exists('data', $_POST)) {
// Timestamp sent by AJAX
if (array_key_exists('ts', $_POST)) {
// TODO: verify ts, but beware of time zones!
$_SESSION['data'] = $_POST['data'];
Header("Content-Type: application/json;charset=UTF-8");
die(json_encode(array('status' => 'OK')));
}
die("Error");
}
// This is safe (we move unsecurity-ward):
$_POST = $_SESSION['data'];
unset($_SESSION['data']); // keep things clean.
?>
Now your call becomes
$.post('datadestination.php', { data: list, ts: Date.now() }, function(){
window.open('datadestination.php');
});
and in your datadestination.php (or anywhere else) you add
require 'savepost.php';
I suggest:
Pass that list with the jquery.post() function and save it in the SESSION array.
Open a new tab with the same file/address/URL with the window.open() function.
Retrieve saved data from the SESSION array.
This seems straightforward and clean to me.

Passing a JavaScript value to PHP on completion of quiz

I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});

Request timeout

I'm using some jQuery to display tweets but once the Twitter API limit is reached, the request is sent but just keeps loading and loading. This doesn't look good. I want to be able to determine if the request is taking too long and then obviously do stuff, like cancel the request, change the styling, etc.
So this is the code that sends the request:
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", "http://search.twitter.com/search.json?q="+buildString+"&callback=TweetTick&rpp=50");
document.getElementsByTagName("head")[0].appendChild(fileref);
And this is the TweetTick function:
function TweetTick(ob)
{
var container=$('#tweet-container');
container.html('');
$(ob.results).each(function(el){
/* in here, a div is built for each tweet and then appended to container */
});
container.jScrollPane(); /* just adds the scrollbar */
}
You need to cache twitter api response on your server side.
How do I keep from running into the rate limit?
I had a very similar problem lately. I use this script by Remy Sharp for most of my twitter requests: http://remysharp.com/2007/05/18/add-twitter-to-your-blog-step-by-step/
What you need to realise is that the api timeout is per IP address. So if the api has timed out for you based on your testing, it won't have timed out for someone else on a different IP address. Now, if someone accessing the site is doing so within a corporation or business, and others in the same place are doing the same, that timeout will occur almost instantaneously.
To get around this you need to cache your results. The way I did this was as follows.
I created a twitter caching system using the following code:
$twitter_username = "tadywankenobi"; //
$number_of_tweets = "10";
$options[CURLOPT_URL] = 'http://api.twitter.com/1/statuses/user_timeline.xml?screen_name='.$twitter_username.'&count='.$number_of_tweets.'&include_rts=1';
$options[CURLOPT_PORT] = 80;
$options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = 60;
$tweets = cache($options);
$twxml = new SimpleXMLElement($tweets);
echo "<ul>";
for($i=0;$i<=($number_of_tweets-1);$i++){
$text = $twxml->status[$i]->text;
echo "<li>".auto_link_twitter($text)."</li>";
}
echo "</ul>";
function cache($options) {
$cache_filename = "/var/cache/tweets.xml";
if(!file_exists($cache_filename)){
$handle = fopen($cache_filename, 'w') or die('Cannot open file: '.$my_file);
fclose($handle);
}// Check if cache file exists and if not, create it
$time_expire = filectime($cache_filename) + 60*60; // Expire Time (1 hour) // Comment for first run
// Set time to check file against
if(filectime($cache_filename) >= $time_expire || filesize($cache_filename) == 0) {
// File is too old or empty, refresh cache
$curl = curl_init();
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
curl_close($curl);
if($response){
file_put_contents($cache_filename, $response);
}
else{
unlink($cache_filename);
}
}else{
$response = file_get_contents($cache_filename);
}
return $response;
}
What the cache function at the end does is create a file on the server and stores the twitter xml feedback in there. The system then checks to see the age of that file and if it's younger than an hour old, it takes its results from there. Otherwise, it re-accesses twitter. You need to have the file writable in the /var/cache folder (create it if it's not there).
I've kinda hacked this code together a bit, so let me know if you run into any issues with it. It also uses an auto_link_twitter() function, which creates the links required within the twitter text. I didn't write that, so I'll try and find you a link to it now.
Hope that all helps,
T
UPDATE: I can't remember where I got the auto_link_twitter() function, so here it is. If the person who wrote it reads this post, my apologies, I couldn't find the source again.
function auto_link_twitter($text) {
// properly formatted URLs
$urls = "/(((http[s]?:\/\/)|(www\.))?(([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+(\.[a-z]{2,2})?)\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1})/is";
$text = preg_replace($urls, " <a href='$1'>$1</a>", $text);
// URLs without protocols
$text = preg_replace("/href=\"www/", "href=\"http://www", $text);
// Twitter usernames
$twitter = "/#([A-Za-z0-9_]+)/is";
$text = preg_replace ($twitter, " <a href='http://twitter.com/$1'>#$1</a>", $text);
// Twitter hashtags
$hashtag = "/#([A-Aa-z0-9_-]+)/is";
$text = preg_replace ($hashtag, " <a href='http://twitter.com/#!/search?q=%23$1'>#$1</a>", $text);
return $text;
}
You can use specific jQuery methods to make a JSONP request. There is basic $.ajax method and shorthand method $.getJSON which fits better for you. To control timeout of the request you can use timeout parameter. Request exceeded timeout can be processed using the error callback.
$.ajax(
dataType: 'jsonp',
url: 'http://search.twitter.com/search.json',
data: {
q: buildString,
rpp: 50
},
jsonpCallback: 'TweetTick',
timeout: 30000,
error: function(jqXHR, textStatus, errorThrown) {
if (textStatus == 'timeout') {
alert('timeout exceeded');
}
}
);

Categories