How to get and store Twitter share counts in database? - php

I want to get twitter counts of my website and article pages. After getting them I want to store them in database. I tried getting counts and posting them on my query.php using ajax but its showing me Cross Origin Block Error. Is there any way to do this? or am I missing something?
$.ajax({
url: "https://cdn.api.twitter.com/1/urls/count.json?url=<?php the_permalink(); ?>",
crossDomain: true,
crossOrigin: true,
success: function(data) {
var count = JSON.parse(data);
$("#dd").html(count);
$.ajax
({
type: "POST",
url: "post.php",
data: { stats: count, paralink:'<?php echo $rows['link_id'];?>', social:'2' },
success: function(data) {
},
dataType: 'json'
});
}
});

It would probably be more efficient / faster if you just made one ajax call to your server and a request to twitter directly from your php script.
And it would solve your problem as well:
// you should validate the input, but for simplicity:
$link = $_POST['paralink'];
// ^^^^^^^^ I am not sure if this is the page you want, you need to check that.
// get twitter json
$json = file_get_contents('https://cdn.api.twitter.com/1/urls/count.json?url=' . $link);
Now you just need the inner ajax call.

Related

JSON can't read returned ajax value

I have an ajax function that retrieve two values for a given post: one for the number of likes, another one for the div that contains all the people that liked that post.
Everything seems to work fine, the json retrieved is correct, but the printing result is incorrect. Every time I try to get the number of likes (data.numDiLikes) I always get undefined even though the json is saying {"numDiLikes":"1","personeACuiPiace":"div info and stuff"}, how do I fix this?
AJAX with JSON
$.ajax({
dataType: "json",
type: 'POST',
cache: false,
url: "lib/ottieniCose.php",
data: { like: "", id: valCOR, comOrisp: comOrisp },
dataType: "html",
success: function(data, textStatus){
trova.find('.numDiLikes').first().replaceWith('<p class="numDiLikes">' + data.numDiLikes + ' mi piace</p>' + data.personeACuiPiace);
}
});
PHP
if ($_POST['comOrisp'] == 'commento') {
$commento->set_likes($_POST['id'], true);
// number of people that liked the post
$return_data['numDiLikes'] = $commento->get_likes($_POST['id'], true);
// div with all the people who liked the post
$return_data['personeACuiPiace'] = $commento->posso_fare_qualcosa($_SESSION['auth'], 'cancRisp', $_POST['id']);
echo json_encode($return_data);exit;
}
Use dataType: "json" to tell $.ajax that it returns JSON, and that it should parse it. dataType: "html" means that it returns HTML text, and data will be a string, not an object.

How to empty the GET values from a MySQL/jQuery ajax call

If you do an ajax call to retrieve info from a MySQL database and you time the function so it runs every X seconds, I am a bit confused about where do the GET values reside, in order to empty them.
I have this code in test.js:
var fill = function () {
$.ajax({
type: "GET",
url: "refresh.php",
dataType: "html",
success: function( data ) {
$( "#tb" ).append( data );
setTimeout( fill, 5000);
}
});
} ;
and in refresh.php I have the SQL query to retrieve the info. After the query, I setting the table like this:
printf( "<tr><td>".$row['name'].
"</td><td>".$row['surname'].
"</td><td>".$row['phone'].
"</td><td>".$row['date'].
"</td></td></tr>");
How can I stop the table from populating the same row every 5 seconds? I can pass the $row['name'] values to regular php values if needed, but I don't fully get in which moment I should empty them.
There might be another solution to this, but I think that my problem could be easily solved by removing the contents of the table before adding another. For instance:
var fill = function () {
$.ajax({
type: "GET",
url: "refresh.php",
dataType: "html",
success: function(data) {
$('#tb').empty().append(data);
}
});
};
setInterval(fill, 5000);
You can also make use of setInterval() so that you don't need to define a timeout on every execution.
That will do.
Thanks!

How to serialize form inputs in a .change event with javascript/PHP/CURL?

I'm working on a small project that requires Ajax to fetch data from database and update a page. The query to the database is built on the fly by the user and the query strings build like a chain. So for example the first item of the chain effects the next and the next and so on. Therefore it creates a list of post variables that I can't "know" ahead of time. I figured this would be a pretty simple thing to achieve however it's proving not to be. Here is my issue.
When I use a .changed event and try to seralize the form before posting it. I get nothing but empty strings. I've noticed that if I hard code the post variables everything works just fine. Is there something I'm missing? Does .changed not have a seralize method?
I am also using a CURL bridge since the server with the data is on another domain. I don't think that is causing any issues though. I believe it has to do with my event choice.
Here is the code:
$('#selector').change(function() {
$.ajax({
type: "post",
dataType: 'json',
url: "/pages/curlbridge.php",
data: $("#queryform").serialize(), //"select=all&date=2013"
success: function(data)
{
console.log(data);
var resultset = data;
}
});
Was Asked to attach the HTML. It's just a simple form
<form id="selector">
Select: <input type="text" id="select" />
Date: <input type="text" id="date" />
</form>
<br />
I agree with #m1ket that #queryform doesn't exist, although you can't use serialize() on a single input element, so the following line is incorrect:
data: $(this).serialize(), //"select=all&date=2013"
Perhaps what you can do is this (which gets all the data in the form the #selector is a part of):
data: $(this).closest('form').serialize(), //"select=all&date=2013"
EDIT
My bad, I didn't pay attention to the HTML posted in the original question
Scope issue maybe? Does this work:
$('#selector').change(function() {
var formData = $(this).serialize();
$.ajax({
type: "post",
dataType: 'json',
url: "/pages/curlbridge.php",
data: formData, //"select=all&date=2013"
success: function(data)
{
console.log(data);
var resultset = data;
}
});
});
$("#queryform") does not exist. Your jQuery should read like this:
$('#selector').change(function() {
$.ajax({
type: "post",
dataType: 'json',
url: "/pages/curlbridge.php",
data: $(this).serialize(), //"select=all&date=2013"
success: function(data)
{
console.log(data);
var resultset = data;
}
});
});
Also, are you using .change() because you want to submit the AJAX request every time a user enters a key?

sending increment value from jquery to php file with for loop help

I have this for loop in jquery
$(document).ready(function() {
for(i=0; i<counter; i++)
{
dataCounter = i;
$.ajax({
url: 'file.php',
dataType: 'json',
data: dataCounter,
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});
}
});
And then I want to bring in my dataCounter into the file.php as a variable and have it change each time so I can get different records in mysql in file.php, am I doing this right? How would the php portion look like? I know how pass variables to a php file with this method if I had a form, but I don't have a get or a post form to work with. Also, my variables are going to change.
Can someone help me? Thank you!
While I don't recommend running an ajax query inside of a loop, I am wiling to explain the data option for $.ajax(). Ideally, you pass an object as the data option, and it is translated by jQuery into a query string where each object property name is a key and its value is the value:
data: {
count: dataCounter
}
becomes
?count=1
in the query string of the ajax request if datacounter is equal to 1.
In PHP you would access it as $_GET['count'].
data needs to be a key-value pair, not just a value as you have it here. Try something like: (not tested)
$.ajax({
url: 'file.php',
dataType: 'json',
data: ({dataCounter : dataCounter}),
error: function(){
alert('Error loading XML document');
},
success: function(data){
$("#contents").html(data);
}
});

JQuery Ajax post data not arriving

my Ajax post data is not arriving - any clues please.
The data is a serilaized form that "alerts" correctly with all the data using this
$(document).ready(function() {
var serial = $('#frm_basket').serialize();
alert(serial);
$.ajax({
url: "basket-calc.php",
type: "post",
data: serial,
success: function(){
("#basketTotal").load('basket-calc.php');
}
});
});
The alert gives me a string like product=p1&qty=1&product=p2&qty=2
But when I try to php echo out the results on basket-calc.php I get an "empty" array
basket-calc.php:
$test = $_POST;
print_r($test);
You can debug your request with firebug to make sure what is happening.
Also try setting the post type to GET:
type: "GET",
to see if it makes any difference.
try:
$(document).ready(function() {
var serial = $('#frm_basket').serialize();
alert(serial);
$.ajax({
url: "basket-calc.php",
type: "post",
data: serial,
success: function(result){
("#basketTotal").html(result);
}
});
});
Also note following points:
make sure basket-calc.php is not returning 404
try sending blank data and echo your response
once you get sample string from server, just attach the real data
hope this helps
If your htaccess is stripping the .php from the , the POST gets converted to GET. I think.
Try and remove .php from your url.

Categories