Combine data from different URLs in ajax - javascript

I have one ajax request which i use to extract data from API, and create a table from the extracted data. Now i need to do the same, but to extract the data from two different URLs and merge is to the same table (retTable).
Here is my current code (one ajax request):
$.ajax(
{
url : '/url/status',
type: "GET",
success:function(data, textStatus, jqXHR)
{
theRows = extract_status_data(data)
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('error')
}
});
}
function extract_status_data(jsonDataRaw){
jsonResultSect = jsonDataRaw['result']
retTable = ""
for( key in jsonResultSect){
statusParam = jsonResultSect[key]
a = statusParam['a']
b = statusParam['b']
c = statusParam['c']
d = statusParam['d']
e = statusParam['e']
retTable += "<tr><td>" + dropDownList(key) + "</td><td>" + key + "</td><td>" + a + "</td><td>" + b + "</td><td>" + c + "</td><td>" + d + "</td><td>" + e + "</td></tr>"
}
return retTable
}
How would be correct to combine the data from two different URLs? Please advise.

I can't hammer out a really robust solution right now, but here is what I came up with: https://jsfiddle.net/heejse8h/
Basically the principal is that you place all the URLs in an array and keep a flag variable incrementing for every url you pull from. This might look like this:
urls = [
'/url/status',
'/url/status2'
];
var i = 0;
Then when you execute the AJAX, you'll want to store that in some array
var result = [];
For my AJAX call in the jsfiddle, I used this basic structure
$.ajax({
url : urls[i],
type: "GET",
success: function(data) {
// simplified example of storing the results
// the example code from the fiddle is more
// involved.
result[key].push(data);
if(urls[++i] !== undefined){
// if there is another URL, use the same
// ajax object (using `this`), extend it,
// changing only the URL, and call it.
// the important part is that the `this`
// object has a reference to the currently
// executing `success` method.
$.ajax($.extend(this, {url: urls[i]}));
} else {
// otherwise, we're at the end of our URLs
// and we can focus on final formatting and
// display of the data.
for( key in result ){
$('#mytable').append("<tr><td>" + dropDownList(key) + "</td><td>" + key + "</td>" + result[key].join('') + "</tr>");
}
}
}
});
In the end I would have liked to flesh this out and use the DOM API to actually create nodes rather than constant concatenation, but this solution already diverges from the original code quite a bit. You might want to consider creating a function that parses an object rather than relies on concatenation.

Related

How to iterate through json arrays

I'm stuck in a script here, not sure how to get it to print in the div I set up. I imagine it's something related to how I'm handling the response.
The response in chrome devtools looks like this:
{
"[\"record one\", \"/description\"]": 0
}
I've attempted to use both each and map to iterate the data out but so far not going anywhere. I'm brand new to js and jquery, so the script is mostly from reading and examples.
Maybe some kind of nested loop? Here is my code -
$(function() {
return $('#myslider').slider({
range: true,
min: 0,
max: 20,
values: [1, 20],
stop: function(event, ui) {
var max, min;
min = ui.values[0];
max = ui.values[1];
$('#range').text(min + ' - ' + max);
$.ajax({
url: '/dir_scan',
type: 'get',
data: {
min: min,
max: max
},
dataType: 'json',
success: function(response) {
var albums;
albums = response;
$.each(albums, function(index, obj) {
var albumname, artist, li_tag;
li_tag = '';
albumname = obj.AlbumName;
artist = obj.Artist;
li_tag += '<li>Artist: ' + artist + ', Album: ' + albumname + '</li>';
$('#result').append($(li_tag));
return console.log;
});
}
});
}
});
});
As Will said in the comments, the JSON looks off.
But, you're on the right track of using .each, as it looks that you're returning an array of objects.
Here's an example of what to do:
var li_tag = '';
$.each(albums, function(index, obj) {
var albumname = obj.AlbumName;
var artist = obj.Artist
li_tag += '<li>Artist: ' + artist + ', Album: ' + albumname + '</li>';
$('#result').append($(li_tag));
return console.log;
});
Additionally, 'albums' should be set to the returned response of the success function. You're potentially creating a bunch of headache to try and decipher from the window.location; especially since the json example looks malformed. And, any work done with the data returned from the ajax call, should occur in the success function.
Here is how iteration worked for this situation. Comments in code -
success: function(response) {
var albums;
// side issue - but I had to clear the div to get a complete refresh
$('#result').empty();
albums = response;
$.each(albums, function(key, value) {
var albumname, li_tag, path;
li_tag = '';
// I found I had to do this parseJSON call otherwise
// I had no correct key/value pair, even though I had set dataType
// to JSON
albumname = jQuery.parseJSON(key);
path = albumname[1];
li_tag += '<li ><a href=/album' + encodeURI(albumname[1]) + '>' + albumname[0] + '</a href></li>';
$('#result').append($(li_tag));
return console.log;
});
Actually, value in the code is just the index number, but I had the actual key/value pair separated by commas, so again the parseJSON seemed to be the only way it would work. This, despite trying things like split and substr. Hope my answer is clear if not I can edit.

how to store array of objects using localstorage fron one file to other file

I am new to localstorage.I am trying to store json data in one file and retrieving the data in other file.Below is my json data which i have fetched from an url.I have tried storing feeds data using using localstorage now i am tring to fetch the data in other html file.But i am getting only the final object from the feeds.How can i get all the feed objects in other file.
{
"channel":{
"id":9,
"name":"my_house",
"description":"Netduino Plus connected to sensors around the house",
"latitude":"40.44",
"longitude":"-79.9965",
"field1":"Light",
"field2":"Outside Temperature",
"created_at":"2010-12-14T01:20:06Z",
"updated_at":"2017-02-13T09:09:31Z",
"last_entry_id":11664376
},
"feeds":[{
"created_at":"2017-02-13T09:07:16Z",
"entry_id":11664367,
"field1":"196",
"field2":"31.507430997876856"
},{
"created_at":"2017-02-13T09:07:31Z",
"entry_id":11664368,
"field1":"192",
"field2":"30.743099787685775"
},{
"created_at":"2017-02-13T09:07:46Z",
"entry_id":11664369,
"field1":"208",
"field2":"28.280254777070063"
}]}
One.html:-(here i am storing all the feeds data)
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
localStorage.setItem('Created_at', feed.created_at);
var create = localStorage.getItem('Created_at');
console.log(create);
localStorage.setItem('Entry_id', feed.entry_id);
var entry = localStorage.getItem('Entry_id');
console.log(entry);
localStorage.setItem('Field1', feed.field1);
var fd1 = localStorage.getItem('Field1');
console.log(fd1);
localStorage.setItem('Field2', feed.field2);
var fd2 = localStorage.getItem('Field2');
console.log(fd2);
});
other.html:(here i am trying to fetch the localstorage data)
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var create = localStorage.getItem('Created_at');
console.log(create);
document.writeln("<br>Created_at = "+create);
var entry = localStorage.getItem('Entry_id');
document.writeln("<br>Entry_id = "+entry);
var fd1 = localStorage.getItem('Field1');
document.writeln("<br>Field1 = "+fd1);
var fd2 = localStorage.getItem('Field2');
document.writeln("<br>Field2 = "+fd2);
}
</script>
Because you are over-riding the localStorage item in your for Loop.
The required for loop when simplified looks like:
json1.feeds.forEach(function(feed, i) {
localStorage.setItem('Created_at', feed.created_at); //Gets over-riden on every iteration
localStorage.setItem('Field1', feed.field1);});
That's why after the loop is completed. The Created_at field would only have the value of the most recently processed item in the array i.e. the last element. What you need to is create a corresponding array where each element would correspond to a feed item that you are reading from the API response.
Now, localStorage can simply store key value pairs. It doesn't have support for types like array. What you can do is something on these lines (Untested Code):
json1.feeds.forEach(function(feed, i) {
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
feedsArray.push(feed);
localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
});
Yes, You will have to check if feedsArray key exists or not and set it as an empty array the first time. I have deliberately not put in the entire code as it is quite simple and should be good exercise for you.
So, once you are done and you want to read all the feeds from localStorage. Just get the feedsArray key and parse it and then iterate over it. Put simply, the basic idea is to have a JSON array of feeds and store it as a string with key feedsArray in localStorage.
The code snippet I have given above can get you started toward the solution I propose.
Relevant SO Post
The answer for the above issue is below.through which i got the solution.But not too sure if der is any wrong.
one.html:
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are :\nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
feedsArray.push(feed);
localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
for (var i = 0; i < localStorage.length;i++){
var savedArr =localStorage.getItem('feedsArray[i]')
}
});
other.html:
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
for (var i = 0; i < localStorage.length;i++){
var savedArr =localStorage.getItem('feedsArray[i]');
//feedsArray.push(savedArr);
}
console.log(savedArr);
document.writeln("<br>FEEDS = "+savedArr);
}
</script

How to construct and invoke method or function in generic jquery ajax call

I'm trying to construct a generic Ajax function by passing the few properties required by a jQuery Ajax object as object parameters. I'm stuck on one piece of the puzzle, that is the proper way to pass the callback function within "done". The idea is to replace about 10 ajax functions in my .js file with just one ajax function.
Here's my code:
// The generic ajax function, which will be called by various functions
// and passing variable parameters, different controller urls, different
// GET or POST types, different POST data sets, and finally, different
// callback functions.
function generalAjax(params){
$.ajax({
url: params.url,
type: params.type,
data : params.formData,
dataType : 'json'
}).done(function( data ) {
params.callback; // <-- Trying to get this line to work.
}).fail(function(jqXHR, textStatus){
var string = "Ajax request failed : " + textStatus + " - " + jqXHR.responseText;
$("#diag").html(string);
});
}
// Create the prototype
function ajaxParams(url, type, data, callback) {
this.url = url;
this.type = type;
this.formData = data;
this.callback = callback;
}
// A button in my php file will call this function.
function nameSearch(){
var url = "/ajax/name_search/";
var type = "POST";
var formData = { 'q' : document.getElementsByName("searchname")[0].value };
var callback = nameSearchCallback; // Specific method for this event
var params = new ajaxParams(url, type, formData, callback);
generalAjax(params);
}
// One specific callback function for one specific event trigger.
function nameSearchCallback(e){
var string = "";
$.each(e,function(k,v){
string += k + " = " + v + "\n";
if(v instanceof Object == true){
string += "<ul>\n";
$.each(v,function(kk,vv){
string += "<li>" + kk + " = " + vv + "</li>\n";
});
string += "</ul>\n";
}
});
$("#form-panel").html(string);
}
15 lines down, you can see where I've substituted parameters.callback for a hard coded script or direct call to a specific function. What I want is for that line to call different functions or methods, depending on the needs of the instantiated object calling the genericAjax function.
Depending upon whether I try params.callback or params.callback(), at best, nothing happens, or at worst, the page refreshes and in my javascript console I get a TypeError : a is undefined in the jquery library file.
I have also tried var callback = nameSearchCallback; and var callback = nameSearchCallback(); I have also skipping the reference to the nameSearchCallback() function, and just writing the function into params.callback as
params.callback = function(){
var string = "";
$.each(e,function(k,v){
string += k + " = " + v + "\n";
if(v instanceof Object == true){
string += "<ul>\n";
$.each(v,function(kk,vv){
string += "<li>" + kk + " = " + vv + "</li>\n";
});
string += "</ul>\n";
}
});
$("#diag").html(string);
}
I have a working solution to my problem, but it isn't a specific answer to my question. Since nobody is answering the question, I guess I'll post the general solution.
I came across a question with an answer on how to make dynamic functions using arrays. I applied this answer to the above question.
I declare an array:
var dyn_functions = [];
Every time I want to define a callback function, I write something like this:
// Where data is an object and data['string'] is a property returned in jsson format from a php controller.
dyn_functions['nameSearchCallback'] = function (data){
var string = "<h3>Search results:</h3>\n";
string += "<blockquote>" + data['string'] + "</blockquote>";
$("#form-panel").html(string);
}
Every callback function will have its own name.
Your event trigger will call its own function, something like
var n = "Mark";
<button onClick='nameSearch(n);return false;'>Search</button>
In your script file, the event function nameSearch looks like this:
function nameSearch(n){
var url = "/ajax/name_search/"; //This is the name of a php file or a function in an MVC controller
var type = "POST"; //This can also be GET
var formData = { 'q' : n }; //If your type is "GET", then this should be empty, like "", and you could pass `n` as a url query string or a uri segment.
var callback = "nameSearchCallback"; //Remember the dynFunction callback above? This is the name of it.
var params = new ajaxParams(url, type, formData, callback);//Make a params object to pass our params to the generic ajax function.
generalAjax(params); //Calling the generic ajax function.
}
You need to prototype the params property constructor:
// The prototype constructor for the general Ajax parameters.
function ajaxParams(url, type, data, callback) {
this.url = url;
this.type = type;
this.formData = data;
this.callback = callback;
}
...and finally, we have one single ajax function that serves infinite n of calls:
// The general Ajax function.
function generalAjax(params){
$.ajax({
url: params.url,
type: params.type,
data : params.formData,
dataType : 'json'
}).done(function( data ) {
var callback = dyn_functions[params.callback](data);
}).fail(function(jqXHR, textStatus){
var string = "Ajax request failed : " + textStatus + " - " + jqXHR.responseText;
$("#diag").html(string);
});
}
So, the whole thing all together will look like this:
// The prototype constructor for the general Ajax parameters.
function ajaxParams(url, type, data, callback) {
this.url = url;
this.type = type;
this.formData = data;
this.callback = callback;
}
// The general Ajax function.
function generalAjax(params){
$.ajax({
url: params.url,
type: params.type,
data : params.formData,
dataType : 'json'
}).done(function( data ) {
var callback = dyn_functions[params.callback](data);
}).fail(function(jqXHR, textStatus){
var string = "Ajax request failed : " + textStatus + " - " + jqXHR.responseText;
$("#diag").html(string);
});
}
//The global dyn_functions object, to be used for all scripts.
var dyn_functions = [];
dyn_functions['nameSearchCallback'] = function (data){
var string = "<h3>Search results:</h3>\n";
string += "<blockquote>" + data['string'] + "</blockquote>";
$("#form-panel").html(string);
}
function nameSearch(n){
var url = "/ajax/name_search/";
var type = "POST";
var formData = { 'q' : n }; //If your type is "GET", then this should be empty, like "", and you could pass `n` as a url query string or a uri segment.
var callback = "nameSearchCallback";
var params = new ajaxParams(url, type, formData, callback);
generalAjax(params);
}

GiantBomb API Work

I have made an account and have my api key currently i just want a simple search box and button that when hit will list the game and the image of that game
Have linked the site info below
http://www.giantbomb.com/api/documentation
I want to run is and get the output using json and jquery any help welcome
This is a working search now some what does not allow the user to enter in a new value and there is a problem bring up the image
two main problems wont load the image just says undefined and cant figure out how to make it a full search only when he user enters a new title
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "http://api.giantbomb.com/search/",
type: "get",
data: {api_key : "key here", query: "star trek", resources : "game", field_list : "name, resource_type, image", format : "jsonp", json_callback : "gamer" },
dataType: "jsonp"
});
});
function gamer(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td>' + value.image + '</td><td>' + value.name + '</td><td>' + value.resource_type + '</td></tr>';
});
table += '</table>';
$('#myelement').html(table);
}
</script>
</head>
<body>
<h1>Game Search</h1>
<input id="game" type="text" /><button id="search">Search</button>
<div id="myelement"></div>
</body>
</html>
Your working code as per standard of the giantbomb docs:
var apikey = "My key";
var baseUrl = "http://www.giantbomb.com/api";
// construct the uri with our apikey
var GamesSearchUrl = baseUrl + '/search/?api_key=' + apikey + '&format=json';
var query = "Batman";
$(document).ready(function() {
// send off the query
$.ajax({
url: GamesSearchUrl + '&query=' + encodeURI(query),
dataType: "json",
success: searchCallback
});
// callback for when we get back the results
function searchCallback(data) {
$('body').append('Found ' + data.total + ' results for ' + query);
var games = data.game;
$.each(games, function(index, game) {
$('body').append('<h1>' + game.name + '</h1>');
$('body').append('<p>' + game.description + '</p>');
$('body').append('<img src="' + game.posters.thumbnail + '" />');
});
}
});
http://jsfiddle.net/LGqD3/
GiantBomb Api example/explanation
First get your api key
Key: http://www.giantbomb.com/api/
Documentation: http://www.giantbomb.com/api/documentation
Your base url:
http://www.giantbomb.com/api/
Your url structure:
/RESOURCE?api_key=[YOUR_API_KEY]&format=json/FILTERS/FIELDS
/RESOURCE/ID example: /game/3030-38206/
The type of resource you which to return, in your case a search. Sometimes.. in case of a specific game you also want to pass in the ID under /ID (like in the example)
api_key
Your api key
You need this otherwise you cannot use the api :)
format
The format you which to output, in this case json.
FILTERS example: /search?limit=100
This manipulates the resourses output
See under the resources in the documentation for a what you can do.
FIELDS example: /search?field_list=description,
Which field to return, use this to "reduce the size of the response payload"
A game request for it's name & description would be:
http://www.giantbomb.com/api/game/3030-38206/?api_key=[YOUR-API-KEY]&format=json&field_list=name,description
A search request
Lets say we want to search for the game "Elder scroll online".
You would construct your url like this:
/search/?api_key=[YOUR-API-KEY]&format=json&query="elder scrolls online"&resources=game
To implement this in with $.ajax:
The ajax function
/*
* Send a get request to the Giant bomb api.
* #param string resource set the RESOURCE.
* #param object data specifiy any filters or fields.
* #param object callbacks specify any custom callbacks.
*/
function sendRequest(resource, data, callbacks) {
var baseURL = 'http://giantbomb.com/api';
var apiKey = '[YOUR-API-KEY]';
var format = 'json';
// make sure data is an empty object if its not defined.
data = data || {};
// Proccess the data, the ajax function escapes any characters like ,
// So we need to send the data with the "url:"
var str, tmpArray = [], filters;
$.each(data, function(key, value) {
str = key + '=' + value;
tmpArray.push(str);
});
// Create the filters if there were any, else it's an empty string.
filters = (tmpArray.length > 0) ? '&' + tmpArray.join('&') : '';
// Create the request url.
var requestURL = baseURL + resource + "?api_key=" + apiKey + "&format=" + format + filters;
// Set custom callbacks if there are any, otherwise use the default onces.
// Explanation: if callbacks.beforesend is passend in the argument callbacks, then use it.
// If not "||"" set an default function.
var callbacks = callbacks || {};
callbacks.beforeSend = callbacks.beforeSend || function(response) {};
callbacks.success = callbacks.success || function(response) {};
callbacks.error = callbacks.error || function(response) {};
callbacks.complete = callbacks.complete || function(response) {};
// the actual ajax request
$.ajax({
url: requestURL,
method: 'GET',
dataType: 'json',
// Callback methods,
beforeSend: function() {
callbacks.beforeSend()
},
success: function(response) {
callbacks.success(response);
},
error: function(response) {
callbacks.error(response);
},
complete: function() {
callbacks.complete();
}
});
}
search function
function search() {
// Get your text box input, something like:
// You might want to put a validate and sanitation function before sending this to the ajax function.
var searchString = $('.textox').val();
// Set the fields or filters
var data = {
query: searchString,
resources: 'game'
};
// Send the ajax request with to '/search' resource and with custom callbacks
sendRequest('/search', data, {
// Custom callbacks, define here what you want the search callbacks to do when fired.
beforeSend: function(data) {},
success: function(data) {},
error: function(data) {},
complete: function(data) {},
});
}
Example of a get game function
function getGame() {
// get game id from somewhere like a link.
var gameID = '3030-38206';
var resource = '/game/' + gameID;
// Set the fields or filters
var data = {
field_list: 'name,description'
};
// No custom callbacks defined here, just use the default onces.
sendRequest(resource, data);
}
EDIT: you could also make a mini api wrapper out of this, something like:
var apiWrapper = {};
apiWrapper.request = function(resource, data, callbacks) {
// The get function;
};
apiWrapper.search = function(data) {
// The search function
};
apiWrapper.getGame = function(id, data) {
// The game function
}
apiWrapper.init = function(config) {
var config = config || {};
this.apiKey = config.apiKey || false;
this.baseURL = config.baseURL || 'http://api.giantbomb.com';
}
apiWrapper.init({
apiKey: '[API-KEY]'
});
Have not tested the code, so there might be a bug in it, will clean it up tommorow :)
Edit: fixed a bug in $.ajax

Twitter API - no encoding

I'm currently working on a project for university. we are trying to use the twitter api but we are having some trouble with the query. I want to search a complete string, therefore I need to put my string in quote sings.( like "I'm seraching for this whole sting")
the problem is that the command I use to get the array from twitter somehow encodes the whole string but I need the quote sings to not be encoded. I hope you guys understand my problem. in addition i'll post my js code.
JS CODE: first I tryed a json command but it didnt work. afterwards I tryed ajax but I ran into the same problem. I don't get a response when I use quote signs in my query.
$( document ).ready(function()
{
console.log("ready");
// div mit id unique1 - bei klick mache onClick1
$('a#unique1').bind('click', onClick1);
});
function onClick1(elem)
{
var inputString = $("#SearchInput").val();
var EncodedString = encodeURI(inputString);
console.log('test' + inputString);
var endNode = 'search/tweets.json?q=hate%20' + EncodedString + '&result_type=mixed&count=200';
/*
$.getJSON('twitter/twitter-proxy.php?url='+encodeURIComponent(endNode),
*/
$.ajax({
type: "GET",
url: 'twitter/twitter-proxy.php?url='+encodeURIComponent(endNode),
data: " ",
success: function(twitterResponse){
var respStr = "start";
console.log(twitterResponse);
console.log(twitterResponse.statuses);
for(var i = 0; i < twitterResponse.statuses.length; i++)
{
$('.container .apiCall ol').append('<li>'+ twitterResponse.statuses[i].created_at + '</br>' + twitterResponse.statuses[i].text.toLowerCase() + '</li>');
respStr = respStr + twitterResponse.statuses[i].created_at + twitterResponse.statuses[i].text.toLowerCase();
}
}
});
/*
function(twitterResponse)
{
var respStr = "start";
console.log(twitterResponse);
console.log(twitterResponse.statuses);
for(var i = 0; i < twitterResponse.statuses.length; i++)
{
$('.container .apiCall ol').append('<li>'+ twitterResponse.statuses[i].created_at + '</br>' + twitterResponse.statuses[i].text.toLowerCase() + '</li>');
respStr = respStr + twitterResponse.statuses[i].created_at + twitterResponse.statuses[i].text.toLowerCase();
}
*/
/*
// respSgtr = " ";
// write tweets to file
$.post("writer.php", { fileString:respStr},
function(response)
{
//alert("Data Loaded: " + data);
});
});*/
}
Your approach is flawed.
jQuery does all the parameter encoding for you. Don't interfere, just pass an object which contains keys and values. Do not build URLs from individual bits of string.
Important security consideration: Don't build a server-side proxy script that accepts any arbitrary URL. Doing this is plain stupid.
Instead change your PHP script to accept a set of operation verbs, like "search", which are hard-wired to the correct URL on the server side.
I recommend using $.get() and $.post() over $.ajax(), for the benefit of cleaner code.
Further, use $.each() rather than a regular for loop. The resulting code will be cleaner and easier to read.
Avoid building HTML from bits of string. Especially if the bits of string come from a completely untrustworthy source, like Twitter. Use jQuery's capabilities and the DOM to build HTML safely. (read about XSS vulnerabilities if you're not sure why I bring this up)
Suggested solution (appendText() jQuery plugin taken from here):
$.fn.appendText = function(text) {
return this.each(function() {
var textNode = document.createTextNode(text);
$(this).append(textNode);
});
};
$(function () {
$('a#unique1').on('click', function (event) {
$.get('twitter/twitter-proxy.php', {
operation: 'search',
params: {
q: 'hate ' + $("#SearchInput").val(),
result_type: 'mixed',
count: 200
}
}).done(function (twitterResponse) {
$.each(twitterResponse.statuses, function (index, status) {
$("<li>")
.appendText(status.created_at)
.append("<br>")
.appendText(status.text.toLowerCase())
.appendTo(".container .apiCall ol");
});
});
});
});

Categories