I'm trying to post JSON between URLs in my app. The receiving URL expects JSON in the body of the request and responds with JSON in the body of the request. The problem is I can't seem to send JSON in the body using Mootools Request.JSON. This is what I have:
// formObj is an object constructed from a form
var request = new Request.JSON({
url: "/api/object.new",
urlEncoded: false,
onRequest: function(){
// swap submit button with spinner
},
onComplete: function(jsonObj) {
// work with returned JSON
},
body: JSON.encode(formObj)
});
request.setHeader("Content-Type", "application/json");
request.post();
The server returns a 500 error:
BadValueError: Property name is required
Which means that request.name is returning None which means that the server is not getting my JSON.
Using HTTPClient to paste the output of JSON.encode(formObj) into the body field produces the desired results.
body is not a valid mootools property for Request. use data: blah instead. as it stands, data is empty so no wonder you get nothing on the server side...
Related
I would like to send data to a Node.js server running on localhost with ajax. To test this, I wanted to send the input of type text to the server and just log it there.
This is my Post-Function (which is called by clicking on a button):
function answer(){
let data = {
name : $('#send').val()
};
console.log(data);
$.ajax({
type: 'POST',
url: 'http://localhost:3456/MyWebApp/Test',
dataType: 'text',
data: data.name,
success: console.log('post was successfull'),
error: function(textStatus, errorTrown){
console.log(textStatus + " " + errorTrown);
}
});
}
On my Server I try to collect the data with the following function:
app.post('/MyWebApp/Test', function(request,response){
console.log(request.body.data);
});
app.listen(3456);
My problem is, that the value on my server (in the above console.log) is always undefined.
I already tried to send the whole json-Object with dataType-Parameter json instead of text, but then I get an error in my server for trying to read a property value of something undefined. How do I have to implement the app.post function, to make the data readable and work with it?
I hope it is possible to understand what I am trying to achieve and what my problem is, I dont really know much about Node.js or Ajax, still I would be thankful for any help.
You're sending one string value data.name so your http request Content-Type would be plain/text
At NodeJS side you're using express library and it doesn't provide post request body by default.
You need to collect post request body using "data" event
request.on("data", callback);
I am running into problem requesting data from an API. The documentation states that I must make a post request. My goal is to make the request with jQuery, then style the resulting data.
Since I'm using a Cross-Domain-Request, I know that I have to use jsonp. The issue is that I get parseerror when I run this code because the server is returning an XML error. (The server defaults to an xml response if no format is specified)
$.ajax({
type: 'POST',
url: url,
data: {format: 'json'},
dataType: 'jsonp',
success: function(data) {
console.log("Success.");
},
error: function(data, error, err) {
console.log(data.status);
console.log(error);
console.log(err);
}
});
Inside the inspector I see:
Uncaught SyntaxError: Unexpected token <
menu?&callback=jQuery2240569993828256961_1469752734662&format=json&_=1469752734663:1
This is the XML response...
<?xml version="1.0" encoding="UTF-8"?><response> <response_header> <response_code>ERROR</response_code>
</response_header>
<response_details> <error_details>The post parameters contain an invalid or disabled API ID</error_details>
</response_details>
</response>
Because it returns XML, I can determine that the server is not even recognizing my parameter {format: 'json'}, because here is the same request in Python:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url = url # Set destination URL here
post_fields = {'format':'json'} # Set POST fields here
request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)
And the resulting JSON response:
{"response_header":{"response_code":"ERROR"},"response_details":{"error_details":"The post parameters contain an invalid or disabled API ID"}}
As you can see, it responds with JSON demonstrating that the server read the post request.
For some reason, the AJAX request is not sending the parameters through which means I can't even get back the actual data I need by including the api key + api id.
Can anyone tell me what is going on here?
Thank you.
There is a client-side JavaScript and server-side Python, powered by Django. There is a data object: foo_data = {"foo":1, "bar":2}.
Now, I would like to send a post-request using dojo/request/xhr, and send foo_data along with another variable:
xhr.post(document.location.href, {
data: {
'is_foo': true,
'data': foo_data
},
headers: { 'Content-Type': 'application/json' }
}).then(function(text){
console.log('The server returned: ', text);
});
And then read sent data in Django's views.py file:
def post(self, request, *args, **kwargs):
json.loads(request.body)
BUT, it doesn't work:
if I ssend foo_data, python doesn't recognize it correctly as JSON object and can't read it using json.loads.
I can't encode foo_data using JSON.parse because it is already an object!
request.POST is an empty QueryDict
request.body has string word object (instead of the real object)
Any ideas how to solve this?
Goal: send JSON object from JS --> Python and read it on server-side.
dojo.xhr has been deprecated, please consider using dojo/request more info here:
https://dojotoolkit.org/reference-guide/1.10/dojo/request/xhr.html#dojo-request-xhr
For a live example of post to a server, you can look source code for this page:
https://dojotoolkit.org/documentation/tutorials/1.8/ajax/demo/dojo-request-xhr-post.php
Here some a simple example of usage:
require(dojo/request"],
function(request){
// post the data to the server
request.post("your/server/script", {
// send your data here
data: { yourData: 1},
// wait 2 seconds for a response
timeout: 2000
}).then(function(response){
// do smt here when operation is successfully executed
});
}
);
Regarding your code sample in your question, you have't posted your server side code. But you could try to pass your data to the server using JSON.stringify().
I'm new to prototypejs. Can you guys tell me how to get serialized values from a posted form using Ajax in prototype?
http://www.prototypejs.org/api/ajax/request
Is this what you need?
http://prototypejs.org/api/form/serialize
Or you want to handle a form through ajax instead of page load? then
http://prototypejs.org/api/form/request
"how to get serialized values from a posted form using Ajax " Makes it sound like you're expecting the Ajax response to include the serialized data sent to the server, but what the response contains is entirely up to the server. Typically, once you make an Ajax request, the onComplete handler doesn't really care about the properties that it sent. The response argument to the onComplete (and any other Ajax callback) contains a request property, which contains parameters object. This would be useful if you did indeed need to see what your request sent to the server, like so:
$('customerdetails').request({
method: 'get',
onComplete: function(response) {
console.log(response.request.parameters); // What you sent to the server
console.log(response.responseText); // What the server sent back to you
console.log(response.responseJSON); // JSON-ified version of what the server sent back
}
});
It's possible for response.responseJSON to be null if Prototype isn't sure that the response actually contains JSON (if, for instance, the response headers were improperly set). If you can bank on the response being JSON, you could do something like this:
onComplete: function(response) {
var jsonObj = response.responseJSON || response.responseText.evalJSON();
// now you can work with jsonObj
}
Hope this helps and I didn't just completely misunderstand your question.
new Ajax.Request('your_ajax_url',{
method:'POST',
parameters:Form.serialize($('your_form_id'))
});
I'm trying to download, parse and show a list, from the XML received from my server using Backbone.js. The code is like:
var Item = Backbone.collection.extend({
url: "http://myurl.com/file.xml",
parse: function() {
console.log("parse");
},
success: function(data) {
console.log(data);
},
error: function() {
console.log("error");
}
});
var View1=Backbone.view.extend({
initialize: function() {
var item = new Item();
item.fetch();
}
});
When I check it in the Chrome extension, the XML file is getting downloaded but the breakpoints placed in the parse, success, error directly lands to the error.
And it has 3 arguments, but I'm unable to extract any information from that.
Backbone does not support fetching XML, hence, you'll need to override the sync method to provide your own custom parsing functionality. If you don't want to have to mess with Backbone internals, try doing your $.ajax GET first, parse your response into a proper JSON Array and then use that array with a Backbone#Collection-reset.
Backbone#Collection-fetch
The server handler for fetch requests should return a JSON array of
models.
Backbone#Sync
With the default implementation, when Backbone.sync sends up a request
to save a model, its attributes will be passed, serialized as JSON,
and sent in the HTTP body with content-type application/json. When
returning a JSON response, send down the attributes of the model that
have been changed by the server, and need to be updated on the client.
When responding to a "read" request from a collection
(Collection#fetch), send down an array of model attribute objects.