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'))
});
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);
The service API I am consuming has a given GET method that requires the data be sent in the body of the request.
The data required in the body is a list of id's separated by hypen and could potentially be very large and thus it must be sent in the body otherwise it will likely foobar somewhere in the browsers/proxies/webservers etc chain. Note I don't have control over the service or API so please don't make suggestions to change it.
I am using the following jQuery code however observing the request/response in fiddler I can see that the "data" I am sending is ALWAYS converted and appended to the query string despite me setting the "processData" option to false...
$.ajax({
url: "htttp://api.com/entity/list($body)",
type: "GET",
data: "id1-id2-id3",
contentType: "text/plain",
dataType: "json",
processData: false, // avoid the data being parsed to query string params
success: onSuccess,
error: onError
});
Anyone know how I can force the "data" value to be sent in the body of the request?
In general, that's not how systems use GET requests. So, it will be hard to get your libraries to play along. In fact, the spec says that "If the request method is a case-sensitive match for GET or HEAD act as if data is null." So, I think you are out of luck unless the browser you are using doesn't respect that part of the spec.
You can probably setup an endpoint on your own server for a POST ajax request, then redirect that in your server code to a GET request with a body.
If you aren't absolutely tied to GET requests with the body being the data, you have two options.
POST with data: This is probably what you want. If you are passing data along, that probably means you are modifying some model or performing some action on the server. These types of actions are typically done with POST requests.
GET with query string data: You can convert your data to query string parameters and pass them along to the server that way.
url: 'somesite.com/models/thing?ids=1,2,3'
we all know generally that for sending the data according to the http standards we generally use POST request.
But if you really want to use Get for sending the data in your scenario
I would suggest you to use the query-string or query-parameters.
1.GET use of Query string as.
{{url}}admin/recordings/some_id
here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.
2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true
here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.
3.GET Sending arrays
{{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]
and you can access those array values at server side like this
let osValues = JSON.parse(req.query.os);
if(osValues.length > 0)
{
for (let i=0; i<osValues.length; i++)
{
console.log(osValues[i])
//do whatever you want to do here
}
}
Just in case somebody ist still coming along this question:
There is a body query object in any request. You do not need to parse it yourself.
E.g. if you want to send an accessToken from a client with GET, you could do it like this:
const request = require('superagent');
request.get(`http://localhost:3000/download?accessToken=${accessToken}`).end((err, res) => {
if (err) throw new Error(err);
console.log(res);
});
The server request object then looks like {request: { ... query: { accessToken: abcfed } ... } }
You know, I have a not so standard way around this. I typically use nextjs. I like to make things restful if at all possible. If I need to make a get request I instead use post and in the body I add a submethod parameter which is GET. At which point my server side handles it. I know it's still a post method technically but this makes the intention clear and I don't need to add any query parameters. Then the get method handles a get request using the data provided in the post method. Hopefully this helps. It's a bit of a side step around proper protocol but it does mean there's no crazy work around and the code on the server side can handle it without any problems. The first thing present in the server side is if(subMethod === "GET"){|DO WHATEVER YOU NEED|}
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.
I want to send a JSON object to a PHP file while my script opens that PHP file in a new popup window. Is it possible to send it via POST method (by jQuery or without it)?
If not, how do I convert JSON to a URL encoded string? Is there any JavaScript function?
You may create a form (on the fly) with an input (where you fill the value with the JSON) and a target-attribute regarding to name of the popup (second parameter of window.open()).
Then send this form.
Open the popup: var popup = window.open(...)
Assign the json object to a new variable in the new window: popup.json = ...
Use the variable json in your popup (it will be accessible as window.json or just json from JavaScript code running in the popup).
There's a JSON encoder/decoder that looks like it would do the job. You could call this to encode your object before adding it to your querystring.
Example
alert(JSON.encode([0,1,false,true,null,[2,3],{"some":"value"}]));
// [0,1,false,true,null,[2,3],{"some":"value"}]
alert(JSON.decode('[0,1,false,true,null,[2,3],{"some":"value"}]'))
// 0,1,false,true,,2,3,[object Object]
You can use the Ajax API to do so... In the Ajax API, you can specify the data property and set it a JSON, and it will send the data to the server based on the type you have set, that is, GET or POST.
For example:
$.ajax(
{
url: url, // Your post URL
type:"POST", // or GET
data: {a:1} // In your case, your JSON object
success:function(response){}, // Function that will be called when your posted URL responds
crossDomain: true, // If it's a cross-domain request
dataType: "json" // Response datatype: JSON, text, HTML, XML, etc.
}
);
One thing to note is that if your response needs to be processed, you need to get around the same origin policy set by the browser. Please read about the same. You could use something called JSONP. It's part of the Ajax API.
I hope this is what you want.
Hello I have a form that submits remotely with the jQuery UJS for rails. I binded to the beforeSend event to allow me to modify the data submitting to the serve. It's not working. Here is what I have in the beforeSend:
settings.data = JSON.stringify({
'list_item[title]' : 'hi?? there'
})
This doesn't work. In the server logs I see this:
Started POST "/lists/9/list_items" for 127.0.0.1 at 2011-10-24 14:04:36 -0700
Processing by ListItemsController#create as JSON
Parameters: {"{\"list_item"=>{"title"=>{"\":\"hi?? there\"}"=>nil}}, "list_id"=>"9"}
Any idea what I'm doing wrong? I want to customize the settings.data with added fields that aren't in the form. Thanks
You don't need to stringify anything to put it in settings.data. The data is:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. [...] Object must be Key/Value pairs.
What you're doing is putting this string:
"{"list_item[title]":"hi?? there"}"
into data but that string is not a query string so things are going to get confused. You should be able to simply assign your JavaScript object to settings.data:
settings.data = { 'list_item[title]' : 'hi?? there' };
and let jQuery sort it out from there.
Update based on evidence rather than documentation:
However, further investigation reveals that this doesn't work. If I send a GET request, any changes I make to settings.data are ignored but if I send a POST request, then changes to settings.data stick but you have to use the query string format to get anything sensible through:
settings.data = encodeURIComponent('list_item[title]')
+ '='
+ encodeURIComponent('hi?? there');
The version of settings.data combined with a POST request gets me this:
Parameters: {"list_item"=>{"title"=>"hi?? there"}}
on the server and that looks like what you're after. If you want to preserve some of the original parameters then you'll have to unpack and repack the query string by hand.