Ruby on Rails: JSON, javascript, and ruby [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Ruby on Rails: Sending javascript data to ruby controller
Total noobie with JSON, javascript and RoR
In my RoR application I have some javascript on a webpage. I would like to pass in one of the arrays I have built up to a Ruby function in my controller (is that possible?)
I've read somewhere I need to convert to JSON. Using this command gives me something I can work with (totalChanges is my array)
JSON.stringify(totalChanges)
but how do I pass this to a ruby function? If anything doesn't make sense please straighten me out.
Thanks
EDIT:
I'm using jquery. The comments have pointed out that I can use something like http://api.jquery.com/jQuery.ajax/ to send data over to a controller.
the particular action I want to do is save some data (in a javascript array) to a database and then reload the page to show the new data. jquery.ajax just seems to have so many options I'm a bit lost.

You can place an AJAX request using jQuery like this:
$.ajax({
type: "POST",
url: "/route/to/action",
data: { mydata: JSON.stringify(totalChanges) },
success: function(response, textStatus, jqXHR) {
console.log("Yay it worked.", response);
}
);
In your action, you can then retrieve the data passed to your action like this:
def action
mydata = params["mydata"]
# Save it to the database...
end

Related

How to store a js value in php variable? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I want to store the value of x in js variable into php variable on the same page.
Short answer is: you can not.
The reason for this: PHP is executed on the server side, and the response is sent to the browser, and (usually) generated as HTML. The javascript is rendered after this, so at this point, the PHP code no longer exists.
Long answer:
You can send a javascript variable to PHP using an XHR request (or more commonly known as an AJAX call). This will be a different request from the one that loads your initial page though. For more information see this: https://www.w3schools.com/Php/php_ajax_php.asp
you can use ajax or
add input hidden with this value and when submit form sent a value
i think in most cast ajax in best.
$.ajax({
url: 'url',
method: 'POST',
data: 'data',
cache: false,
success:function(data){
},
error: function(data){
}
}); // end ajax

Is there a way to use javascript variable as part of PHP SQL page?

I have a variable within a laravel PHP page, held within Javascript. I currently print / output this as:
${data.id}
I now want to connect to PHPMyAdmin to check to see if the ID is within a table. However, I realise I can't use the ID number in PHP - as this is done on the server side and JS on the client side. A little stuck.
Unfortunately, I'm on a shared hosting package so node.js isn't a solution I can use.
Any help would be great! I think I can use AJAX, but unsure on how this would look.
here the AJAX sample.
$.ajax({
method: "POST",
url: "some.php",
data: { id: data.id}
})
.done(function( response) {
console.log(response);
//TODO:process your response here if receive response from php file.
});

Update user attribute from Coffeescript?

How can I in Rails write a Coffeescript function to update a database column? I guess an Ajax call of sorts would be ideal:
id = $('#document').attr('data-document-id')
$.ajax
url: "/documents/#{id}/update_attr"
type: "GET"
success: (data) ->
console.log(data)
Is something like this the only way? Or is there something better?
Well, keep in mind that frontend code (html, css, js) cannot access the database directly. So you need an AJAX request.
REST best practices would require you to use a POST/PUT/PATCH method instead of the GET method which should never change the state of the application.
Also, you are not passing any value to the Rails backend.
$.ajax
url: "/whatever/#{id}"
type 'POST'
data:
key: value
success: (data)->
console.log data
On the Rails side you need to setup the appropriate route in config/routes.rb:
post '/whatever/:id', to: 'some_controller#some_action'
Still ideally, following the best practices, you probably have some sort of
resources :apples
already mapped to an ApplesController. You now have to implement the action, which will be like this:
def update
#object = Whatever.find(params[:id])
if #object.update(key: params[:key]
render json: { success: 1 }
else
render json: { success: 0 }
end
end
That implementation is not complete (it does not handle HTML requests, multi-key updates and other fancy things), but still it should solve your problem.

How do I pass form data to PHP and return a json string to Javascript?

Does anyone know how pass form values into PHP and still return the data to JavaScript? (For use in Google Charts if anyone is wondering.)
I have an HTML form with 4 radio boxes. I'd like to pass the value of the form so that my PHP request will be modified based on the user's selection.
The results from the PHP request need to be passed to JavaScript for processing.
In the radio button on click event place a javascript function that will perform an XMLHttpRequest to the php page and have the PHP page echo some JSON content that can be decoded in the return of the XHR in Javascript.
Example of such
May this can help you.
I think that you must do an Ajax request
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( data) {
alert( "Data Saved: " + data);
});
You send data to server form your form (here sent are name and location). You read this data with javascript with OnSelect and transfert it to your PHP code and,
You get back data from server into your JavaScript code and you can do what you want with it.
Sorry if my solution use JQuery, it is better for cross-browser with less code writing !
You could use this line to parse an array into json and use it later in javascript:
json_encode($rows); //format array named $rows into json data
More info: http://php.net/manual/en/function.json-encode.php

jQuery write to database Database [duplicate]

This question already has answers here:
How to connect to SQL Server database from JavaScript in the browser?
(8 answers)
Closed 8 years ago.
i am quite new to jQuery and i cant seem to find a method to write to a database on the server on which jquery is running.
Is there a sqlite plugin or similar?
I want to be able to let the user make some input, which gets processed and stored in a database. Is it possible in javascript/jQuery at all, or do I have to turn to PHP?
jQuery is entirely client side, you're going to need to use PHP or another language to actually interact with the database and just use jQuery to send the information via the AJAX method.
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
Taken from
https://api.jquery.com/jQuery.ajax/

Categories