Jsonp request using jquery to fetch bing web results - javascript

using this as a guide: http://msdn.microsoft.com/en-us/library/dd250846.aspx
can someone help me with the jquery call?
Do I actually pass in the javascript code for the callback, or just the name of the function?
BingSearch = function($bingUrl, $bingAppID, $keyword, $callBack) {
$bingUrl = $bingUrl + "?JsonType=callback&JsonCallback=" + $callBack + "&Appid=" + $bingAppID + "&query=" + encodeURI($keyword) + "&sources=web";
$.ajax({
dataType: 'jsonp',
jsonp: $callBack,
url: $bingUrl,
success: function(data) {
alert('success');
$callBack(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + textStatus);
}
});
};
Update
Ok so I changed this to:
BingSearch = function(bingUrl, bingAppID, keyword, callback) {
var url = bingUrl + "?method=?&JsonType=callback&Appid=" + bingAppID + "&query=" + encodeURI(keyword) + "&sources=web";
$.getJSON(url, callback);
};
Calling it like:
BingSearch(url, appid, searchkeyword, function(searchresults) {
alert('yes!');
};
Still getting the 'invalid label' error.

To use do jsonp with jQuery, replace the JsonCallback=UserCallback with JsonCallback=?. jQuery will then handle it like a regular $.ajax() request.
I suggest starting out with $.getJSON() to get used to the Bing API and moving back to $.ajax() when your ready to integrate it with your application.
Using the example from the Bing API docs:
var apikey = 'YOUR_API_KEY';
var url = 'http://api.bing.net/json.aspx?AppId='+apikey+'&Version=2.2&Market=en-US&Query=testign&Sources=web+spell&Web.Count=1&JsonType=callback&JsonCallback=?';
$.getJSON(url, function(data) { console.log(data); });

jsonp: needs to be set to a string (I think it can also be left out), as this is just the name of the dynamically created function used to receive the JSONP.
But the formal parameter $callBack needs to be a reference to a function, so either you use
function callback(result){ /*processResultHere*/ }
BingSearch(..,..,.., callback);
or
BingSearch..,..,.., function(result){ /*processResultHere*/ });
And just so you know it, the excessive use of $ really hurts my eyes :)
Also, function names beginning with a capital should be reserved for 'classes', as many syntax checkers will complain on functions with capitals being called without new in front..

Related

Prototype to jQuery Conversion Confusion

I have the following function:
function updateproductselectionxxx(form, productassignment, mainproductid, subprodqty) {
var checkingurl = "shopajaxproductselection.asp";
var pars = 'productassignment=' + productassignment + '&qty=' + subprodqty + '&mainid=' + mainproductid;
var url = checkingurl + '?' + pars;
var target = 'productselectionresult' + productassignment;
var myAjax = new Ajax.Updater(target, checkingurl, {
method: 'post',
parameters: pars
});
}
And I am currently in the process of converting all the javascript on this website to jQuery. Usually I can use something similar to:
function updateproductselection(form, productassignment, mainproductid, subprodqty) {
$.ajax({
type: 'POST',
url: 'shopajaxproductselection.asp',
data: $(form).serialize(),
success: function (response) {
$(form).find('productselectionresult' + productassignment).html(response);
}
});
return false;
}
And that does the trick, however I really only want to send over 1 field as indicated in the first function and I would also like to send along the information I am sending directly to the function upon it being called. JavaScript is definitely not my area of expertise but usually I can muddle through, but this time everything I have tried has caused errors and I'm not getting very far. Any help would be greatly appreciated.
Looks like a bit of confusion between POST and GET. Although the request method is set to POST in the older Prototype version the params are being sent via CGI which normally appear on the server as a GET. It's a bit hard to say more without seeing the server-side code, but you could try this, such that the jQuery version more closely mimics the old Prototype version:
function updateproductselection(form, productassignment, mainproductid, subprodqty) {
var checkingurl = "shopajaxproductselection.asp";
var pars = 'productassignment=' + productassignment + '&qty=' + subprodqty + '&mainid=' + mainproductid;
var url = checkingurl + '?' + pars;
$.ajax({
type: 'POST',
url: url,
data: {},
success: function (response) {
$(form).find('#productselectionresult' + productassignment).html(response);
}
});
return false;
}
Note that I have added a hash # to the start of productselectionresult - this is crucial due to the difference in the way PrototypeJS works. In Prototype, you can use an ID selector like:
$('id')
whereas in jQuery it has to be:
$('#id')

jQuery Ajax failing to call to MVC 4 Controller method

I'm attempting to use jQuery in order to fire off an Ajax call after clicking a certain button. I've read several examples of the syntax and issues that may be encountered, but have failed to find a working solution for my cause. Here's the code.
Controller Method: (HomeController.cs)
[HttpPost]
public JsonResult ChangeCompany(string companyCode)
{
return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
}
jQuery Code:
function changeCompany(company) {
$.ajax({
url: '#Url.Action("ChangeCompany", "Home")',
type: 'POST',
data: JSON.stringify({ companyCode: company }),
success: function (data) {
alert("Company: " + data);
},
error: function (req, status, error) {
alert("R: " + req + " S: " + status + " E: " + error);
}
});
}
And finally, I'm calling this function with:
$('.companyButton').click(function () {
compCode = $(this).text();
debug("Click event --> " + $(this).text());
changeCompany(compCode);
});
My debug message displays properly, and the Ajax call constantly fails with the following alert: R: [object Object] S: error E: Not Found
I'm not entirely sure what to make of that.
I know there are several questions on this topic, but none of them seem to resolve my issue and I'm honestly not sure what's wrong with these code blocks. Any insight would be appreciated.
EDIT:
In case it's worth noting, this is for a mobile device. Testing on Windows 8 Phone Emulator (Internet Explorer), alongside jQuery Mobile. Not sure if that affects Ajax at all
EDIT 2:
After taking a look at the raw network call, it seems that 'Url.Action("ChangeCompany", "Home")' is not being converted into the proper URL and is instead being called directly as if it were raw URL text. Is this due to an outdated jQuery, or some other factor?
Ok with your EDIT2 it seems you are using url: '#Url.Action("ChangeCompany", "Home")', in a separate JavaScript file. you can only write the razor code inside the .cshtml file and it is not working inside the .js files
You are missing some important parameters in your AJAX call. Change your AJAX call as below:
function changeCompany(company) {
$.ajax({
url: '#Url.Action("ChangeCompany", "Home")',
type: 'POST',
data: JSON.stringify({ companyCode: company }),
success: function (data) {
alert("Company: " + data);
},
error: function (req, status, error) {
alert("R: " + req + " S: " + status + " E: " + error);
}
});}
You can then annotate your controller method with [HttpPost] attribute as below;
[HttpPost]
public JsonResult ChangeCompany(string companyCode)
{
return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
}
Note that your action is not returning companyCode directly. You're assigning it to Json result property therefore
In your success function to display result you need to have:
success: function (data)
{
alert("Company: " + data.result);
}
Also this: E: Not Found tells me that you may have some routing issues. If you set a break point inside of your ChangeCompany Action, is it being hit ?

display a javascript function

I am creating an API and I want to show a code example in javascript that you can use to invoke the API.
I write a test function in javascript. I would like to be able to execute AND display the code for the javascript function(s) but I would rather only have one copy of the code to make maintenance easier.
Example, I have the following code:
function doauth_test(apikey,username,userpass)
{
$.ajax({
url: "/api/v1.2/user.php/doauth/" + username + "/" + userpass + "?apikey=" + apikey,
type: "GET",
success: function(data,textStatus,xhr) {
var obj = JSON.parse(data);
var authkey = obj.authkey; //store this somewhere for subsequent use
var user_id = obj.user_id; //store this somewhere for subsequent use
},
error: function(xhr, ajaxOptions, thrownError) {
alert("ERROR! Status code: " + xhr.status + " Response Text: " + xhr.responseText);
}
});
}
I want this code to be something I can EXECUTE and I want it to display the code in a DIV in my documentation example. But I do not want to (ideally) have two copies of this code.
You can call toString() on a function to get its source code.
Alternatively, you can use the DOM to get the text of the <script> tag.
Just use toString method for your function and it will return your function definition as a string.
alert(doauth_test.toString());
Hope it helps!

What are the differences between Ajax & getJSON when calling an action method that return JSON

I am reading a book about asp.net MVC and I found different methods for calling Action methods that return JSON:, either using Ajax OR getJSOn, so are these two methods equivalent to:-
$.ajax({
type: "GET",
url: "http://localhost:11279/test/testcall",
dataType: "json",
success: function (result) {
var message = result.Title + ": $" + result.CurrentPrice;
$('#Result').html(message);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
And the getJSON is:-
<script type="text/javascript">
$(function () {
$.getJSON("http://localhost:11279/test/testcall",
function (data) {
$.each(data, function (key, val) {
var str = val.Description;
$('<li/>', { html: str }).appendTo($('#auctions'));
});
});
});
</script>
Second question
if I want to call the above action method or an external web service from a controller class instead of using javaScript, so which c-sharp methods I should use ?, and how I am going to pass the returned JSON from the controller class to the view.
BR
getJson-
Method allow get json data by making ajax call to page. This method allows only to pass the parameter by get method posting parameter is not allowed.
Ajax ()- This method provide more control than all other methods we seen. you can figure out the difference by checking the list of parameter
Provide more control on the data sending and on response data.
Allow to handle error occur during call.
Allow to handle data if the call to ajax page is successfull.
Answer to 2
You can make use of jquery + Ajax() function to consume it in your html page..
here is article for you : Steps to Call WCF Service using jQuery.
something like this
function WCFJSON() {
var userid = "1";
Type = "POST";
Url = "Service.svc/GetUser";
Data = '{"Id": "' + userid + '"}';
ContentType = "application/json; charset=utf-8";
DataType = "json"; varProcessData = true;
CallService();
}
//function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}

Save temporary Ajax parameters in jQuery

I am developing a heavily scripted Web application and am now doing some Error handling. But to do that, I need a way to access the AJAX parameters that were given to jQuery for that specific AJAX Request. I haven't found anything on it at jquery.com so I am asking you folks if you have any idea how to accomplish that.
Here is an example of how I want to do that codewise:
function add_recording(filename) {
updateCounter('addRecording','up');
jQuery.ajax({
url: '/cgi-bin/apps/ajax/Storyboard',
type: 'POST',
dataType: 'json',
data: {
sid: sid,
story: story,
screen_id: screen_id,
mode: 'add_record',
file_name: filename
},
success: function(json) {
updateCounter('addRecording','down');
id = json[0].id;
create_record(id, 1, 1, json);
},
error: function() {
updateCounter('addRecording','error',hereBeData);
}
})
}
hereBeData would be the needed data (like the url, type, dataType and the actual data).
updateCounter is a function which updates the Status Area with new info. It's also the area where the User is notified of an Error and where a Dismiss and Retry Button would be generated, based on the Info that was gathered in hereBeData.
Regardless of calling complete() success() or error() - this will equal the object passed to $.ajax() although the values for URL and data will not always be exactly the same - it will convert paramerters and edit the object around a bit. You can add a custom key to the object to remember your stuff though:
$.ajax({
url: '/',
data: {test:'test'},
// we make a little 'extra copy' here in case we need it later in an event
remember: {url:'/', data:{test:'test'}},
error: function() {
alert(this.remember.data.test + ': error');
},
success: function() {
alert(this.remember.data.test + ': success');
},
complete: function() {
alert(this.remember.data.url + ': complete');
}
});
Of course - since you are setting this data originally from some source - you could rely on the variable scoping to keep it around for you:
$("someelement").click(function() {
var theURL = $(this).attr('href');
var theData = { text: $(this).text(); }
$.ajax({
url: theUrl,
data: theData,
error: function() {
alert('There was an error loading '+theURL);
}
});
// but look out for situations like this:
theURL = 'something else';
});
Check out what parameters you can get in the callback for error.
function (XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info
this; // the options for this ajax request
}
You can use the ajax complete event which passes you the ajaxOptions that were used for the request. The complete fires for both a successful and failed request.
complete : function (event, XMLHttpRequest, ajaxOptions) {
//store ajaxOptions here
//1 way is to use the .data on the body for example
$('body').data('myLastAjaxRequest', ajaxOptions);
}
You can then retireve the options using
var ajaxOptions = $('body').data('myLastAjaxRequest');

Categories