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);
}
});
Related
If I have this JavaScript function:
function fillMainStreetEvent(location) { // /AJAX Pages/Compute_Main_Street_Event.cshtml
$.ajax({
url: "/App_Code/ContentGenerator.cs/ContentGenerator.GenerateMainStreetEvents",
async: false,
type: "GET",
dataType: "html",
data: { page: location },
success: function (response) {
$("#MainStreetEvents").html(response);
},
error: function (jqXHR, textStatus, error) {
alert("Oops! We're sorry, there has been an AJAX error. The server responded with (" + textStatus + ": " + error + ").");
}
});
}
And I want to target the method: GenerateMainStreetEvents of the class: ContentGenerator in an external file named: ContentGenerator.cs, how do I do this?
This was my latest attempt to target a single method within my .cs file, however, I am not surprised that I couldn't get it working since guessing is a horrible way to begin writing syntactically correct code.
In the first line's comment you can see the string I would normally use to point to an external cshtml file, which, functionally would serve me fine, especially since I can just call my external .cs file's method from there. However, I am trying to reduce hops across files and began researching for ways to do this, but came up empty handed.
In addition to:
/App_Code/ContentGenerator.cs/ContentGenerator.GenerateMainStreetEvents
I have tried this:
/App_Code/ContentGenerator.cs/ContentGenerator/GenerateMainStreetEvents
This:
/App_Code/ContentGenerator.cs.ContentGenerator.GenerateMainStreetEvents
And this:
/App_Code/ContentGenerator.cs/GenerateMainStreetEvents
None of which have worked for me, considering my environment. The only online examples that I can find on how to do this involve PHP, classic ASP, or some other language I am not using with ASP.NET.
The answer here is probably something very simple, but since I have never targeted an external .cs file with AJAX before, I am all out of guesses and research is turning up no new ideas.
So to start - your App_Code directory in any ASP.NET application should NEVER serve content. This is to protect yourself from accidentally exposing your source code on your web site :) To get this rolling, you need to follow a few steps:
Create a new cshtml page named 'GenerateMainStreetEvents.cshtml'.
Inside of that page, add a razor block that invokes your GenerateMainStreetEvents function
After you have a list of objects in razor, you need to convert them into JSON. I suggest using JSON.NET, which is available on NuGet: http://james.newtonking.com/projects/json-net.aspx
Using Response.Write and Response.End to write out the JSON and end your HTTP response
Here is a really good example:
Retrieve JSON Array from jQuery Ajax call in asp.net webpages
Happy coding!
I'm doing a project for college where one WebSite sends commands to a Windows Forms application. This application is responsible for access to serial port and send and receive commands.
Communication between the Website and the Windows Forms application, I used Web Api, however after publishing, auditioning remembered that the localhost in a C # WebSite. Net's own site and not my Windows Forms application.
I changed the call to the Web Api directly use Ajax and not a controller.
In the examples I found I saw that I use JSONP, but I can not read the results and use it on my website.
The calling code and return seen by Chrome are below
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
jsonpCallback: "cmdTorre",
jsonp: "cmdTorre"
});
}
function cmdTorre(data) {
alert(data);
}
Response Header
Content-Length:10
Content-Type:application/json; charset=utf-8
Date:Tue, 10 Jun 2014 11:18:30 GMT
Server:Microsoft-HTTPAPI/2.0
Response
No Properties
Windows Forms APIController
namespace TCCWindows.Lib
{
public class GPSController : ApiController
{
[HttpGet]
public string Posicao()
{
var coordenada = TCCWindows.FormPrincipal.PegarCoordenadas();
return coordenada.Latitude + "|" + coordenada.Longitude + "|" + coordenada.Altitude;
}
}
}
First, you ajax call looks overly complicated try replacing it with :
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
success: cmdTorre,
error: function(err){
alert("You have a error"+err);
}
});
}
function cmdTorre(data) {
alert(data);
}
Please validate the new code carefully. I just typed it in here so can have errors. If this runs at this point you should probably see the error message. That is because your GPSController doesnt seem to be returning a valid JSONP (or JSON for that matter). Please read up on JSONP for more clarification but, I think if you modify your return statement to make it look like following, it should work. Assuming your controller is actually getting called and your network stuff is working:
return "cmdTorre({\"lat\":"+coordenada.Latitude+" , \"lon\":"+coordenada.Longitude+" });"
Basically your return string should look like following when printed on console:
function cmdTorre({
"lat": 23.34,
"lon":34.23,
"alt":50
});
Again I suggest you check the code I wrote for syntax issues as i just typed it up in here, but it should give you the idea.
So problems were:
The return string you are generating is NOT in JSON format
It is also not wrapped in a function call making it a invalid JSONP too.
Lastly my solution should get your code working and JSONP started but its not the right way to do things. Its more of a ugly hack. Your GPS controller should read the HTTP request for parameter called 'callback' which is a accepted convention for JSONP calls. Then instead of hardcoding the function name in the return statement, you should use the value of this callback parameter. Then you dont need to use a specific function like 'cmdTorre' in your jQuery. Instead a anonymus function like success:function(response){...} will work just fine.
Hope that helps.
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!!!
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/
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 :)