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.
Related
I'm making a jQuery AJAX call to my Rails app (all run on localhost) which is responding with Javascript. The javascript is running because I'm getting the alert. But, I would like to read the my_var variable in the js.erb file. However, when I try to look at the data parameter of the success function it sees the data as a string. So doing data.my_var is undefined.
js.erb file
var my_var = "hi";
alert('this ran');
javascript
$.ajax({
url: "/a/validate?a_id=" + "<%= params[:id] %>",
context: this,
dataType: "script",
data:
{
json_a: JSON.stringify(this.a),
model_to_validate: model,
target_class: target_class,
current_class: current_class
},
success: function (data, textStatus, jqXHR) {
if(!this.orderFormViewed) {
this.orderFormViewed = data.order_block_opened;
}
},
error: function (data) {
console.log("error in ajax validate call");
debugger;
}
})
That's because that's exactly what you told it to do with dataType: "script" - look at the dataType options below. The script is run in it's own context and so you won't see that variable (I believe). You're going to need to communicate differently if you want that set. Or if you just need data send json.
https://api.jquery.com/jQuery.ajax/
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
try to change your dataType to json if you only need to get an object and be sure your server return a json.
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.
I'm trying to assign the contents of an xml file to a var, like so:
var testing = $.load('xx.xml');
$('#display').text(testing);
but it's not working. I tried the ".load" function as suggested in:
How to assign file contents into a Javascript var
and I had a look at the page they suggest form the jquery website, but I can't find something specific to assigning the contents of the .xml file to the var as a string.
I appreciate this is probably very obvious & I am arguably being lazy, but I have been trying random things for a while & cannot figure this out.
Thanks
EDIT! I was loading up the contents inside the load function, i didn't mean this, it's now edited.
Firstly, $.load isn't a defined function in the latest jQuery source, nor is it documented on the jQuery site.
Secondly, assuming you haven't modified jQuery's global AJAX settings, jQuery.fn.load and other request functions will be asynchronous, so you can't just assign the result to a variable because the function returns before the request has completed. You need to use callback handlers.
Try using $.ajax with a callback function instead:
var testing;
$.ajax('xx.xml', {
dataType: 'text',
success: function (data) {
testing = data;
$('#display').text(testing);
}
});
Since you want the data as text and the file appears to be XML, we're using dataType to tell jQuery to return the data as a string.
There is no $.load function. What you probably want is jQuery.get:
var xml;
$.get("xx.xml", function(data) {
xml = data;
});
As the file is retreived asynchronously, you need to assign the result to the variable inside the callback, which is executed when the request returns successfully. Note however that if you try and run code that depends on xml after the .get call, xml is going to be undefined because the callback won't have run yet. For example:
var xml;
$.get("xx.xml", function(data) {
xml = data;
//Do stuff with data here
});
console.log(xml); //Most likely undefined because asynchronous call has not completed
If you are trying to insert the results into a DOM element, then you can use the .load method:
$("#someElem").load("xx.xml");
if you are trying to get an xml from your server using ajax, you may try something like this -
function getXml()
{
var contents;
$.ajax({ url :'/website/method', type: 'GET', dataType :'xml', async : false,
cache : true, success : function(myXml){
contents = myXml;
}
});
return contents;
}
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).
I'm using Google App Engine (Python) along with jQuery for Ajax calls to the server. I have a page where I want to load up a list of strings in Javascript from an Ajax call to the server.
The server method I want to invoke:
class BrowseObjects(webapp.RequestHandler):
def get(self):
ids_to_return = get_ids_to_return()
// TODO: How to return these ids to the invoking ajax call?
self.response.out.write(ids_to_return)
The HTML page where I want to be able to access the returned ids:
var strings_from_server = new Array();
$.ajax({
type: "GET",
url: "/get_ids.html",
success: function(responseText){
// TODO: How to read these IDS in here?
strings_from_server = responseText
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
My experience with Ajax is limited-- I've only used them to store data to the server (a-la POST commands) and so I really have no idea how to get data back from the server. Thanks in advance for all help
Edit: My final answer:
I've switched to a full Ajax call (to prevent from cross-domain requests) and also to handle 'error' callbacks. My working client method looks like:
$.ajax({
type: "GET",
dataType: "json",
url: "/get_ids.html",
success: function(reponseText){
strings_from_server = responseText
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
Note I specify the dataType as 'json'.
And my final server function, with sahid's answer, looks like:
class BrowseObjects(webapp.RequestHandler):
def get(self):
ids_to_return = get_ids_to_return()
# Note: I have to map all my objects as `str` objects
response_json = simplejson.dumps(map(str, ids_to_return))
self.response.out.write(response_json)
Thanks all!
The SDK of Google AppEngine provided by django the lib "simplejson".
from django.utils import simplejson
So your handler maybe it simply:
from django.utils import simplejson
class BrowseObjects(webapp.RequestHandler):
def get(self):
ids_to_return = get_ids_to_return()
response_json = simplejson.dumps (ids_to_return)
self.response.out.write(response_json)
There are a good article about ajax/rpc: http://code.google.com/appengine/articles/rpc.html
It's probably not the cleanest solution, but it will work. Since they are just IDs, it sounds like it's safe to push them directly into a string.
class BrowseObjects(webapp.RequestHandler):
def get(self):
ids_to_return = get_ids_to_return()
response_html = '["'
response_html += ids_to_return.join('","')
# Edit: since my ids are Key objects (not strings)
# I had to use the following instead:
# response_html += '","'.join(map(str, ids_to_return))
response_html += '"]'
self.response.out.write(response_html)
and
var strings_from_server = new Array();
$.getJSON("/get_ids.html", function(responseData){
strings_from_server = responseData;
});
You can check to see if the response was empty incase of an error, and you can use $.each to loop through the results.
I am using jQuerys getJSON feature to automatically parse the response. Since I'm just returning a json list, it will generate the array of data in the strings_from_server variable.