web request from the user browser - c#

is it possible to send a web request from the user browser to another api and then process the result sent back??
im trying the following ajax code but its not working, i was wondering whether is it possible or not and if its a yes how can i implement it ...
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=xml",
dataType: "xml",
success: function(xml) {
alert("sucess");
$(xml).find('Ip').each(function() {
var ip = $(this).find('Ip').text();
alert(ip);
});
}
});
});

Due to same origin policy restriction you are pretty limited to sending AJAX requests to your own domain only. JSONP is a common workaround but the remote site needs to support it. Another workaround consists in crating a server side script on your domain which will serve as a bridge between your domain and the remote domain and it will simply delegate the AJAX request sent to it from javascript.

Should be possible, I have done the same.
BUT you have to have the pages on the same server, you cannot send a request to another server, in that case you would have to use a proxy on your server to relay the call.

Just to add to what was already said: if you can't create your own JSONP proxy, you can use YQL service which creates that proxy for you. Note that YQL will wrap your data with it's own meta data (unless there is a way yo disable that...).
By the way, you should use JSON output instead of XML output from your API service. JSON is a more lightweight format and as such is more adapted for Web.
Below is a fully functional example with your API URL (outputting JSON this time) and YQL:
var apiRequestUrl = "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=json";
var yqlRequestUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22";
yqlRequestUrl += encodeURIComponent(apiRequestUrl);
yqlRequestUrl += "%22&format=json&callback=?";
$.getJSON(yqlRequestUrl,
function(jsonData) {
alert(jsonData.query.results.json.Ip);
});
Finally, this article can come handy: http://www.wait-till-i.com/2010/01/10/loading-external-content-with-ajax-using-jquery-and-yql/

Related

URL to call the JSON WebService produced into ASP.NET

I have done a web service using Visual Studio 2012 into C#.
I'm usually use SOAP but now I need to use JSON.
So I've used this code to create a SOAP method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string test()
{
var testArray = new List<clienti>();
testArray.Add(new clienti() {nome = "Mark", cognome = "Reed", email = "mark.reed#test.com"});
var serializer = new JavaScriptSerializer();
return serializer.Serialize(testArray);
}
Can I call this method directly from an URL?
(that is the real goal that I want to obtain)
A stuff like this: http://ws.mysite.com/serice1.asmx/test.
If I try to type the URL with the name of the method after the slash not return data but an error on the URL format!!!
In debug mode all works perfectly if I click the button method
So the answer to your question is Yes I believe, but let's start for sure with an Ajax scenario that 100% works.
Something I want to clarify for you though, your "test()" method in service1.asmx is not a "Soap method" as you called it. Its a "Web Service method" and it returns JSON. It is callable using HTTP protocol or SOAP protocol. Because you added the [ScriptMethod] to the Web Method you can now call it using an HTTP Get request. If you remove the [ScriptMethod] attribute, you can only call "test()" with an HTTP POST request or a SOAP request.
The following jQuery Ajax call will work with service1.asmx/test:
$.ajax({
type: "POST",
url: "Service1.asmx/test",
data: "{ ifTestHadAParameter: 'hello world'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = JSON.parse(data.d); // data.d is a JSON formatted string, to turn it into a JSON object
// we use JSON.parse
// now that myData is a JSON object we can access its properties like normal
}
});
If you are using ASP.NET 3.5 or below, ASP.NET Web Services wrap JSON responses to HTTP Get and Post requests in an outer JSON {} to project against a certain type of hacking. Hence the data.d in my jQuery Ajax code snippet. If you using ASP.NET > 4.0 then, in your success function data contains your response from service1.asmx/test, no data.d required.
Now to call http://ws.mysite.com/serice1.asmx/test, this will not work in a "browser" as you say but you probably ultimately do not want to use the URL in a browser, that is just how you stated your question for simplicity.
You need to format your Get request correctly with http://ws.mysite.com/serice1.asmx/test.. So in C#, using the HTTPRequest .NET lib you should be able to prepare a proper HTTP Get Request to call your Web Services URL, basically simulating a browser request in your C# code if you have the right contentType in your Get request header.
A great tool to use for this problem is called Fiddler, you can easily create HTTP Get requests and change the content type.
No as asmx webservices have no router's like webapi or MVC best create a webapi project, add a controller with empty read write methods and return your array in there it will serialize automatically in JSON,XML or BSON default JSON (you can change this in the accept header in you client request) example method
public class mycontroller: ApiController
{
public string Get()
{
var testArray = new List<clienti>();
testArray.Add(new clienti() {nome = "Mark", cognome = "Reed", email = "mark.reed#test.com"});
return testArray ;
}
you can access the url like this site/api/controller

sending mail from outside of a website or asp.net application

is it possible to post data from an html page using Jquery to another asp.net website ?
say www.site1.com/mail.html - > www.site2.com/mailServ.aspx
using jquery ajax i could use this code to post to code behind [webmethod]
so instead of code within same website(site2) it will be sent from site1
this is the code i am using to post the form data to a web method within same website application
function jQuerySendMailCsCodeBehind(resluts) {
var SentClientinfo = []
SentClientinfo.push({ key: "SentClientinfo", value: resluts });
var CurrpageURL = "default.aspx/"; <---
var WebmethodName = "StartTest";
var StageIdentifyer = "stage1";
var Post_TargetUrl = CurrpageURL + WebmethodName;
jQueryAajaxNoPostBack(Post_TargetUrl, SentClientinfo, StageIdentifyer);
}
i tried to post from outside of application
so i just used
var CurrpageURL = "http://www.site2.com/default.aspx/";
from the other site (site1) html website non asp.net but the idea did not work in reality (:
so is there an option that a webForms application/ asp.net website
will accept requests from another website code of ajax/jquery ?
By default, JavaScript is not allowed to access other domains than the one it originated from for security reasons. You don't want the JavaScripts on my site to access your bank's web site, with your bank login cookie if you happen to be looking at my site while being logged in to the bank.
One way to work around it is JsonP, but as far as I've understood it it's mostly for retrieving data.
What you're probably looking for is Cross Origin Resource Sharing or short CORS. To implement that, your site2 would need to set a Access-Control-Allow-Origin header and the users would be required to use a browser that supports CORS (not all do, see the wikipedia page for info).
You cannot make cross-website requests with javascript. You need to use jsonp
jQuery supports jsonp, see the following example
$.ajax({
type: 'GET',
url: 'http://githubbadge.appspot.com/badge/torvalds',
dataType: 'jsonp',
success: function(json) {
var result = '<h3>' + json.user.login + '</h3>' +
'<p>Languages: ' + json.languages + '</p>' +
'<p>Followers: ' + json.user.followers + '</p>';
$('#badge').append(result);
}
});

The equivalent of C# consuming a WCF method in JavaScript (jQuery)

I have a running WCF service that exposes a method GetStuff(String type). It's called by the automatically created client class, so the syntax is embarrassingly simple.
ServiceClient client = new ServiceClient();
String response = client.GetStuff("other's");
client.Close();
The straight-forward question is this. How do I convert that to a call in JavaScript (possiblyusing jQuery) in an easy way?
After some serious googling, I concluded that I'm only going to find examples of how to consume a JSON-formatted stream using jQuery. I prefer not to touch the service-side of the software, if at all possible.
I tried the code below (along with a bunch of derivatives that I could think of) but the error I got was "No Transport" and googling that didn't yield anything that I got me going.
$.ajax({
type: "GET",
url: "http://hazaa.azurewebsites.net/Service.svc",
success: function (response) { console.info(response); },
error: function (response) { console.error("Error! " + response.statusText); }
});
Will I have to write a totally different service that exposes the data in JSON format? How do I specify that the service is supposed to call this or that method? Am I out of luck and these convenience methods are for .NET clients only?
Please note that I've got another way of getting the data where I want, not using JavaScript at all but I'd prefer to see if this is (easily) doable too.
I would convert server method to use web invocation = WebInvoke attribute. Here you can specify uri for the method call.
Link to the info
Look into Jquery SOAP .. http://plugins.jquery.com/soap/ etc.
haven't tried it myself but it's the kind of thing you might be needing here.

Ajax - 'Origin localhost is not allowed by Access-Control-Allow-Origin'

I'm relatively new to Ajax and was just tasked with this cross-domain call. We have a text box on our web page that a user will use to preform a search of company names. By clicking a button next to the text box, the Ajax call will be requested. Unfortunately the web service is located in a separate domain, so this is naturally causing issues.
Below is my best attempt at making this work. I should also note, the purpose of this call is to return the results in an XML format, which will be parsed in the success portion of the request.
Here is the error message again:
Origin http://localhost:55152 is not allowed by Access-Control-Allow-Origin.
I'm at a loss as to what to do for a work-around, any ideas would be greatly appreciated.
function GetProgramDetails() {
var URL = "http://quahildy01/xRMDRMA02/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,\'" + $('.searchbox').val() + "\')";
var request = $.ajax({
type: 'POST',
url: URL,
contentType: "application/x-www-form-urlencoded",
crossDomain: true,
dataType: XMLHttpRequest,
success: function (data) {
console.log(data);
alert(data);
},
error: function (data) {
console.log(data);
alert("Unable to process your resquest at this time.");
}
});
}
This error is due to the restriction enforced in cross-domain resource sharing. This has been implemented as a part of security feature to restrict the clients(domain) of a resource via cross domain calls. When you send a request to the webservice or api or similar, it adds Origin header in the request for the server or destination (here your api) to validate if the request is coming from an authorized source or not. Ideally the api/server should look for the Origin in the Request header it received and probably validate against the set of origins(domains) which it is permitted to serve the resources to. If it is coming from a permitted domain it will add the same domain in the response header as "Access-Control-Allow-Origin" value. wildcard is also permitted for this, but the issue is that with wild card permission any one can make a request and get it served (with some restrictions like an api is authenticated via windows auth or cookies where you need to send the withCredentials value * is not allowed). it is not a good practice to use wildcard origin the response header which makes it open to everyone.
These are some ways to set the response header with the values:-
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://yourdomain.com
you can even add multiple Access-Control-Allow-Origin headers in the same response (I believe works in most browsers)
Access-Control-Allow-Origin: http://yourdomain1.com
Access-Control-Allow-Origin: http://yourdomain2.com
Access-Control-Allow-Origin: http://yourdomain3.com
On the server side (c# syntax) you would do this:-
var sourceDomain = Request.Headers["Origin"]; //This gives the origin domain for the request
Response.AppendHeader("Access-Control-Allow-Origin", sourceDomain ); //Set the response header with the origin value after validation (if any) .Depending on the type of application you are using syntax may vary.
Hope this helps!!!

How to get page content using Javascript or JQuery

I will have a widget on a remote page. In the widget I want javascript or jquery to get all the article content from the webpage and send it back to my website. I only need just the article content and not all the other information on the webpage. I would like the script to send the remote webpage url, page content, title text, and h1 text. I would not like to receive any html tags. Is this possible to do?
The script I am making is like google adsense.
Also, Ill be using c# as my backend server
will something like this work?
http://blog.nparashuram.com/2009/08/screen-scraping-with-javascript-firebug.html
my suggestion, if it's not too much data would be to use a beacon.
var beac = new Image();
beac.onload = function () {
//do somethiringng on completion
}
beac.src = "youdomain/somthing.php?var=asdasd&key=someUniqueString";
This allows you to send a moderate amount of data to a server on another domain, provided you don't need anything back.
In short you can't do this, at least not in the way you were expecting. For security reasons there's a same-origin policy in place that prevents you from making requests to another domain.
Your best option is to do this on your server and make the request to it. I can't speak as to how you'd do this on the server since your question doesn't include which framework you're on, but let's say it's PHP, then you'd have that page take a URL, or something you can generate the URL from, then return a JSON object containing the properties you listed. The jQuery part would look something like this:
$("a").click(function() {
$.ajax({
url: 'myPage.php',
data: { url: $(this).attr("href") },
dataType: 'json',
success: function(data) {
//use the properties, data.url, data.content, data.title, etc...
}
});
});
Or, the short form using $.getJSON()...
$.getJSON('myPage.php', { url: $(this).attr("href") }, function(data) {
//use the properties, data.url, data.content, data.title, etc...
});
All the above not withstanding, you're better off sending the URL to your server and doing this completely server-side, it'll be less work. If you're aiming to view the client's page as they would see it...well this is exactly what the same-origin policy is in place to prevent, e.g. what if instead of an article it was their online banking? You can see why this is prohibited :)

Categories