I have a form in my view.
I only want to submit the data, without the rendering of any other template or following the post request to a new URL.
Are there any solutions to this besides structuring the whole thing about AJAX?
EDITED:
I have a multipart form..
part 1 submits data to a cache (using AJAX), then I use JQuery to hide that part of the form and show part 2. Part 2 is what submits the main data to a rails controller. That controller action is responsible for pulling the previously cached data and sending a POST request to an API that stores part 1 and part 2 in a database.
What I would like to do:
Have the rails app receive the form data and process the request, then I could use an AJAX request to append data to the page (clearing out the form, and showing the compiled data submitted if the post was successful, and an error message if not).
UPDATE:
I have tried the following and it does nothing when clicked:
$('#button').click(function(event){
event.preventDefault();
$(this).submit(); //also tried .send();
});
you could either redirect to the same page or maybe do this
$('#selector').click(function(event){
event.preventDefault();
//Do other thing, or maybe nothing
});
In your controller do the following:
respond_to do |format|
format.all { render nothing: true, status: 200 }
end
Related
I was trying to implement page caching in Yii2 advanced project and everything seemed to be super cool. And suddenly I was hit by a strange issue.
Case: On the homepage of the website there is some dynamic data like showing records from DB, info of current user like the name (if the user is logged-in) and some static content. Also, a search input field which fetches result using AJAX call.
To speed page loading I implemented PageCaching provided by Yii2. And all worked good. But one issue I got stuck at is that after user log-in the ajax call didn't work and gave Error:
Bad Request (#400): Unable to verify your data submission.
I get this error till cache is refreshed after the set duration or I disable cache.
Is this issue related to cookie/session or something else? How to resolve it?
The 400 Bad Request is because the csrf-token is not being sent, with the request which is required to prevent cross-site attacks by Yii whenever you use POST to submit a page or ajax request, if you create an ActiveForm then it creates an input automatically with the token value.
You didn't add the code that you are using for the ajax call so not clear if you are using it for only one field or the whole form, so I would suggest the concerning part only.
You need to send the csrf-token and you can get it via javascript using yii.js and calling these 2 methods
yii.getCsrfParam() to get the parameter name of the token
yii.getCsrfToken() to get the token or actual value of the csrf-token
The csrfParam name is configured inside your frontend/config.php or config/web.php depending on the app you are using (advance /basic) under the request component like below
'components'=>[
......
......
'request' => [
'csrfParam' => '_csrf-frontend',
],
......
......
]
So what you need to do is either change the request method from POST to GET and send data via query string or use the following way to send the POST request.
Note: You should change the URL and add the csrf data into your existing data that you are sending with the request
let data={};
data[yii.getCsrfParam()]=yii.getCsrfToken();
$.ajax(
{
method:"POST",
url:"/site/test",
data:data,
success:function(data) {
console.log(data);
},
error:function(jqXHR,textStatus,errorThrown) {
console.log(jqXHR,textStatus,errorThrown);
}
}
);
If you have a test action inside the SiteController with the following code, then the above ajax call should show you the $_POST array inside the console with the csrf param and token value as key=>value.
public function actionTest()
{
print_r($_POST);
}
I have been trying to do a HTTP POST of some input data from a HTML form to mongodb.
Although I am able to perform the database insertion of my data but unable to redirect to another HTML page after the operation is finished.
I have tried both res.render as well as res.redirect, but nothing seems to work.
However, I am getting a successful post /index 200 followed by a get /home 200.
On the front side maybe write something like this
$.post("/").then(function(data) {
window.location = data.redirectUrl;
});
And in the server side write this
res.send({err: 0, redirectUrl: "/"});
I am new to MVC and need a bit of help refactoring my code. In my view I have a http 'POST' request to a known URL that gets triggered when a user enters a new Client Name. The end point URL then returns three unique keys in json format that I then display on my UI. So I have four text boxes that display the following info:
Client Name: newclient
Key1: xyz
key2: 123foo
keys3: 456bar
My question is how do I make this request from the controller instead of everything taking place in the view ? I'm struggling to see how I can make the POST request from the controller when I need the information entered from the user in the view.
Thanks
I am trying to build a website using Ruby on Rails that presents a question to the user(say on page1). After the user submits an answer to the question he goes to page2. I want to record his response, check with my database for its correctness and I want to give a feedback and also present the next question on the same page(page2).
I want to conceptually understand how can I do the above. When do I use HTTP GET and POST?
Data Persistence
I want to record his response, check with my database for its
correctness and I want to give a feedback and also present the next
question on the same page(page2)
This will likely be achieved using a session based model - whereby the question response is created sequentially:
#app/models/form_response.rb
class FormResponse
def initialize(session)
#session = session
#session[:form_response] ||= []
end
def process_response(response)
#response here
end
...
end
This will allow you to store the response, and evaluate over time. There's a great Railscast about it here:
In terms of the POST / GET requests, I'd be tempted to use POST, as this will keep your application modular (the params are not stored in the URL etc)
The way to do this would be as follows:
#config/routes.rb
resources :controller do
collection do
post :page1
post :page2
post :summary
end
end
#app/controllers/your_controller.rb
Class YourController < ApplicationController
def page1
#form = FormResponse.new(session)
render :page2
end
end
--
Ajax
You'll may also want to use ajax for this
Ajax is the ability to send an asynchronous request to your application, through JS. In fact, Ajax actually stands for Aysnchronous Javascript and XML, which means you need to be able to use it to send a hidden request to your controller, processing the response as you require
You'll want to use this for UX more than anything (the ability for a user to stay on the same page to edit their response). I can detail more about this if you wanted
This sounds more like a general question about HTTP than Ruby on Rails so I'll approach it that way. At a high level the HTTP exchange will look something like this:
The user/browser sends an HTTP request to your server and waits for a response. This can be, for example, a GET or POST request.
Your server will process that request (eg. using Rails in your case) and send an HTTP response back to the user. The response will contain a status code and an optional body.
The user/browser receives the response and processes it. The response body often is the HTML markup of a web page, in which case, it will be rendered in the browser. The page may contain links or forms that the user can click on or submit, which then brings us back up to Step 1.
I'd suggest you read more about the HTTP protocol (eg. on Wikipedia)
Sorry if this seems like a silly question, but assuming one implements a HTML form with an action triggering a post call to a server, is the server supposed to return the 'next' page or can the post call be twisted to return only a JSON for processing by the same HTML page too?
Is there a standard defining what can or should be done after a HTML post call is performed or is everyone free to do what they want?
is the server supposed to return the 'next' page
In general, yes, although you can return a 204 No Content response.
can the post call be twisted to return only a JSON for processing by the same HTML page too?
It could return JSON, but the page couldn't process it because there is no standard way to process JSON.
If you want to deal with JSON, then you need to make the request with JavaScript instead of a regular form submission.
The browser will render the response returned by the server.
If you want to handle the response in code, use AJAX instead.