Using AJAX to access to the Twitter API - javascript

I'm thinking about adding some twitter functions in my web-application, so I started doing some tests. I checked the way to call the search twitter URL (more info in: http://dev.twitter.com/doc/get/search) in order to get tweets that contains the searched word/sentence. I realized that you can do it in php just getting the JSON file that the search URL returns with the file_get_contents() function. Also you can do it directly in JavaScript creating a script object, appending it to the body and use the callback parameter of the search URL to process the data.
Different ways to do, but that's the way I finally did it:
MAIN HTML FILE:
<title>Twitter API JSON</title>
<script type="text/javascript">
//function that created the AJAX object
function newAjax(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
//function that search the tweets containing an specific word/sentence
function gettweets(){
ajax = newAjax();
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'getsearch.php', true);
// Process the data when the ajax object changes its state
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 ) {
if ( ajax.status ==200 ) { //no problem has been detected
res = ajax.responseText;
//use eval to format the data
searchres = eval("(" + res + ")");
resdiv = document.getElementById("result");
//insert the first 10 items(user and tweet text) in the div
for(i=0;i<10;i++){
resdiv.innerHTML += searchres.results[i].from_user+' says:<BR>'+searchres.results[i].text+'<BR><BR>';
}
}
}
}
ajax.send(null);
} //end gettweets function
</script>
#search_word Tweets
<input type="button" onclick="gettweets();"value="search" />
<div id="result">
<BR>
</div>
</html>
PHP WHERE WE GET THE JSON DATA:
$jsonurl = "http://search.twitter.com/search.json?q=%23search_word&rpp=10";
$json = file_get_contents($jsonurl,0,null,null);
echo $json;
And that's it, in this way it works fine. I call the PHP file, it returns the JSON data retrieved from the search URL, and in the main HTML JavaScript functions I insert the tweets in the div. The problem is that at the first time, I tried to do it directly in JavaScript, calling the search URL with Ajax, like this:
MAIN HTML FILE:
//same code above
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'http://search.twitter.com/search.json?q=%23search_word&rpp=10', true);
//same code above
I thought it should return the JSON data, but it doesn't. I'm wondering why not and that is what I would like to ask. Does someone have any idea of why I can't get JSON data using the Ajax object? If the search URL http://search.twitter.com/search.json?q=%23search_word&rpp=10 returns JSON data, it should be obtained in the ajax object, right?

XHR requests are generally limited to same-domain requests; e.g, if you're on bertsbees.com, you can't use an Ajax method to pull data from twitter.com.
That said, Twitter's API supports a popular data transport method known as JSON-P, which is really just a glorified injection technique. You simply pass it a callback method, and the data returned will be wrapped in your desired function, so it gets eval'd and passed in.

You cannot make a cross domain request using javascript, unless you are doing from an browser addon.

Related

Reading JSON format from URL

I am trying to make a website that analyzes data from a game called Overwatch.
I have this (https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/) and when you visit it, all you see is text in the json format.
Is there anyway I can read this using JavaScript and send it to a nice <p> tag on my website?
Current Code:
<script>
var obj = JSON.parse('https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/');
document.getElementById("elims").innerHTML = obj.Eliminations;
</script>
<p id="elims"></p>
You didn't tag this with jQuery so I'm going to assume you're wanting to do this with vanilla JS. .jsonParse() doesn't actually request JSON from a URL--it parses existing JSON-data into an object.
To handle this, you'll first want to request the data. This can be done using an XMLHttpRequest():
var requestUrl = "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/";
You next want to build out and perform your request. Create a function once the JSON data is fully loaded (onload):
let request = new XMLHttpRequest();
request.open('GET', requestUrl);
request.responseType = 'json';
request.send();
request.onload = function() {
logData(request.response);
}
An example function that handles the data could be:
function logData(data) {
document.querySelector('.elims').innerText = `Genji Eliinations: ${data['Genji']["Combat"]["Eliminations"]}`;
}
This appends it to an element with the class .elims, for example, a tag:
<p class="elims"></p>
I've added the whole code below. This should be enough to get you in the correct direction:
let requestUrl = "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/";
let request = new XMLHttpRequest();
request.open('GET', requestUrl);
request.responseType = 'json';
request.send();
request.onload = function() {
logData(request.response);
}
function logData(data) {
document.querySelector('.elims').innerText = `Genji Eliinations: ${data['Genji']["Combat"]["Eliminations"]}`;
}
<p class="elims">
</p>
Good way to start, so the URL you are trying to access is the REST web service which is just a GET method which produces the JSON. All you have to do is make an AJAX call via Javascript or Jquery and you can parse this to a Javascript variable then you can use those variable values you can generate the Paragraph elements to your HTML page.
You need to load data from server using HTTP GET request like this,
$.get( "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/", function( data ) {
console.log(data);
//process your data here
});
Since your url (https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/) is in json format. In order to retrieve it you need to use something like getJson.
Example:
$.getJSON( "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/", function( json ) {
console.log( "JSON Data: " + json.Assists["Healing Done"]);
});
You can read more on how to use getJson.

JS counter write to database

Is there any way I can use this JS second counter, to write to mysql:
var counter = 0;
setInterval(function () {
++counter;
}, 1000);
Can I export it as a variable and then use that variable to write to mysql?
What I'm attempting to do is save the time the user was on the page.
Is this even possible?
To help solve your ajax part (need jquery):
$.ajax({
type:'POST',
url: "yourfile.php",
data:{
"foo": filename // to add more variables you add on the spot after filename but remember the last one variable you send shouldn't have a comma
}
});
on the receiving end (php):
<?php
$filename = $_POST["foo"];
?>
basically ajax is used to send data to a php script.
Javascript is a language that is used in client side and can't write to MYsql. The code above will help you send data to your script. Your php script will run once it recieves the data through AJAX
You would need to write a bit of back-end php to handle ajax query from your front-end javascript.
Your JS may look like this:
function ajaxRequest(data) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "path/to/back-end.php", true);
xmlHttp.timeout = 1000;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) { //DONE
//success
console.log("Successfully sent to back-end.php");
}
};
xmlHttp.send(data);
}
You can refer to http://www.w3schools.com/ajax/default.asp for more information.
Then your php will retrieve the body of this POST request and insert it to mysql database accordingly.

Accessing and decoding JSON sent from JavaScript to PHP

So I have a form, I took the contents of its inputs, threw them into an array, had it made into a JSON and then sent it to PHP so it can in turn decode and enter it into a database. I know it'd be easier to just use a <form method="POST" action="phpfile.php"> but I can't have this redirecting to another page, especially since my PHP is not embedded into HTML, instead it handles things offsite. Otherwise it'd be simpler to just use $_POST["name"] to get what I need. Nonetheless, this page in particular is supposed to create the user, receive a server response, that the user has been entered into the database and then is given an alert with a button to be redirected to the main page.
So anyway here are the relevant sections of this whole process.
JavaScript:
window.onload = function findSubmitButton() {
var button = document.querySelector(".send_info").addEventListener("click", serverInteraction);
}
function serverInteraction() {
var xmlhttp;
var inputArray;
var finalArray = [];
var JSONArray;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
throw new Error("Your browser is not compatible with XMLHTTP");
return false;
}
inputArray = document.querySelectorAll("input[type=text]");
for(var i = 0; i < inputArray.length; i++){
finalArray[i] = inputArray[i].value;
}
console.log(finalArray);
JSONArray = JSON.stringify({finalArray: finalArray});
console.log(JSONArray);
xmlhttp.open("POST","phpFiles/sendUserInfo.php", true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(JSONArray);
}
PHP:
<?php
$finalArray = json_decode($_POST['finalArray']);
var_dump($finalArray);
?>
That var_dump simply returns a null and using echo gives me nothing, except a warning that my array variable isn't initialized through XDebug. I'm not quite sure what I'm doing wrong here, I've been following this just like the tutorials tell you to do it, and isn't generating the array. I've also tried $_POST['JSONArray']without any luck in case that was how it was supposed to go. Also tried file_get_contents('php://input') which sends an empty string as well.
You can't get your data from $_POST if you put JSON in your post body.
see this question Receive JSON POST with PHP. php can't handle application/json properly.
For your var_dump is empty, try this
var_dump(file_get_contents('php://input'));
var_dump(json_decode(file_get_contents('php://input'), true));
you will see your data.
And if you send your data without change it to JSON, you will get wrong data.
eg: your finalArray is ['a','b','c'] and you send it directly.
var_dump(file_get_contents('php://input'));
you will see php got string a,b,c instead of ['a','b','c']
So if you want to use $_POST to receive data, you need to use application/x-www-form-urlencoded. you can use jquery to do it. see http://api.jquery.com/jquery.ajax/
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
it will serialize your js object into x-www-form-urlencoded and php will handle it properly.
use chrome's dev tools, switch to network and see the request payload and response would be helpful for you.
You are bypassing $_POST by sending the the data as "Content-type","application/json" .
The data will instead be set in the body of request and can be retrieved using file_get_contents("php://input")
For further discussion see file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?
Generally there is no need to send your data as json to php

Variable target file with Ajax

I'd like to start by saying that I would rather any suggestions didn't include JQuery; I don't like how JQuery has become a defacto standard within JavaScript.
So here's my problem:
I'd like to pass a variable to a function that then uses that variable as the path to the file in a .open(). Here's my code so far:
Example of function being called:
ajaxPost('chatlog.txt',null);
The function being called:
function ajaxPost(targetPath,toSend){
var getMessage;
if (window.XMLHttpRequest){
getMessage=new XMLHttpRequest();
}
else{
getMessage=new ActiveXObject("Microsoft.XMLHTTP");
alert("Stop using Internet Explorer.");
}
getMessage.open("POST",targetPath,true);
getMessage.onreadystatechange=function(){
if (getMessage.readyState==4 && getMessage.status==200){
alert(getMessage.responseText);
}
};
getMessage.send(toSend);
}
This unfortunately doesn't work, for some kabuki reason.
I see some logical issue in your code:
the whole idea of using POST method is to send any kind of data to a specific backend and do server side stuff based on that data, but here you are using POST method to actually GET the 'chatlog.txt'. so you had to use GET method, to begin with.
BUT if you still insist on using POST instead of GET, you should know that you can use POST method instead of GET and it does the same, but you would face with some unforeseen problems.
YOUR ACTUAL PROBLEM:
I loaded your actual page and saw your problem, you have a error in your console:
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
and as I said it means you have to change your method. I changed it like this:
function ajaxPost(targetPath,toSend){
var getMessage;
if (window.XMLHttpRequest){
getMessage=new XMLHttpRequest();
}
else{
getMessage=new ActiveXObject("Microsoft.XMLHTTP");
alert("Stop using Internet Explorer.");
}
getMessage.open("GET",targetPath,true);
getMessage.onreadystatechange=function(){
if (getMessage.readyState==4 && getMessage.status==200){
alert(getMessage.responseText);
}
};
getMessage.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
getMessage.send(toSend);
}
and it returned a data like this:
<b>Peck:</b> Hello World!<br/>#
<b>World:</b> Hello Peck!<br/>#
Add
getMessage.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Before you send it. It tells the server how to process the POST stuff.
Using XMLHttpRequest is a very bad idea. If you are already using JQuery, try something like this:
$.post( "test.php", {name: "John", time: "2pm"}).done(function( data )
{
alert ("Succes! Data received: " + data);
});

How to pass javascript variable to php inside javascript function

I have a js file. Is it possible to do inside the js file a php coding? On my header I include my js file like this.
<script type="text/javascript" src="js/playthis.js"></script>
now inside my jsfile:
function getURL(e) {
alert(e+' javascript varibale');
<?php $url; ?> = e;
alert('<?php echo $url; ?>'+' php variable');
}
in my php file
<?php $url = "www.google.com"; ?>
<a href="#" onclick="getURL('<?php print $url; ?>');" class="title">
It's not working. Is there something wrong?
you have to make a new object for Ajax transaction named XMLHTTP REQUEST in some browsers and in I.E this is ActiveXObject basically; and this object belong to window object;
so the first step is:
if ( window.XMLHttpRequest ) {
XHR = new XMLHttpRequest();
}
else if ( window.ActiveXObject ) {
XHR = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("You Cant see because Your Browser Don't Support Ajax!!!\n Change Your Browser To A Modern One");
}
now, you have the right object
in next step, there is some methods for XHR object for send and receive you should know:
1/ onreadystatechange
2/readyState
3/status
4/open
5/send
6/setRequestHeader
first open a connection with open:
XHR.open("POST", url, true);
as you know, post is method of sending, and now you have to set the url you want to information send to, for example if you want to send the variable to the test.php, then the url is test.php...
true means the request will sent asynchronously..
next is set your request header, because your are using post method, in get method you don't need this:
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
next is sending the request with send method with this format send(name, value):
XHR.send('value=' + value);
first string 'value=' is the index of $_POST that you will get in php, so in your php code, you'll give this with $_POST['value'], if you set the name to 'name=', in php you have $_POST['name'], be careful that in Ajax send param you have to use = after the name of data, but in php the = is not used...
after you sent the request; it's time to mange response:
XHR.onreadystatechange = function() {
if ( XHR.readyState == 4 && XHR.status == 200 ) {
document.getElementById('your target element for show result').innerHTML == XHR.responseText;
}
}
XHR.readyState == 4 and XHR.status == 200 means every thing is O.K.
this is the basics of Ajax as you wished for; but there is so many information for Ajax, and either you can use jQuery Ajax method that is so simple and flexible; But as you want I described the basics for you...
No it's not possible to have PHP code inside JS file.
You can make $.ajax call to a PHP file and that file can handle the setting of the variable required.
Hope this helps.
There are a few ways to handle this.
1 - Have .js files parsed by php. You will need to change your webserver configuration to do this.
2 - Use AJAX to interact with php.
3 - Have php render an additional JS snippet in the body onload event that sets this JS parameter (but still have the library as a seperate file).
this is not necessary, when you print the url with print $url in onclick attribute inside the php page as an argument for getURL function, it means the value of $url will be sent to the function with name getURL in your js file...
so, you have to write:
alert(e);
and if you are just asking, as the other friends told, you should use Ajax for this...
when you assign a variable to a function as an argument, just like getURL(e), the time that you call the function,getURL('print $url") you have to set the value of that variable, so, the program set the value you give to the function to the default variable...e = $url
you can change .js file to .php file and work with javascript and php together
change this
<script type="text/javascript" src="js/playthis.js"></script>
to this
<script type="text/javascript" src="js/playthis.php"></script>

Categories

Resources