Reading a JSON Object from a Javascript file - javascript

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!

Related

AJAX call how to retrieve my javascript variable

I work with Rails 4 and basically I am searching a value on my html webpage traversing the DOM with jquery.
I store the value in a variable named key and I want to use this value to then make a request that would look like this :
Record.find(id: key).name
I perform an AJAX call and it works well (I checked it rendering status json ok). But now how can I use/retrieve the parameter key in my controller ?
I have a User and a Record model. In the app/views/usersdirectory I have the partial _form.html.erb in which I am doing some javascript.
var key = $('input#record_id').val();
And I want this variable to be available in the method search of my user controller, so that I can make a request with the parameter key.
So I am doing an AJAX call that looks like this :
$.ajax({
url: "/search",
type: "POST",
data: {
value: key
},
complete: function(){
console.log('success');
}
});
And in my config routes file I wrote this route :
post '/search' => 'users#search'
In my User controller I wrote the method like this :
def search
#record = Record.find(params[:key])
end
Is #record available in my partial ? How can I print in my view the result of my request ?
Can anyone tell me if I am doing right or wrong for my AJAX call ? Thanks for any help. If I forgot to mention any information you might need tell me and I'll edit my post.
I added a complete function in my AJAX call, that is supposed to show successif the AJAX call had been done and in my console log I have this message 'success' that appears
For 404 not found the url must be wrong.
And to get the param key in your controller you must change data to data: {key: key} or if you use data: {value: key} then your action must change the name of the param like #record = Record.find(params[:level])
Basically, you are not using the right param name in your controller which is why the issue arises. Hope it helps.
To answer your second question:
#GDMN, you need to get your basics right! Every ajax has a success and failure callback.You could return json from your action which will be used by success callback and you could do whatever you want from there. Essentially in rails you might want to render a js file like this
Create a file named search.js.erb and use your javascript code in it like below
$('.some_id_or_class').html("<%= #record.name %>")
that will simply replace the element of that class with the value that is returned by #record.name
put the full url
url: "http://yoursite.domain/search",

Passing multiple arguments through HTTP GET

I have an HTML file referencing a PHP script to perform various functions. One of the ways the HTML file calls the PHP script is through an HTTP GET. The GET request should pass three parameters and return a list of all saved events as a JSON-encoded response.
So far, I have the following but I'm not sure how to pass the three arguments through the HTTP GET. Also, I'm not sure if I am returning the JSON-encoded response correctly:
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo json_encode(events.json); }
GET requests are done through the URL... So if you want to pass three GET requests you would do...
http://www.domain.com/target.php?param1=whatever&param2=whatever&param3=whatever
target.php represents the PHP script file you want to send the information to. You can have as many variables as you want but just keep in mind that every other GET request has to be separated by an & symbol. The first param simply has to be started off with a ? symbol.
If you want to use Javascript, I would recommend using JQuery. You can do something like this
$.get('target.php?param1='+whatever+'&param2='+whatever2, function(data) {
alert(data);
});
Or you can use window.location to send a link with the appropriate link above.
If you want to use AJAX specifically, here is a way of doing it with JQuery (there are ways with Javascript that I could update later if necessary:
$.ajax({
type: "GET",
url: "http://www.domain.com/target.php",
data: { param1 : "whatever", param2 : "whatever", param3 : "whatever" },
success: function(result){
//do something with result
}
})
If you want to access the variables, you can call $_GET['param1'] or $_REQUEST['param1'] to get access to them in PHP. Simply change the name in the brackets to the desired variable you want and store it in a variable.
If you want to access the params with Javascript... well the most efficient way is to go and decode the URL that was used and pull them out. See here
Hope this helps!
You can access the parameters from the URL via the $_GET superglobal in PHP.
For example, if your URL is http://example.com/test.php?param1=foo&param2=bar, then you could access them in PHP like so:
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
See http://www.php.net/manual/en/reserved.variables.get.php for more details.
As for returning a valid JSON response, you can check out this answer. It uses PHP's header function.

What is the best strategie to send complex data with ajax

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

Is this jQuery AJAX post saving data incorrectly?

$.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

pass array and individual string to php file using ajax call

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.

Categories

Resources