Problem with jQuery JSONP twitter search request - php

I'm having some difficulties to correctly retrieve Twitter data using jsonp search.json.
When I fetch the data only once, it works perfectly with this piece of code :
function getTweets(){
$.ajax({
url: 'http://search.twitter.com/search.json',
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'tw_callback',
data: 'q=<?php echo urlencode($twitter_search); ?>+-RT&rpp=100'
});
}
function tw_callback(jsonp){
for( key in jsonp['results'] ) {
var tweet = jsonp['results'][key]['text'] ;
var from = jsonp['results'][key]['from_user'];
var avatar = jsonp['results'][key]['profile_image_url'];
tw_container.push([tweet,from,avatar]);
}
}
But when I try then to refresh this data every xx seconds, using setInterval:
setInterval(function () { getTweets(); }, 1000*interval_tourniquet);
It unfortunately doesn't work. I'm having this error:
NOT_FOUND_ERR: DOM Exception 8: An
attempt was made to reference a Node
in a context where it does not exist.
basically, I got this every time I try to call my getTweets() function inside another function... :(
Other solution I tried :
function getTweets(){
$.ajax({
url: 'http://search.twitter.com/search.json',
type: 'GET',
dataType: 'jsonp',
data: 'callback=tw_callback&q=<?php echo urlencode($twitter_search); ?>+-RT&rpp=100'
});
}
This way it works perfectly with my own jsonp api on another server, but Twitter returns me my callback twice:
tw_callback(tw_callback({results...
And the jsonp string is not interpreted..
Any clue on this, any hint?
Thanx a lot!

Try to rewrite your function with the following, more simple, way.
function getTweets(){
$.ajax({
url: 'http://search.twitter.com/search.json?q=<?php echo urlencode($twitter_search); ?>&rpp=100&callback=?',
dataType: 'jsonp',
success: function(){
for( key in jsonp['results'] ) {
var tweet = jsonp['results'][key]['text'] ;
var from = jsonp['results'][key]['from_user'];
var avatar = jsonp['results'][key]['profile_image_url'];
tw_container.push([tweet,from,avatar]);
}
}
});
}

Related

calling a php function using ajax after interval of time

hi i am working on a codeigniter project. I want to execute a php function after an interval of 10seconds. When a user visits that specific page after 10 seconds i want that php function to be executed. In that php function i have set a counter which adds 1 to the specific table into the database. I have tried using AJAX but didnt get the desired result. Kindly explain me with examples as i am new in ajax. Thanks in advance...
#Majid Golshadi s answer is the right answer.
Working version is here
Please in view that is loaded all the time (like header_view.php)
add this few lines
<script type="text/javascript">
var _baseUrl = "<?= base_url() ?>";
</script>
This makes that your base_url is usable in JavaScript anywhere in page (but make sure to have it somewhere on "TOP" of page)
and literraly use #Majid Golshadi s answer in this way
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: _baseUrl + "/your/controller/param",
type: 'post',
data: {"token": "your_token"}, });
}, 10000);
});
using jquery this will be the easiest and fastest way to do that
`//setting timeout to 3 seconds = 3 thousand milli seconds
setInterval(function(){
//ajax call
$.ajax({
url: _baseUrl + "/controller_name/function_name/", //the url where you want to fetch the data
type: 'post', //type of request POST or GET
data: {"data": "value"}, }); //data passed to controller
},3000);`
in your controller you may use
function function_name(){
$var = $this->input->post();//getting data passed from ajax
//process here...
echo json_encode($var)//parses and returns the processed value
}
try this
setTimeout(function(){
$.ajax({
url: "<?php echo base_url('your/controller/address');?>",
type: 'post',
data: {"token": "your_token"},
});
}, 10000);
Example
in your view
$(document).ready(function(){
setTimeout(function(){
$.ajax({
url: "<?php echo base_url('MyController/Mymethod');?>",
type: 'post',
data: {"token": "12majid18"},
});
}, 10000);
});
and in Your Controller write method like this
public function Mymethod()
{
$token = $this->input->post('token');
if ( $token == '12majid18' )
{
/*call your model and insert your data in Table*/
}
}
you can try this:
window.jQuery(function(){
var y=setInterval(function() {
window.jQuery.post(url,{"token": "your_token"},function(res){
alert(res);
});
}, 10000);
});

Serialize() form in an existing ajax function

Actually the following function works fine, but now I need to add other variable in order to return from the php file the right statement.
function sssssss1(page) {
loading_show();
$.ajax({
type: "GET",
url: "load_data.php",
data: "page=" + page,
success: function (msg) {
$("#search").ajaxComplete(function (event, request, settings) {
loading_hide();
$("#search").html(msg);
});
}
});
}
I need to add the following two variable to be read by my php file. I have tried different solution, but nothing seem working
var form2 = document.myform2;
var dataString1 = $(form2).serialize();
How to add those variable in my existing function? Any idea?
You can send object as data,
this line:
data: "page="+page,
could be
data: {mypage:"page="+page, form2:document.myform2, dataString1:$(form2).serialize()}
and your PHP can get it like:
$page = $_GET['mypage'];
$form2 = $_GET['form2'];
$dataString = $_GET['dataString1'];
Hope it Help.

Access php function data via ajax

I have this php function inside a class the returns json data
function getPhotoDetails( $photoId ) {
$url = $this::APP_URL . 'media/' . $photoId . $this::APP_ID;
return $this->connectToApi($url);
}
and this ajax request
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: 'index.php',
success: function (data) {
console.log(data);
}
});
}
The question is how I can call the php function to get the json data.
Solution:
A big thanks to all of you guys and thanks to Poonam
The right code
PHP:
I created a new object instance in php file
$photoDetail = new MyClass;
if(isset($_REQUEST['image_id'])){
$id = $_REQUEST['image_id'];
echo (($photoDetail->getPhotoDetails($id)));
}
JavaScript
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: './instagram.php?image_id=' + photoId,
success: function (data) {
var data = $.parseJSON(data);
console.log(data);
}
});
}
Try with setting some parameter to identify that details needs to send for e.g assuming photoid params needed for function
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: 'index.php?sendPhoto=1&photoid=23',
success: function (data) {
console.log(data);
}
});
}
and then on index.php check (You can make check for photoid whatever you need as per requirement)
if(isset($_REQUEST['sendPhoto'])){
$id = $_REQUEST['photoid'];
return getPhotoDetails($id);
}
setup a switch-case. Pass the function name as GET or POST variable such that it calls the php function
You need a file which calls the PHP function. You can't just call PHP functions from Ajax. And as pointed out by Tim G, it needs to use the proper header, format the code as JSON, and echo the return value (if the function is not already doing these things).

Workaround possible for cURL and Javascript?

Everything was going great in my previous help request thread. I was on the correct track to get around a CSRF, but needed to be pointed in the right direction. I received great help and even an alternate script used to log into Google's Android Market. Both my script and the one I altered to match my form is get hung up at the same point. Apparently cURL cannot process JS, is there any way to work around the form being submitted with submitForm() without changing the form?
Here is the code for the SubmitForm function
function submitForm(formObj, formMode) {
if (!formObj)
return false;
if (formObj.tagName != "FORM") {
if (!formObj.form)
return false;
formObj = formObj.form;
}
if (formObj.mode)
formObj.mode.value = formMode;
formObj.submit();
}
Here is the code for the submit button -
<a class="VertMenuItems" href="javascript: document.authform.submit();">Submit</a>
Here is a link to my last question in case more background information is needed.
PHP service...
<?php
// PHP service file
// Get all data coming in via GET or POST
$vars = $_GET + $_POST;
// Do something with the data coming in
?>
Javascript elsewhere...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function sendData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'POST',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
function getData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'GET',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
});
</script>

Passing Two JavaScript Arrays to PHP

I need to get the distance between two points from JavaScript to PHP using Google Maps. Below is my function to get the distance and post no problems. Now, how can I send the arrays (i.e. volunteerDist and tvid) to another php file (i.e. distanceToDb.php) and what should be the code of my distanceToDb.php to get these data? Thanks! Actual codes is highly appreciated.
<?php
function getFDistance(lat, lng, vlat, vlng, vid) {
var eventlocation = new GLatLng(lat, lng);
var volunteerDist = new Array();
var tvid = new Array();
var volunteerlocation;
for(i=0;i<lat.length;i++) {
tvid[i] = vid[i];
volunteerlocation = new GLatLng(vlat[i], vlng[i]);
volunteerDist[i] = (Math.round((eventlocation.distanceFrom(volunteerlocation) / 1000)*10)/10);
}
$.ajax({
type: 'POST',
url: "distanceToDb.php",
data: {tvid: tvid, volunteerDist: volunteerDist},
success: function(data){
alert("Successful");
},
dataType: "json"
});
}
?>
I've passed arrays and objects using JSON in javascript, let's say through a jquery.post call:
$.ajax({
type: 'POST',
url: "distanceToDb.php",
data: {tvid: tvid, volunteerDist: volunteerDist},
success: successfunction,
dataType: "json"
});
Then, in the php file you just do this:
$js_data_arr = json_decode($_POST['data']);

Categories