$.ajax({
type: 'POST',
url: '/users',
data: {
_method : 'PUT',
user : {
guides : {
step1 : true,
step2 : true
}
}
}
});
Is this saving correctly? I want this json data in a rails serialized field but It's saving incorrectly as follows below which is causing errors.
User.guided:
--- "{\"step1\"=>\"true\", \"step2\"=>\"true\"}"
Then when I do the following in the rails view:
guides = [<%= current_user.guides.try(:html_safe)%>];
It outputs with => instead of the expected :.
First of all you could try to use JSON.stringify() otherwise jQuery will use $.param() to serialize your data. But your main issue is that you want a JSON string, and not the YAML that is generated. As far as I now something like
guides = [<%= current_user.guides.to_json %>];
should do the trick. Also, maybe I'm not 100% sure but you probably don't need to use html_safe on this, because it's already escaped, although can't tell how it will be rendered in view
Related
I'm using ajax POST method
to send objects stored in an array to Mvc Controller to save them to a database, but list in my controller is allways empty
while in Javascript there are items in an array.
here is my code with Console.Log.
My controller is called a ProductController, ActionMethod is called Print, so I written:
"Product/Print"
Console.Log showed this:
So there are 3 items!
var print = function () {
console.log(productList);
$.ajax({
type: "POST",
url: "Product/Print",
traditional: true,
data: { productList: JSON.stringify(productList) }
});}
And when Method in my controller is called list is empty as image shows:
Obliviously something is wrong, and I don't know what, I'm trying to figure it out but It's kinda hard, because I thought everything is allright,
I'm new to javascript so probably this is not best approach?
Thanks guys
Cheers
When sending complex data over ajax, you need to send the json stringified version of the js object while specifying the contentType as "application/json". With the Content-Type header, the model binder will be able to read the data from the right place (in this case, the request body) and map to your parameter.
Also you do not need to specify the parameter name in your data(which will create a json string like productList=yourArraySuff and model binder won't be able to deserialize that to your parameter type). Just send the stringified version of your array.
This should work
var productList = [{ code: 'abc' }, { code: 'def' }];
var url = "Product/Print";
$.ajax({
type: "POST",
url: url,
contentType:"application/json",
data: JSON.stringify(productList)
}).done(function(res) {
console.log('result from the call ',res);
}).fail(function(x, a, e) {
alert(e);
});
If your js code is inside the razor view, you can also leverage the Url.Action helper method to generate the correct relative url to the action method.
var url = "#Url.Action("Print","Product)";
I'm trying to implement a custom suggestion engine using jquery.
I take the user input, call my codeigniter v2 php code in order to get matches from a pre-built synonyms table.
My javascript looks like this:
var user_str = $("#some-id").val();
$.ajax({
type: "POST",
url: "http://localhost/my-app/app/suggestions/",
data: {"doc": user_str},
processData: false
})
.done(function (data)
{
// Show suggestions...
});
My PHP code (controller) looks like this:
function suggestions()
{
$user_input = trim($_POST['doc']);
die("[$user_input]");
}
But the data is NOT posted to my PHP :( All I get as echo is an empty [] (with no 500 error or anything)
I've spent 2 days looking for an answer, what I've read in SO / on google didn't help. I was able to make this work using GET, but then again, this wouldn't work with unicode strings, so I figured I should use POST instead (only this won't work either :()
Anyone can tell me how to fix this? Also, this has to work with unicode strings, it's an important requirement in this project.
I'm using PHP 5.3.8
Try using the $.post method, then debug. Do it like this:
JS
var user_str = $("#some-id").val();
var url = "http://localhost/my-app/app/suggestions";
var postdata = {doc:user_str};
$.post(url, postdata, function(result){
console.log(result);
});
PHP
function suggestions(){
$user_input = $this->input->post('doc');
return "MESSAGE FROM CONTROLLER. USER INPUT: ".$user_input;
}
This should output the message to your console. Let me know if it works.
For those interested, this works for me, even with csrf_protection being set to true
var cct = $.cookie('csrf_the_cookie_whatever_name');
$.ajax({
url: the_url,
type: 'POST',
async: false,
dataType: 'json',
data: {'doc': user_str, 'csrf_test_your_name': cct}
})
.done(function(result) {
console.log(result);
});
Alright, so I'm making a quick edit on an exiting application, but I have never touched Grails before, so I apologize if this is not explanatory enough.
So, I have a JS controller for an set of input that needs parsing on the page. I also have a Grails function that need to take in the parsed data from the Javascript file. I've saved everything in a JSON object in the Javascript, and I need to pass it to the Grails function to be processed. Any ideas how? I've tried to find answers, but all of the answers go from Grails to JS not the other way around.
One way is to use jQuery. In your javascript code, you serialize your data to JSON:
var parameters = {
a : "a_value",
b : [1,2,3],
c : {
d : 'd_value'
}
}
$.ajax({
url: your_url,
data : JSON.stringify(parameters),
contentType : 'application/json',
type : 'POST'
})
then, in your controller, you can have an access to your data:
def parameters = request.JSON
//example access to parameters
assert parameters.a == 'a_value'
assert parameters.b == [1,2,3]
assert parameters.c.d == 'd_value'
Hope that should help!
I have some informations in a form to send to the server as a (complex) array (or Object if you prefer) with JS/jQuery. (jQuery 1.7.2)
I'm thinking about JSON to solve the problem smartly. My code works right now, but i want to know if its possible to do it better.
So this example is pretty typical (The data are more complex irl) :
dataSend = { 'id': '117462', 'univers': 'galerie', 'options' : { 'email': 'hello#world.com', 'commenataire': 'blabla', 'notation' : '4' } };
$.ajax({
url: "/ajax/ajaxMavilleBox.php",
data: JSON.stringify(dataSend),
success: function(x){
smth();
}
});
In an another context, i have to make the exact same thing without JSON.
With the same example :
dataSend = { 'id': '117462', 'univers': 'galerie', 'options' : { 'email': 'hello#world.com', 'commenataire': 'blabla', 'notation' : '4' } };
$.ajax({
url: "/ajax/ajaxBox.php",
data: $.param(dataSend),
success: function(x){
smth();
}
});
Obviously, I missing something.
The url is :
http://www.mywebsite.com/ajax/ajaxBox.php?id=117462&univers=galerie&options=%5Bobject+Object%5D
And the url should be :
http://www.mywebsite.com/ajax/ajaxBox.php?id=117462&univers=galerie&options[email]=hello#world.com&options[commenataire]=blabla&options[notation]=3
There is any easy way to do it (I hope I don't have to edit the data myself in a loop or something)
Edit : Solution for the second part
Ok, the last part without JSON is correct. In fact, i was using an older version of jQuery in my page.
$.param is not so good with jQuery < 1.4
More information here Param Doc
I would suggest setting the type: 'POST', otherwise you will have a data limit eqvivalent of the browsers query string length.
If you use the post method, you should send the data as a json-string. Something like:
data: { DTO: JSON.stringify(dataSend) }
You need to use json2.js if window.JSON is undefined (like in ie7 for example).
If you are using PHP on the serverside, you can fetch the object using:
$data = json_decode($_POST['DTO']); //will return an associative array
or ASP.NET
public class DataSctructure
{
public string id { get; set; }
public string univers { get;set; }
//etc...
}
var data = HttpContext.Current.Request.Form['DTO'];
DataSctructure ds = new JavaScriptSerializer().Deserialize<DataSctructure>(data);
//properties are mapped to the ds instance, do stuff with it here
as mentioned by #Johan POST shouldbe used here instead of GET
you can view data you are sending by using the Developer options in the browser you are using just press f12
also make sure you are using jquery >= 1.4
the incorrect serialized string in the url is the way that $.param() used to serialize prior to 1.4 version
I try to implement the following code
var flag = new Array();
var name = $("#myselectedset").val();
$.ajax({
type: 'post',
cache: false,
url: 'moveto.php',
data: {'myselectset' : name,
'my_flag' : flag
},
success: function(msg){
$("#statusafter").ajaxComplete(function(){$(this).fadeIn("slow").html(msg)});
}
});
You can see that the name is a single string and the flag is an arry, am I using the right format for passing them throw ajax call, anyone could help me, thanks
It is impossible to pass arrays in a POST request. Only strings.
You will either need to stringify your array, or consider posting as JSON instead.
You should be able to do something quite simple, like replace your "data" property with:
data : JSON.stringify( { myselectset : name, my_flag : flag } )
That will convert the data into a JSON string that you can turn into PHP on the other side, using json_decode($_POST["my_flag"]);
Very important note:
For JSON.stringify to work, there can't be any functions in the array - not even functions that are object methods.
Also, because this is a quick example, make sure that you're testing for null data and all of the rest of the best-practices.