Hi I'm new to rails so please bear with me :) I want to send JSON object to rails and save it to database. basically I have a data entered by the user then I have a javascript function thats retrieves the data and convert it into JSON object. What i want is to sent the JSON object maybe through ajax to rails and save it to the database.Can anyone give me any idea how to do it. thnx
function save(){
----(some codes)
notesArray.push({ Index: i, Title: title.val(), Content: content.val()});
// json encode it
var jsonStr = JSON.stringify(notesArray);
//want to add code here to send to rails
}
If you're using jQuery, it's very easy to do this using $.post():
$.post('/some/page/here', {notes: jsonStr});
As to "handle the JSON object in the controllers" you can use parsed_params = CGI.parse(params[:_json]) ,then you can get what you what througt parsed_params[key1][key2]
Related
i am trying to create a simple web app that gets the latitude and longitude stored in a JSON string and uses them to place markers on a google map. Currently, I have a program on a server which retrieves a JSON string with data when a URL is entered into a web browser. The JSON string produced is as follows:-
{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}
What method could i use in JavaScript that would allow me to get the JSON string that is produced?
P.S I know I will need to parse the text afterwards to make a JSON Object, this is something that can be done afterwards.
Use the Jquery library's get method to request the data from the server. Here is a link to a simple W3 tutorial : http://www.w3schools.com/jquery/ajax_get.asp
Your code will look something like this:
$("button").click(function(){
$.get("/your/server/url",function(data){
var result = JSON.parse(data);
// Process result.employees
});
});
You could use
var x = JSON.parse('{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}');
and then access it with:
x["employees"][0]["lat"];
try this for normal strings:
JSON.parse(str)
or if you're using AJAX to get that Json you can use as following:
$.get(..,'json')
OR
$.post(..,'json')
I am trying to send Javascript Array via AJAX POST to django view.
I store this array in hidden input using JSON.stringify:
$('#id_uuids').val(JSON.stringify(arr));
this is how I try to send it:
$.post("/ajax/generateGallery",{uuids: $('#id_uuids').val()},function(response){
resp = JSON.parse(response);
alert(resp.html);
},"json");
Browser console shows that data which is being send looks like:
uuids:["6ecbe35b-0b77-4810-aa9a-918fecaeef13","e41f52f7-721b-4d44-b7d6-bbb275182d66"]
However, I am not able to use this in my django view. I've tried:
uuids = request.POST.getlist('uuids')
logger.info(uuids)
logger.info(type(uuids))
which returns:
[08/Aug/2014 15:20:00] INFO [app.rest_client:307] [u'["89a26646-6000-4c48-804a-69abcc496fd8"]']
[08/Aug/2014 15:20:00] INFO [app.rest_client:308] <type 'list'>
[08/Aug/2014 15:20:00] INFO [app.rest_client:312] Generate HTML gallery for photo ["89a26646-6000-4c48-804a-69abcc496fd8"]
So, Django treats very list sent as single element. How can I force python code to treat this data as list and be able to iterate on?
try to JSON-decode the posted data
uuids = json.loads(request.POST.get('uuids'))
that is if you loaded some json module before, e.g.
import simplejson as json
I'm creating an android app which takes in some json data, is there a way to set up a directory such as;
http://......./jsons/*.json
Alternatively, a way to add into a json file called a.json, and extend its number of containing array data, pretty much add more data into the .json file this increase its size.
It could be by PHP or Javascript.
Look into Parsing JSON, you can use the JSON.parse() function, in addition, I'm not sure about getting all your JSON files from a directory call, maybe someone else will explain that.
var data ='{"name":"Ray Wlison",
"position":"Staff Author",
"courses":[
"JavaScript & Ajax",
"Buildinf Facebook Apps"]}';
var info = JSON.parse(data);
//var infostoring = JSON.stringify(info);
One way to add to a json file is to parse it, add to it, then save it again. This might not be optimal if you have large amounts of data but in that case you'll probably want a proper database anyway (like mongo).
Using PHP:
$json_data = json_decode(file_get_contents('a.json'));
array_push($json_data, 'some value');
file_put_contents('a.json', json_encode($json_data));
This is my first attempt at ajax, and I've written a submit handler that parses a form and sends the data via POST to the server as a JSON string. Here is a simplified example of what my javascript looks like
formData = JSON.stringify({'testA':{'testa':'some data'},'testB':{'test2':'more data'}});
The JSON string looks like this
{"testA":{"test1":"some data"},"testB":{"test2":"more data"}}
and I send it via post here
$.post("/some/form/page/",formData,updateForm,'json');
On the server side is where the problem rears its ugly head, this is what my query dictionary looks like when I print if from the Django view
<QueryDict: {u'{"testA":{"test1":"some data"},"testB":{"test2":"more data"}}': [u'']}>
The JSON string is the key of the query dictionary. I am not very familiar with Javascript or JSON so don't be afraid of hurting my pride by pointing out an obvious newbie mistake, because I am and I know it. ;)
Thanks,
You're sending the string as a parameter to $.post. Instead of calling "JSON.stringify()" yourself, just pass in your raw JavaScript object as the second parameter to $.post().
$.post("/some/form/page/", {'testA':{'testa':'some data'},'testB':{'test2':'more data'}}, updateForm, 'json');
Here's something I want to learn and do. I have a JSON file that contains my product and details (size, color, description). In the website I can't use PHP and MySQL, I can only use Javascript and HTML. Now what I want to happen is using JQuery I can read and write a JSON file (JSON file will serve as my database). I am not sure if it can be done using only JQuery and JSON.
First thing, How to query a JSON file? (Example: I would search for the name and color of the product.)
How to parse the JSON datas that were searched into an HTML?
How to add details, product to the JSON file?
It will also be great if you can point me to a good tutorial about my questions.
I'm new to both JQuery and JSON.
Thanks!
Since Javascript is client side, you won't be able to write to the JSON file on the server using only Javascript. You would need some server side code in order to do that.
Reading and parsing the JSON file is not a problem though. You would use the jQuery.getJSON function. You would supply both a url and a callback parameter (data isn't needed, because you're reading a file, so no need to send data). The url would be the path to your JSON file, and the callback would be a function that uses the data.
Here's an example of what your code might look like. I don't know exactly what your JSON is, but if you have a set called "products" containing a set of objects with the details "name" and "price", this code would print those out:
$.getJSON("getProductJSON.htm",
function(data) {
$.each(data.products, function(i, item) {
var name = item.name;
var price = item.price;
// now display the name and price on the page here!
});
},
);
Basically, the data variable in $.getJSON makes the entire contents of the JSON available to you, very easily. And the $.each is used to loop over a set of JSON objects.