Get JSON via javascript [Cross-Domain] - javascript

Please help me with the following situation:
there is the page p1.aspx with only one button:
<button id="btn1" onclick="btnclick();">Button</button>
<script type="text/javascript">
$('#btn1').click(function () {
$.getJSON("http://localhost/p2.aspx", function (data) {
$.each(data, function (i, field) {
alert(field);
});
});
});
</script>
Above is how I want to get the JSON text via javascript.
Web application http://localhost/p2.aspx is redirected to http://localhost/p3.aspx inside. And the page http://localhost/p3.aspx again is redirected back to
http://localhost/p2.aspx?code=1.
code=1
is the value I want read in my javascript code. But it's not works.
In p2.aspx I generate JSON data as following
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
Response.End();
After this I can not read json data via javascript. But if I just put the http://localhost/p2.aspx via web browser then it get json data on the page.

You need to use JSONP if you want that to work.
So your script should take into account the callback parameter:
Response.Clear();
string callback = Request["callback"];
if (!string.IsNullOrEmpty(callback))
{
Response.ContentType = "application/javascript; charset=utf-8";
Response.Write(string.Format("{0}({1})", callback, jsonString));
}
else
{
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
}
Response.End();
And then on the client:
$.getJSON("http://localhost/p2.aspx?callback=?", function (data) {
...
});
Notice how the callback query string parameter is set to ?. Basically jQuery will translate this to a request that looks like this:
http://localhost/p2.aspx?callback=jQuery123456789....
and your server side script should of course return JSONP which is your JSON string wrapped into the callback name:
jQuery123456789....({"code":1})
Also make sure that the jsonString variable used in your code is an actual JSON string (as its name suggests). Because what you have shown in your question (code=1) is very far from being JSON.

Related

Ajax data not reaching backend C# code

Below is the code which i m trying to send. As you can see, ajax call is made at UI and data 'sub' is passed through. this 'sub' has an array of objects in it. So data is present when it is passed.
UI SIDE
$scope.save = function () {
var sanit = $scope.gridOptions.rowData;
var sub = JSON.stringify(sanit);
$.ajax({
type: 'POST',
url: '/api/Pr/PM',
data: sub, //this has data in it
contentType: "application/json"
}).success(function (response) {
window.alert("Database updated successfully.");
})
};
However, when i debug the code at backend, the parameters is showing as null. i have commented the section showing this is null where the data is showing as null at the start of backend function.
BACKEND C# SIDE
[HttpPost]
public HttpResponseMessage PM([FromBody] string parameters) //this is null.
{
string message = string.Empty;
try
{
var model = JsonConvert.DeserializeObject<List<PODetails>>(parameters);
message = "Insert Successfull";
return Request.CreateResponse(HttpStatusCode.OK, message);
}
catch (Exception ex)
{
message = "Insert fail";
return Request.CreateErrorResponse(HttpStatusCode.NoContent, message);
}
}
Can someone please let me know why it is showing as null value at backend.
You need to ensure the data you're sending via AJAX is an object with a single parameter, which should be named the exact same as the parameter your backend is expecting.
In this case:
$.ajax({
type: 'POST',
url: '/api',
data: JSON.stringify({ parameters: sub }),
contentType: "application/json"
}).success(function (response) {
...
})
Next, if the variable "sub" is an array of objects then you must create a class model server side to match the structure of the data being sent. Then, your API's interface should be expecting a list of that newly created class.
For example:
[HttpPost]
public HttpResponseMessage PM(List<YourClassModel> parameters)
{
...
}
Your API should now be able to receive and read the data being sent via the AJAX call above.
Take a look at this: Post a json object to mvc controller with jquery and ajax
You are sending a list of objects but trying to recieve it as string. You should change your function parameter from (String parameters) to (List parameters) and change your ajax request according to the link above. That will probably solve your problem.
(ps: i couldn't try it myself that's why i said probably :) )

call regular asp from javascript in other domain

I have used dojo/dom from a javascript file before to call a php file on another domain that handles some database queries and returns the result to the javascript file.
The call to the php file was (i offcourse hope i can use the same call to asp)
postdata = dojo.toJson({ action: "get", userid: 1 });
require(["dojo/_base/xhr", "dojo/dom", "dojo/domReady!"],
function (xhr, dom) {
var xhrArgs = {
url: "http://otherdomain.com/file.php",
postData: postdata,
handleAs: "text",
load: function (result) { }
};
var deferred = dojo.xhrPost(xhrArgs);
In the php file i had
$foo = file_get_contents("php://input");
$postvalue = json_decode($foo, true);
to read the values from the dom call.
The reason i need to do this is because i get an error from the browser about a security risk because of the cross domain request.
So i think i need to use Jsonp
How do I write the php code in asp? NOT asp.net
Since your post data is JSON, the Request.Form won't be filled in, so you will have to use Request.BinaryRead and convert this result as a string.
See here to convert this JSON string into an object.

Receiving window keyword with JSON request using jQuery

Client side javascript:
var headFiles = {
Admin:{
JS:"/Path/to/file.js",
CSS:"/Path/to/file.css"
}
};
$.getJSON(URL_TO_SERVER, function (data) {
//My code here
});
Server side code:
Response.ContentType = "text/json"
Text been sent:
Response.Write("{" &
"""HTML"":""/cms/includes/admin_content.aspx"", " &
"""CSS_JS"":[" &
"{""Admin_JS"": headFiles.Admin.JS }," &
"{""Admin_CSS"": headFiles.Admin.CSS }" &
"]" &
"}")
$.getJSON fails to receive response. I have tried $.ajax also. I have tried setting ContentType to "text/plain" also.
The issue is that I am using javascript variable "headFiles" in the JSON, which is not been parsed.
Any idea how to send javascript variable as a part of JSON?
Try to use second parameter of getJSON like,
$.getJSON(URL_TO_SERVER,{headFiles: headFiles}, function (data) {
//My code here
});
And try this on server side
Response.Write('{"HTML":"/cms/includes/admin_content.aspx","CSS_JS":[{"Admin_JS":"headFiles.Admin.JS" },{"Admin_CSS": "headFiles.Admin.CSS"}]}');
check your json is valid or not
{"HTML":"/cms/includes/admin_content.aspx","CSS_JS":[{"Admin_JS":"headFiles.Admin.JS" },{"Admin_CSS": "headFiles.Admin.CSS"}]}
above json is valid tested on http://jsonlint.com/
Read getJSON

Getting JSON Object Result from $.post()

I'm attempting to call a web service via AJAX in a WebForms application.
My script looks something like this:
$.post('UpdateServer.asmx/ProcessItem',
'itemId=' + $(this).text(),
function (result) {
alert(result);
});
My web service looks something like this.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class UpdateServer : System.Web.Services.WebService
{
[WebMethod]
public string ProcessItem(int itemId)
{
return new JavaScriptSerializer().Serialize(
new { Success = true, Message = "Here I am!" });
}
}
The web method is called as expected and with the expected argument. However, the argument passed to my success function (last parameter to $.post()) is of type document and does not contain the Success and Message members that I'm expecting.
What's are the magic words so that I can get back the object I'm expecting?
EDIT
On closer inspection, I can find the data I'm looking for as follows:
result.childNodes[0].childNodes[0].data:
"{"Success":true,"Message":"Server successfully updated!"}"
The reason you're seeing that odd structure of nodes that end with JSON is because you're not calling the service the necessary way to coax JSON out of ASMX ScriptServices and then returning a JSON string anyway. So, the end result is that you're returning an XML document that contains a single value of that JSON string.
The two specific problems you're running into right now are that you're manually JSON serializing your return value and you're not calling the service with a Content-Type of application/json (.NET needs that to switch to JSON serializing the response).
Once you fixed those issues, you'd also run into an "invalid JSON primitive" error due to the data parameter being URL encoded instead of a valid JSON string.
To get it working, do this on the server-side:
[ScriptService]
public class UpdateServer : System.Web.Services.WebService
{
[WebMethod]
public object ProcessItem(int itemId)
{
return new { Success = true, Message = "Here I am!" };
}
}
You could also create a data transfer object (aka ViewModel) to return instead of using an anonymous type and object, if you want.
To successfully get raw JSON out of that, do this on the client-side:
$.ajax({
url: 'UpdateServer.asmx/ProcessItem',
type: 'post',
contentType: 'application/json',
data: '{"itemId":' + $(this).text() + '}',
success: function(result) {
// This will be { d: { Success: true, Message: "Here I am!" } }.
console.log(result);
}
});
If you have a few minutes, read through the posts in the communication section of jQuery for the ASP.NET developer. You'll find a lot of that information helpful as you continue down this path.
Note: The links that helmus left were relevant. Nothing has fundamentally changed between 2.0 and present with regards to using ASMX ScriptServices to communicate via JSON. If you're interested in the truly cutting edge approach to this problem in .NET, ASP.NET Web API is the way to go.
Add this attribute to your ProcessItem method:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Be more explicit in your $.post call.
$.ajax({
type:'post',
url:'UpdateServer.asmx/ProcessItem',
data: {'itemId':$(this).text()}
}).done(function (result) {
alert(result);
});

use javascript variable into python Block

I want to use JavaScript variable into python Block.
<script>
$(document).ready(function() {
$("#WO_cpp_id").change(function() {
id = this.selectedIndex;
ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id');
})
.change(); }); </script>
Thanks in Advance
Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.
One of those ways is "ajax". This client-side code will send the contents of the variable foo to the server as a "fooParameter" parameter on a POST:
var foo = "This is some information";
$.ajax({
url: "myscript.py",
method: "POST",
data: {fooParameter: foo},
success: function(responseData) {
// Successful POST; do something with the response if you want
},
error: function(jxhr, statusText, err) {
// Error, handle it
}
});
More in the jQuery docs and the Wikipedia article on ajax.
That won't work. Python runs on the server before the page is ever rendered on the client; Javascript runs in the browser after the page is rendered. The id variable isn't even set when the Python code runs.
Instead, you should have your javascript code add the extra data you want to set to an existing query string (or by using the data attribute of jQuery's ajax options).

Categories