Add logic to delete method in Sinatra - html

I have been learning Sinatra for a couple of days now so I am still quite new. I am simply created a notes application and have added a delete function within the app.
Here is my Controller:
# Will display title of all notes
get '/' do
#notes = Note.all
erb :index
end
# Will display content within selected note
get '/:id' do
#note = Note.where(id: params[:id]).first
erb :note_description
end
# Will delete item from notes.
delete '/:id' do
Note.delete(params[:id])
redirect '/'
end
Here is my view with html/erb:
<div class="container">
<p>Return to Notes</p>
<h1><%= #note.title %></h1>
<p><%= #note.content %></p>
<form onsubmit="confirm('Are you sure you want to delete the following note?')" action="/<%= #note.id %>" method="POST">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">Delete</button>
</form>
</div>
As you can see, I have created a delete button and have a pop-up on submit when you click it. This will simply verify if the user really wants to delete the object. What happens though, is no matter what I click the item will be deleted and I will be redirected to the home page. I want to add logic where the app will only delete and redirect me to home page if the user clicks okay. If they click cancel nothing should happen. Any advice or help would be greatly appreciated.

You need to return from the event handler itself, so the attribute will look like:
onsubmit="return confirm('Are you sure you want to delete the following note?')"
Currently the return value of return is being returned to the event handler, but the handler itself is returning true (or at least not false).
(The current recommendation seems to be to avoid inline event handling like this though.)

You are seeing this behavior because the client is doing a POST, not a DELETE.
HTML forms only know how to do GET and POST. They cannot do PUT or DELETE. One way you can make it work is by using an AJAX call.
If you are using JQuery, you can set the method to DELETE. Here is the reference.
You will need to create the URL: /1 for example. And you need to handle the success and failure cases. Perhaps set the location on success, and display an error on failure.
EDIT: According to Matt's comment below, _method param replaces the HTTP method. Even though this works, I don't think it is a good practice. It would be better to use the HTTP DELETE method.

Related

How to remove the automatically added value from <option><select> to form action url, without removing the id in the select declaration

I'm actually working on a website that I have very little control over.
I have a form with a Drop down menu implemented like in the following code
<form method="GET" action="/particulier/fichePays">
<select id="pays">
<option value="1">Spain</option>
<option value="2">France</option>
<option value="3">USA</option>
</select>
<button type='submit' class='btn btn-default'>Valider</button>
</form>
The problem here is, when I click on the submit button, the value of the selected option is automatically added at end of the resulted URL. For example, if i select France, the resulted url is
/particulier/fichePays?pays=2
Instaed of
/particulier/fichePays
I don't have a great control on the website, so for some reason, I cannot remove the id=pays in the select declaration.
Is there any way to remove the automatically added ?pays=valueSelected at the end of the URL please?
Do you have control over the method?
If yes you could use POST instead of GET.
The difference according to this link is:
GET Method:
Appends form-data into the URL in name/value pairs
The length of a URL is limited (about 3000 characters)
Never use GET to send sensitive data! (will be visible in the URL)
Useful for form submissions where a user wants to bookmark the result
GET is better for non-secure data, like query strings in Google
POST Method:
Appends form-data inside the body of the HTTP request (data is not shown is in URL)
Has no size limitations
Form submissions with POST cannot be bookmarked
Hope this helps.
use post method instead of get method

Django form: *Nothing* happens when submit button is clicked

I'm probably missing something very basic but I'm stumped.
My HTML form (in a Django template):
<form id="site_signout" method="POST">{% csrf_token %}
<input type="submit" value="sign in">
</form>
In my browser (running my site on the dev server), when I click on the <input> button, nothing happens. Like, nothing nothing. Normally something would show in Terminal such as
[22/Apr/2014 08:29:17] "POST /my/url/ HTTP/1.1" 302 0
Or in Firebug, I would see something about a POST in the HTML tab of the Net panel. But I see nothing. Literally nothing happens when I click the button.
Other submit buttons (for other forms) on my site work just fine.
What could be causing this?
EDIT: The relevant part of my view is:
if request.method == 'POST':
pdb.set_trace()
That's all I have for the form right now because I want to examine what is posted in this scenario before I write more code.
EDIT: My intention is to simply POST to the same page (URL) that the form is on. As I understand it, this should be achievable by simply omitting the action attribute of the <form> element altogether. This is how I started but since it didn't work, I tried a couple of other options such as action="/", which is what I originally posted above. However, my intention is to have the form POST handled by the same view as the form itself. Therefore I've edited my original code sample to omit the action attribute altogether to clarify this point.
Here is my top-level urls.py:
urlpatterns = patterns('',
url(r'^inspection/', include('main_inspection.urls') ),
...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here is main_inspection.urls with the relevant URL:
urlpatterns = patterns('main_inspection.views',
url(r'^home/$', 'home', name="inspection_home"),
...
)
The URL for the view in question (on my dev server) is:
http://127.0.0.1:8000/inspection/home/
The solution turned out to be quite silly, and not discoverable by anyone reading the above question:
I had some JS capturing any click event happening inside the div in which the form was located.
Lesson learned: when something really strange seems to be happening at the basic HTML level, check to make sure you didn't write any stupid JS code that is producing the effect.
Your URL about "/" should be something like this:
...
url(r'^$','yourapp.views.index',name="base_address"),
...
It will run "yourapp.views.index" when you call "/" address.
If you want to set an address in you form action attribute try to set name of address instead:
<form id="site_signout" method="POST" action="{% url 'base_address' %}">{% csrf_token %}
<input type="submit" value="sign in">
</form>
We defined "base_address" name in urls that assigned to "/" address and then used that with "url" method in template.

Why do we put "?" in action = "?"

When I was learning Php with Mysql, I got a problem :
<form action="?" method="POST">
.
.
.
</form>
Why do we put "?" in the action attribute?
PS: this form was for inserting text into a database.
Actually, I have an Index.php file which is the controller, and 2 files (form.html.php and joke.html.php as templates). In the tutorial, I first clicked on a link "add joke" to include the form.html.php file and in this form there is <form action="?"> </form> and a submit <input>. When I click on submit, the controller index tests and executes the inserted SQL query.
Thanks.
Personally don't ever do that.... Use action="action.php" or use action="" post to the current URL.
Not sure what you are trying to accomplish with ? in the action attribute.
"We" don't and "You" shouldn't do so either.
If you want to POST the data to the current URL, leave it empty, i.e. action="".
If you want to POST to another URL, put that URL in there, e.g. action="save.php".

rails parameterize form data

I have a rails application that allows searching of posts when a get request in the form of /posts/search/:searchstring is recieved. I have no problems with the functionality when I put the search string in using my browser's url bar, but I am stuck trying to create a search form.
How can I make an html form in rails that allows me to send a get request using the above syntax? Am I going to be stuck using a controller method to redirect? I really want this functionality because I am a firm believer that the URL is a part of the UX and I hate ugly URLs like this:
http://example.com/search?utf8=%E2%9C%93&q=searchstring&commit=Search
A form's gonna do what a form's gonna do, and if you have a form using GET, it's gonna serialize those parameters into the query string.
But since you are using get, you also don't truly need to submit the form. Rather you can just send the browser to the URL.
So for example, somewhere in your JS:
function doSearch(form) {
// This assumes that the first input of your form is the search
// box. YMMV.
var query = encodeURIComponent(form.elements[0].value);
// just send the browser to the constructed URL
window.location = form.action + "/" + query;
// and return false to prevent the actual submit
return false;
}
Then in your html:
<form action = "/posts/search" onsubmit="return doSearch(this)">
<input type="text" name="searchstring" />
<input type="submit" />
</form>
How about adding the form this way:
<form method="get" action="<%= search_posts_url_path %>">#text input here with name "searchstring"</form>

HTML Form works with GET but not with POST

I'm running Firefox 2.0.0.14.
I have a form on a webpage which is working fine with the GET method.
I'm using a plugin to view my browser's HTTP request when submitting the form, and here it is :
GET /postComment.php?review=2&comment=Testing HTTP/1.1
...
However, if I make the simple change from method=GET to method=POST on the form:
GET /postComment.php HTTP/1.1
...
It isn't even attempting to POST.
Any possible reasons for this, under any circumstances?
EDIT: Here is the form:
<form method=POST action="postComment.php"><input type=hidden name=review value="2"><input type=submit value="Postit">
</form>
Is the action parameter of the form tag set? Could Javascript be intercepting the post? Some HTML from your form would be helpful, or an example link :)
I'm guessing your plugin is not capturing the POST variables. Since the output of your plugin is:
GET /postComment.php HTTP/1.1
How are you catpuring your POST varables? $_POST['key'] or $_REQUEST['key'] should contain your value if the form action and method are set properly.
POST will not be found in the query string.
EDIT:
if you are trying to capture the post value, you can check it with something like this:
if (isset($_REQUEST['submit'])) {
echo $_REQUEST['review'];
}
or
if (isset($_POST['submit'])) {
echo $_POST['review'];
}
Acorn
I would start by making sure your HTML is valid XHTML. Wrap attribute values in quotations and end the input elements with />. Use a valid DOCTYPE.
Also, try changing the value of the submit button to "submit" (as that is the default).
Try it out in different browsers, including the latest version of Firefox.
Firstly, your <form> tag needs to be adjusted:
<form method="post" ... >
Secondly, I have a function called debugArray that I use to spit out misbehaving arrays. It's very handy:
function debugArray($array){
echo("<pre>");
print_r($array);
echo("</pre>");
}
Then, call it in your code like this:
debugArray($_POST);
By looking at the entire contents of the $_POST array, you can see exactly what is being sent, what is not, and how it is being sent.
I'm willing to wager that one of the following is true:
You have a spelling mistake in a field name, remembering that names are case sensetive.
Your form field is outside your <form> tags.
You have a value that is not being escaped correctly, or otherwise being dropped from the $_POST for whatever reason.
Edit: And I would also be inclined to update your copy of Firefox.
I was having the same problem, till I remembered that my .htaccess file hides my PHP extension, and for reasons that someone else can explain (tech stuff) All I did was remove the .php extensión in the action property and it worked.
So, I went from:
action="folder/folder/file.php"
To:
action="folder/folder/file"
And the print_r($_POST) displayed the full array
I really Hope this helps someone else with the same problem.
And if anyone can technically explain why this is happening, it would be very educational 🙃