How to get more than 20 tweets with Bluemix Twitter Insights? - ajax

I'm using this code to create a Twitter Insight app in Bluemix. However, I can't find any documentation on how to increase the number of tweets retrieved by the API. I tried using size and count as parameter in the query but without result. Is it possible to get more tweets?
$.ajax({
url:'/api/search/',
type: 'GET',
contentType:'application/json',
data: {
q: term,
size: 100
},
success: function(data) {
// do stuff
},
error: function(xhr, textStatus, thrownError) {
// do error stuff
}
});

The server side code you are using has a hard coded value of 20 for the number of tweets returned in the app.js file:
var MAX_TWEETS = 20;
// callback - done(err, data)
function insightRequest(path, query, done) {
request({
method: "GET",
url: insight_host + '/api/v1/messages' + path,
qs: {
q: query,
size: MAX_TWEETS
}
}, function(err, response, data) {
You have to modify that value for the max number you want to return, or make a parameter you can pass to function.

Related

How to call continues Ajax requests in background without disturbing front-end page

I want to develop a report page with continues ajax requests which is retrieves a bunch of record sets for each call to complete the entire report,
i.e ,
i want to display a 1000 of student records and for retrieving whole 1000 records makes more loading time which is need to be avoided. so i just created a loop of ajax requests which fetch 100 records for each request. In this case the browser holds until the total of 1000 records displays ...i want to avoid this i want to run the ajax requests in background and it not should disturb or hold the browser to see the first 100 records..
while( loop until the whole records retrived ){
$.ajax({
url: "/erp/reports/json/student_report/",
type: "POST",
dataType: "json",
data: {class_id : id},
success: function (json) { // retrieve 100 records }
});
}
Or tell me that do i approached wrong way can i achieve this using react is possible?
thanks in advance
This will make sure you call the next ajax request right after the first one finishes.
function fetchRecords(id){
$.ajax({
url: "/erp/reports/json/student_report/",
type: "POST",
dataType: "json",
data: {class_id : id},
success: function (json) {
// retrieve 100 records
// DO WHAT EVER YOU WANNA DO HERE
if(! the whole records retrived )
fetchRecords(id)
}
});
}
You should use a recursive function and javascript timeout.
That is, you make a function for ajax, then call the function by timeout recursively.
Please take a look my sample code.
This is a function to get all records more than 1000 by 100 records per page.
It should be refined as you wants
function clickedOrder() {
orderPageIndex = 0;
orderCnt = 0;
importOrder();
}
function importOrder() {
orderPageIndex++;
$.ajax({
type: 'POST',
url: './order.php',
async: false,
data: {pageIndex: orderPageIndex, orderCount: orderCnt},
success: function (result) {
console.log(result);
if (result.indexOf("OK") == 0 || result.indexOf("Zero") == 0) {
alert("imported successfully");
} else if (result.indexOf("ERROR") == 0) {
alert("Import Failed" + result);
} else if (result.indexOf("Order")==0) {
var strCnt = result.substring(result.indexOf(":") + 1);
orderCnt += strCnt*1;
startOrderTimer();
} else {
alert("Import Failed" + result);
}
},
error:function(error){
alert(error);
}
});
}
function startOrderTimer () {
setTimeout(stopOrderTimer,100);
}
function stopOrderTimer () {
importOrder();
}

ajax POST a JSON array to nodejs server removes keys

RESOLVED! see solution at bottom of this post...I have been stuck on this problem for about 2 days now and it's starting to get to me. I am trying to POST a Json array to my node server (cross-domain) and insert it to a cloudant db. This question is more about just getting the json over in the correct format. Here is my client side json and ajax:
function stress(){
var start = new Date().getTime();
$.ajax({
type: 'POST',
url: 'url/',
crossDomain: true,
data: JSON.stringify(products),
dataType: 'json',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function(responseData, textStatus, jqXHR) {
var end = new Date().getTime();
var millis = (end - start);
var duration = (millis/1000);
alert(responseData.msg +'Duration(seconds): ' + duration);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
}
});
}
var products = [
{
name: 'War Room Table',
year: '2005',
color: 'tan',
country: 'USA',
description: 'A Beautiful War Room table. Includes all 4 legs!',
usaDollarPrice: 150
},
{
name: 'Power Strip',
year: '2000',
color: 'white',
country: 'USA',
description: 'A very old power strip, may or may not protect against power surges.',
usaDollarPrice: 16
}];
My Node.js server side:
exports.create = function(req, res) {
var data = req.body;
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json');
//var parsed = JSON.parse(data);
var msg = {};
for(product in data){
db.insert(data[product], function (err, body, headers) {
if (!err) {
msg.msg = 'success!';
console.log(JSON.stringify(msg);
}
else {
msg.msg = 'Error on insert, maybe the item already exists: ' + err
console.log(JSON.stringify(msg);
}
});
}
}
I have tried a multitude of different things. What I basically want is a object on the server side that I can iterate through and insert to the cloudant database, each as a separate doc. I have tried many combinations of JSON.stringify and JSON.parse. using parse has given no luck as I get an error saying SyntaxError: Unexpected token o which I read that means it is already an object, but I cannot access data in any way ( data[0], data.name, data[0].name, nothing on the server side). I have also tried sending the json from the client side in different ways (in ajax - data: JSON.stringify({prod:products}) and still no luck.
Having the json on the server side (same as products above) inserts the docs in the correct order, the problem is when I sent that same json over a ajax post and to a cross-domain server. I cannot get that json out. Any idea or help would be very appreciated, thanks
Solution:
I ended up putting the object into another array and using that to be sent to the server. Here is the working ajax in the client side, notice the data:{data:products} that's what did it for me. Also below is the products json and also how to access it on the nodejs server side.
$.ajax({
type: 'POST',
url: 'url/',
crossDomain: true,
data: {data:products},
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
var end = new Date().getTime();
var millis = (end - start);
var duration = (millis/1000);
alert(responseData.msg +'Duration(seconds): ' + duration);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
}
});
var products = [
{
name: 'War Room Table',
year: '2005',
color: 'tan',
country: 'USA',
description: 'A Beautiful War Room table. Includes all 4 legs!',
usaDollarPrice: 150
},
{
name: 'Power Strip',
year: '2000',
color: 'white',
country: 'USA',
description: 'A very old power strip, may or may not protect against power surges.',
usaDollarPrice: 16
}];
Here is how to access it on the server side. Keep in mind this is all for cross-domain Post, but should work otherwise.
exports.create = function(req, res) {
var body = req.body;
//body.data[0] will get you the first object in the json, in this case it will be the war room table.
//If you use console.log to see it make sure you JSON.stringify(body.data[0]) or else you wil see [Object] [Object]
Also very important to include this in your server/app.js The extended: true part is important. Example
app.use(bodyParser.urlencoded({ extended: true }));
You are stringifying the json data before sending it to the node server, try only
data:products You will also need the node module body-parser using it you will be able to access POSTed data through ajax, see this answer also
I am new to ajax. Please check if this helps. I think I had a similar problem which is solved now.
Please see the answer posted by me
How to send array of arrays as data in $.ajax()?

Making an Elastic Search filtered query in Ajax

I need to make an Elastic Search query with Ajax. What I'm trying to do is search for a specific category name, and return the list of names associated with that category. The structure in Elastic Search is that each _source has a name fields (the name of the category), and an items fields. It also has name.raw so that I can search by exact name.
This is my request:
var query = {
query: {
filtered: {
filter: {
term: { "name.raw": category }
}
}
}
}
$.ajax({
url: "http://192.168.0.240:9200/dropdowns/category/_search",
type: 'post',
dataType: 'json',
success: function(data) {
alert("Success");
},
error: function(data) {
// should be only one item in hits
$(data.hits.hits).each(function(index, hit) {
alert(hit._source.items);
});
},
data: query
});
For now, I'm trying to simply get it to work enough to alert me to the items in the hit. I'm getting a 400 Bad Request error. What's wrong with my Ajax call?
With help from Jonathon Lerner, I figured out that the problem with my query was that it had to be stringified. So, I simply changed it to
data : JSON.stringify(query)
You should be able to send the query in the URL using a GET method, with this syntax:
var query = '{"query":{"filtered":{"filter:{"term":{"name.raw": category}}}}}';
$.ajax({
url: `http://192.168.0.240:9200/dropdowns/category/_search?
source_content_type=application/json&source=${query}`,
success: function(data) {
console.log(data);
}
});
Using the following code:
var query = {
query: {
filtered: {
filter: {
term: { "name.raw": category }
}
}
}
};
$.ajax({
url: "http://192.168.0.240:9200/dropdowns/category/_search",
type: 'GET',
dataType: 'json',
success: function(data) {
console.log('Success');
$(data.hits.hits).each(function(index, hit) {
console.log(hit._source.items);
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
},
data: query
});
you should be able to debug the problem with your query in the Javascript Console, as well as see successful output. Here are some directions on how to see the JS console in different browsers: https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
Edit: It seems like those directions are for Windows specifically. I know that on Mac, Command+Option+j opens the Chrome JS console. Im sure if your browser/OS isnt covered here you can find the correct shortcut on Google.
The HTTP libraries of certain languages (notably Javascript) don’t allow GET requests to have a request body.
See this: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/_empty_search.html
So I think it's correct to use POST method here, you simply forget to stringify the request body.

ajax doesn't not enter success or failure when 0 rows returned

I'll like to know what happens when "echo json_encode($info);" from get.php returns 0 rows as there is no value in the db. And how can i get the function to work after it. From what I have tried, if 1 or more rows returned it goes into success function. However when 0 rows is returned nothing happens. Could i get some help with this?
$.ajax({
type: "GET",
url: "getBooking.php",
data: "id=" + $(this).find(":selected").val(),
cache: false,
success: function(msg) {
$("#facis").empty();
}
error: function() {
$("#facis").empty();
}
/*always: function() {
$("#facis").empty();
}*/
#Scott Selby
Thanks for your info, I manage to get it working after getting it to return a random value. Though I don't really have an idea why it doesn't gives error.
You have commented out the part that could solve your problem.
In always that is being called in any case you can check what is the response and based on that make decisions.
$.ajax({
type: "GET",
url: "getBooking.php",
data: "id=" + $(this).find(":selected").val(),
cache: false,
success: function (msg) {
$("#facis").empty();
}
error: function () {
$("#facis").empty();
}
always: function (response) {
// Check if response is empty and handle this case.
});

ajax GET call with node.js / express server

I´m trying to write a small ajax live search for node.js. First of all here is my Clientside code:
$('#words').bind('keyup', function(){
getMatchingWords($('#words').val(), function (data){
console.log('recieved data');
console.log(data);
$('#ajaxresults').show();
});
});
function getMatchingWords(value, callback) {
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
type: 'GET',
dataType: 'json',
success: function(data) { if ( callback ) callback(data); },
error : function() { if ( callback ) callback(null); }
});
}
and here ist my serverside route:
app.get('/matchword/:value', function(req, res) {
console.log(req.params.value);
res.writeHead(200, {'content-type': 'text/json' });
res.write( JSON.stringify({ test : 'test'}) );
res.end('\n');
});
it works but i don´t recieve any data. data in the callback function is always null. so what i am doing wrong? thx for the help
Change
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
to
$.ajax('/matchword' + value + '/', {
What's the URL that you're making the $.ajax() request from? If the page containing that client-side JS wasn't also loaded from 127.0.0.1:3000, the error you're seeing is due to the same-origin requirement on AJAX requests.
hey better late than never...
I was looking at your problem because I am also trying to put a simple live search together with an express.js back end.
first of all I put your url into a local variable. As I don't think that was your problem.
Particularly if your express / node log was showing a 200 response. then the url was fine...
It seems your function wasn't returning data (correct ?) if so try this.
var search_url = "..."// your url
function getMatchingWords(value, callback) {
$.ajax(search_url, {
type: 'GET',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
var returned_data = data;
console.log("returned_data ="+returned_data);//comment out or remove this debug after test
callback(returned_data);
},
error: function( req, status, err ) {
console.log( 'something went wrong', status, err );
}
});
}
you might also need to add / modify your headers subject to the set up...
headers : { Authorization : auth },
type: 'GET',
dataType: 'json',
crossDomain:true,
the auth variable being an encoded auth pair somewhere else in your code (if your web service is requires some kind of auth...

Resources