How to display twitter search parse? - twitter

My first question with Stackoverflow. How do I display/read twitter search parse data in my webpage?
Below is the code I am working with. I can see 15 object in console.log() but I have no idea on how to show this in web page view.
My coding is below:
$
.ajax({
url : "http://search.twitter.com/search.json?q=gaga&callback=?",
dataType : "json",
timeout:1000,
success : function(data)
{
console.log(data.results);
//console.log(data.results);
//$('#twitter').html(data);// parse data here
},
error : function()
{
alert("Failure!");
},
});

See if this helps http://jsfiddle.net/2cxfN/
$.ajax({
url : "http://search.twitter.com/search.json?q=gaga&callback=?",
dataType : "json",
timeout:1000,
success : function(data)
{
console.log(data.results);
//console.log(data.results);
//$('#twitter').html(data);// parse data here
$.each(data.results, function(i,o){
console.log(o);
$('<img/>', {src:o.profile_image_url}).appendTo('body');
$('<div/>').text(o.from_user).appendTo('body');
});
},
error : function()
{
alert("Failure!");
},
});​
Ah, I see you have a div with an id twitter - you would parse that HTML into what you want using the variables in each object that's in data.results, which I've extracted as o, then appendTo('#twitter');

Related

Do something beside load table

i have a datatable which i'm loading via Ajax.
in the server side i'm prepering the data for the table and prepare another data for another thing
i want, beside the table loading, to do another thing with the other data i've prepared
so i added to my ajax code a success event, but it replace the table loading and i only can do the other thing
i can't separate between the table loading and the other thing because they are connected, meanning the other thing is influenced by the table loading(changes)
i tried also fnDrawCallback but i don't know how to pass the data of the other thing
Here's the Ajax code with success event:
"ajax": {
"url": "/Entreaties/GetEntreaties",
"data": function (d) {
d.status = 0;
d.firstLoad = firstLoad;
d.jAdvanceSearch = JSON.stringify(new AdvanceSearch());
d.freeText = $("#table_filter input").val();
},
"type": "POST",
"dataType": "json",
success: function (data) {
$.each(data.contactWaySum, function (key, value) {
alert(key + ": " + value.ContactWay);
});
},
error: function (xhr, textStatus, errorThrown) {
console.log(xhr.responseText);
}
},
Thank you all for your help
If I understand you right, you were using the built in DataTable ajax but stopped because you wanted to do several things at once. If so, go back to using the DataTable ajax and used the dataFilter function to separate them out and apply them.
Here is an example:
// If your server side sends back somehting that looks like this for the data table (this is what it is expecting)
{draw:1, recordTotal:20, recordsFilter:20, data:dataSet }
// adjust your json to look like
// If the json object return looks like what the
{ dataTableData:{draw:1, recordTotal:20, recordsFilter:20, data:dataSet }, otherStuffData: otherData}
$("#sometable").DataTable({
// other data table stuff left out to save space
"serverSide": true,
"ajax": {
"url": "you url" ,
"data": function (ssp) {
// Do the stuff you need to to get your paramerters ready
// server side parameters (ssp) are documented at http://datatables.net/manual/server-side
// in addition to the ssp parameters, the name of the column is pulled from the table header column
return ssp;
},
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (a, b, c, d) { debugger; },
dataFilter: function (data) {
// call function or what ever you need to do with the other data here
doOtherStuff(data.otherStuffData);
// the web method returns the data in a wrapper
// so it has to be pulled out and put in the
// form that DataTables is expecting.
//return just the datatable data here
return JSON.stringify( data.dataTableData);
}
}
});

Loading failed error

I am getting Loading failed error when searching for something in a select2 box using ajax. My code is as follows:
$("#drugSearch").select2({
placeholder: "Search for a drug by drug id or name",
minimumInputLength: 3,
ajax: {
url: "#Url.Action("SearchDrug", "Drug")",
dataType: 'jsonp',
quietMillis: 100,
data: function (term, page) {
return {
query: term
};
},
results: function (data, page) {
debugger;
return {
results: data.drugs
};
}
},
formatResult: drugResult,
formatSelection: drugSelection,
escapeMarkup: function (m) { return m; }
});
function drugResult(drug) {
debugger;
return drug.Name + " (" + drug.DrugBankRef + ")";
}
function drugSelection(drug) {
debugger;
return drug.Name + " (" + drug.DrugBankRef + ")";
}
The breakpoints are also not hitting the above debugger; lines
My JSON is returned as:
{ drugs: {[...]} }
It also has the properties Name and DrugBankRef and I have confirmed a valid JSON is returned from the URL after searching.
What am I doing wrong here? Anything else you need to trace the issue?
I was using JSONP instead of JSON, changing the data type to JSON fixed the issue.
It is not an error. There is a real difference between JSON and JSONP. In JSONP, your JS will send in a supplementary parameter, named callback, that contains the name of expeted enclosing function name.
Select2 supports the two modes :
JSON, which expects { drugs: {[...]} } as data
JSONP, which provide a callbackName and expects callbackName({ drugs: {[...]} }); as data
Both works, and are correct, differents, way of processing.
Feel free to read http://en.wikipedia.org/wiki/JSONP

JQuery AJAX Call to MVC action , asking the Credentials in Windows Server 2008R2

I have a jquery ajax POST to a MVC Action (which returns action result). In that i retrive record from DB and store in Session and return partial view result . On my machine this works well, when deployed it in Windows Server 2008 R2 , A popup appears in the browser asking me to enter credentials (authentication required).
The jquery call:
var data = $('#SearchForm').serialize();
window.location.hash = '#/' + data;
$.ajax({
url: '/PromotionManagement/PromotionsSearch',
type: 'POST',
data: data,
beforeSend: function (xhr) {
$('#search-result').hide();
$('#divresetCancel').hide();
$('#divwait').show();
// console.log('before sending request...');
},
error: function () {
//console.log("error processing request...");
},
success: function (data) {
debugger;
//console.log("successfully processed request...");
$('#search-result').html(data);
$('#search-result').show();
$('#divwait').hide();
$("#validation").html("");
if ($(data).html() == '\n No Records Found \n ') {
$('#divresetCancel').hide();
}
else {
$('#divresetCancel').show();
}
}
});
MVC Action :
[HttpPost]
public ActionResult PromotionsSearch(string list,string query)
{
//code to retrive the data from DB.
Session["SearchPerameters"] = objSearchPerameters;
return PartialView("PromotionsGrid", Promotions);
}
I referred this link and stopped storing the data in Session.
Even though it didn't work .
Can you pls suggest me what is missing..
any help can be greatly appreciated.
This issue got fixed by changing the AJAX call url: '/PromotionManagement/PromotionsSearch' [controllerName/ActionName] as 'PromotionsSearch' [Only Action Name].

Rails - how to save text data with Uploadify?

I have a page, where I can put a text and to this text I would need to add several images. For uploading images I want to use Uploadify.
Now I am solving the problem, that when I choose images and send the form, the data are not sent, only the Uploadify start to transfer files. But the text information are not transferred.
I am doing it this way:
%script{:type => "text/javascript"}
- session_key = Rails.application.config.session_options[:key]
$(document).ready(function() {
$('#file_upload').click(function(event){
event.preventDefault();
});
$('#file_upload'). ({
'uploader' : '/uploadify/uploadify.swf',
'cancelImg' : '/assets/uploadify-cancel.png',
'multi' : true,
'auto' : false,
'queueID' : "file_queue",
'script' : '/users/#{params[:user_id]}/listings',
'onClearQueue' : true,
onAllComplete : function(queueData) {
$('#upload_next').removeClass('disabled');
},
'onComplete' : false,
'scriptData' : {
'_http_accept': 'application/javascript',
/'format' : 'json', ?????????????
'_method': 'post',
'#{session_key}' : encodeURIComponent('#{u cookies[session_key]}'),
'authenticity_token': encodeURIComponent('#{u form_authenticity_token}'),
'text1' : $('#text1').val(),
'text2' : $('#text2').val(),
'text3' : $('#text3').val(),
'text4' : $('#text4').val()
}
});
$('#photo_submit').click(function(event){
event.preventDefault();
$('#file_upload').uploadifyUpload();
});
});
Is there any way to attach these text data to upload? And also, how to make redirect when the upload (all data from form are saved) is done?
Thanks a million times!
This can done by sending your data along with the image using the formData attribute in uploadify.
scriptData attribute is not in use.
For setting up uploadify with rails you can visit
http://vignesh.info/blog/rails-4-uploadify-paperclip/

jQuery JsTree and JSON error handling

I am using MVC to pass JSON data to JsTree and show a hierarchical view of information.
Everything is working just fine, however, there are times when the user does not have access the the data or for some reason the MVC action throws an exception:
In these cases, the action passes a JSON error message and sets the HttpStatusCode to NotAccepted or InternalServerError.
However the jsTree's sinner keeps spinning and I don't seem to find a way to make it stop and show the error message.
Has anyone solved this issue before? How can one does error handling when using JsTree's JSON data plugin?
UPDATE:
I figured out how to capture the error:
$("#jstree1").jstree({
"json_data": {
"ajax": {
"url": serviceUrl,
"data": function (n) {
return { pid: n.attr ? n.attr("id") : "" };
},
"error": function (x, s, r) { var err = $.parseJSON(x.responseText); if (err!="") { alert(err); } }
}
}
It seems that JsTree does get the MVC http statusCode and the error, now I need to figure out how to tell the JsTree to stop waiting and remove the spinner image!
I am also looking for a good way of showing the error in JsTree, or should I manage the error message outside of it?
I've solved this problem.
Just a note- the code example above for handling ajax call errors is incorrect, please see a complete example below:
$('#YourTree').jstree({
"json_data": {
"ajax": {
"url": "/Controller/Action",
"data": function () {
return { Parameter1: "Value1", Parameter2: "Value2" }
},
"type": "POST",
"dataType": "json",
"error": function (jqXHR, textStatus, errorThrown) { $('#YourTree').html("<h3>There was an error while loading data for this tree</h3><p>" + jqXHR.responseText + "</p>"); }
}
}
});
And in the actual action, you need to set the http response status code to 1 and write the error. e.g.
Response.StatusCode = 1
Response.Write("Error you want to go into jqXHR.responseText here");
Enjoy :)
Maybe you should look into handling this error a layer above the .jstree. Maybe by handling the window.onerror event you can achieve this. In here you could call a function that will rebuild the tree or something? Be sure to include this script as the first one in your page.
<script type="text/javascript">
window.onerror = function(x, s, r){
alert('An error has occurred!')
}
</script>

Resources