I'm trying to do a like/dislike system. So essentially, there are two buttons on the html side.
<form method="post" name="ratings">
<input type="submit" name="vote" value="like">
<input type="submit" name="vote" value="dislike">
</form>
However, I only know how to do a single function. How can I seperate it? I'm working in node js.
So, like the first line of code looks like this:
router.post('/test/*', function (req, res) {
Like what would the if statement look like in javascript? or do I have to change the html code and do something with onclick? Any response would be appreciated.
I figured it out. You can get the name from req.body.vote and then use that value to do whatever.
var inputValue = req.body.vote;
if (inputValue == "like") {
...
I suggest you to use ajax, somelike this..
Buttons:
<button name="btnLike" value="like" onclick="like()">
<button name="btnDislike" value="dislike" onclick="dislike()">
JS:
function like(){
$.ajax({
url: "http://localhost:3000/like",
type: "POST",
data: {like: 'yes'}, //send this to server
success: function(returned) {
console.log(returnet); // here can get the return of route
},
error: function() {
}
});
}
function dislike(){
$.ajax({
url: "http://localhost:3000/dislike",
type: "POST",
data: {dislike: 'yes'}, //send this to server
success: function(returned) {
console.log(returnet); // here can get the return of route
},
error: function() {
}
});
}
Routes:
router.post('/like', function (req, res) {
}
router.post('/dislike', function (req, res) {
}
You can also use formaction
<button type="submit" formaction="/like" name="vote"></button>
<button type="submit" formaction="/dislike" name="vote"></button>
Below is the link
Parsing Form With Multiple Submits
Related
I have a form that I want to send its data to admin-ajax:
<form method="POST" id="form">
<input type="text" name="name">
<input type="number" name="phone">
<input type="email" name="email">
<textarea name="overview"></textarea>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
Javascript/jQuery code to send the data using Ajax:
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var form_data = $('#form').serialize();
$.ajax('http://mywebsite.com/wordpress/wp-admin/admin-ajax.php', {
method: "POST",
data: form_data + {action: 'my_action'},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log('Error:' + err);
}
});
});
Also tried formData:
var form_data = new FormData();
form_data.append('form', $('#custom').serialize());
form_data.append('action', 'my_action');
How to send the form data and the action my_action?
you need to change this line from data: form_data + {action: 'my_action'}, to data: {action: 'my_action', form_data:form_data},
jQuery(document).on("click","#submit", function(){
e.preventDefault();
var form_data =jQuery('#form').serializeArray();
jQuery.ajax('http://mywebsite.com/wordpress/wp-admin/admin-ajax.php', {
method: "POST",
data: {action: 'my_action', form_data:form_data},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log('Error:' + err);
}
});
});
and change input type submit to button.
In general i prefer to use this way, like in your case you are using submit type button:
$(document).on('click', '#submit', function(){ // the id of your submit button
var form_data = $('#your_form_data_id'); // here is the id of your form
form_data.submit(function (e) {
var my_action = "my_action";
e.preventDefault();
$.ajax({
type: form_data.attr('method'), // use this if you have declared the method in the form like: method="POST"
url: form_data.attr('action'), // here you have declared the url in the form and no need to use it again or you can also use the path like in your code
data: form_data.serialize() +'&'+$.param({ 'my_action': my_action}), // here you are sending all data serialized from the form and appending the action value you assing when declare var my_action
success: function (data) {
// after the success result do your other stuff like show in console, print something or else
},
});
});
});
Hope it helps you. if anything is not clear feel free to ask, i try to explain in the comments.
You should just pass form to new FormData() so in your case when submitting the form just pass new FormData(e.target);
Hope it helps
I have a form that I am validating with jQuery.
<form id="target" class="center-block" action="/" method="POST">
<textarea class="form-control" id="name" rows="3" name="name" placeholder="Enter a burger you would like to devour!"></textarea>
<button type="button" id="submit" class="center-block btn btn-default top">Submit</button>
</form>
After validation I am also trying to submit the form via jQuery.
if (validateForm() == true) {
$("#target").submit();
}
The validation is working however, it doesn't seem like the form is submitting to the post route. I was able to get the form to post using ajax, but the post wouldn't redirect after finishing. Was hoping this method would give the desired effect.
The app is running on Express and using MySQL.
I don't think your jquery submit will work ,because an element id or name submit will replace the form.submit method, you should simply change id (name also shouldn't give that).
<button type="button" id="changeThisId" class="center-block btn btn-default top">Submit</button>
Use Ajax and if you want to redirect to the current page, on success reload the current page
$.ajax({
url: yourUrl,
type: "post",
data: $("#target").serialize(),
success: function(r){
//form posted successfully
window.location.reload();
},
error: function(error){
alert(error);
}
});
I might have a typo in there, but the idea is:
$('#target').submit(function(event){
event.preventDefault();
}).validate({
rules: { ... },
submitHandler: function(form){
$.ajax{
type: 'POST',
data: $(form).serialize(),
url: '/',
success: function(result){
console.log(result);
}
error: function(err){
console.log(err.message);
}
}
});
});
I have a form which should submit data after pressing the submit button. After tagging a few input fields as required the form always shows me when there is no input in the required field after pressing the submit button - so far, so good.
What I would like to realize is that there is a redirection to another page if the submission was successful. If there are some empty required fields the form should show me, without redirecting me to another page.
By now I have the following code:
Submit button:
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" name="submityes" id="submityes" class="btn btn-danger">Submit</button>
</div>
</div>
Also I have the following js function to submit the form and to redirect me to another page:
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
The problem I have right now is that I will always be redirected to the "submit_resolved.php" page, whether all required fields are complete or not.
How can I solve this problem? I only want to be redirected when all required fields are not empty.
You should bind to the submit event, not click event:
UPDATED TO MATCH THE COMMENTS
$(function () {
var submityesClicked;
//catch the click to buttons
$('#submityes').click(function () {
submityesClicked = true;
});
$('#submitno').click(function () {
submityesClicked = false;
});
$('#webform').submit(function (e) {
e.preventDefault();//prevent the default action
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
window.location.replace(submityesClicked ? "/submit_resolved_yes.php" : "/submit_resolved_no.php");
},
error: function () {
alert("error");
}
});
});
});
The submit event is triggered only if the form is valid.
Note that the submit event is triggered by the form but the click event is triggered by the input element.
Do redirection on complete. Not on success
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
//window.location.replace("/submit_resolved.php");
},
complete: function () {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
I assume you are validating form in process.php so, you have to return error if validation fail from process.php like this.
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
check this link: Return errors from PHP run via. AJAX?
Hope this may be helpful to you.
The simplest thing you can do is to add "required" attribute to you input elements.Example:
<form action="/action_page.php">
Username: <input type="text" name="usrname" required>
<input type="submit">
</form>
It's a HTML5 attribute, so no JavaScript required. And it is supported by all major browsers. Check this link:
http://caniuse.com/#search=required
Anyway, you shouldn't rely just on front-end verification. Check those inputs on back-end, too.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<form action="">
Username: <input type="text" id="usrname" required>
<button type="button" name="submityes"
id="submityes" class="btn btn-danger">Submit</button>
</form>
</div>
function isValid(){
var usrname = $("#usrname").val();
if(usrname == ""){
return false;
}
return true;
}
$(function () {
$('#submityes').submit(function () {
if(isValid() == true){
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
alert("success");
window.location.replace("/submit_resolved.php");
},
});
}else{
alert("error");
}
});
});
I'm really clueless as to how to get this done.
I need to make a subscribe with email button and it needs to be validated and show a little message for success, Loading ands Error.
I have never worked with Ajax before and this is what I have to do, I have To complete the newsletter subscribe ajax-functionality using a pre-defined controller in a php file on the server called newsletter.php and the I should use the controller function named subscribe in there to generate the response for the ajax request.
If that makes any sense please help me out.
This is my form for the email address
<div id="subscribeText">
<form action="" method="post" name="ContactForm" id="ContactForm" >
<input type="submit" name="subscribeButton" id="subscribeButton" value="Submit" />
<input type="text" name="subscribeBox" id="subscribeBox" value="Enter your email address..." size="28" maxlength="28" onFocus="this.value=''" />
</form>
</div>
http://jsfiddle.net/vaaljan/R694T/
This is what the success should look like and error and loading pretty much the same.
What the success message looks like
Hope this isn't too far fetched, I have not worked with java script that much yet but I understand more or less.
Thanks
I have made a small example on jsfiddle.
$('#send').click(function (e) {
e.preventDefault();
var emailval = $('input#email').val();
console.log(emailval);
if (emailval !== "") {
$.ajax({
cache: false, // no cache
url: '/echo/json/', // your url; on jsfiddle /echo/json/
type: 'POST', // request method
dataType: 'json', // the data type, here json. it's simple to use with php -> json_decode
data: {
email: emailval // here the email
},
success: function (data) {
console.log(data);
$('<strong />', {
text: 'Successfull subscribed!'
}).prependTo('#state');
},
error: function (e) {
$('<strong />', {
text: 'A error occured.'
}).prependTo('#state');
},
fail: function () {
$('<strong />', {
text: 'The request failed!'
}).prependTo('#state');
}
});
} else {
alert("Insert a email!");
}
});
Here it is.
It uses jQuery for the ajax request.
The example shows how ajax works.
So I have a table that gets transformed to an array using:
var result = $("#enrolledStudents").sortable('toArray');
But when I go a head an pass that into my controller like so:
$("#update-enroll").click(function () {
var result = $("#enrolledStudents").sortable('toArray');
$.ajax({
url: '#Url.Action("Enrollment", "Classroom")',
data: { students: result },
type: 'POST',
traditional: true
});
});
My debugging breakpoint gets set off twice, causing issues to arise. What is the proper way to submit data to my controller on POST?
Per my comments, there are a couple things that could be causing this.
You have have the unobtrusive file(s) loaded multiple times
Your form has an action method defined, and your button is inside the form tag as a submit button. This will submit the form, and then the click will also submit the form - see example
Example
<form action="/somerowout/someaction">
<input type="text" id="text1"/>
<input type="text" id="text1"/>
<input type="submit" />
</form>
If you need to validate a value on your form before posting, don't hook up an additional Ajax call. Your javascript will look something like:
$(document).ready(function () {
$("form").submit(function(){
var result = $("#enrolledStudents").sortable('toArray');
if(result == null){
//do something to show validation failed
return false;
}
return true;
});
});
And your form code would then look something like:
#using (#Ajax.BeginForm(new AjaxOptions { })) {
<input type="text" id="text1"/>
<input type="text" id="text1"/>
<input type="submit" />
}
If you want to use Ajax rather than the Html Helpers, use a div instead of a form, and you won't get a duplicate post. Here's how you could achieve this:
<div id="enrolledStudents">
<--! your elements -->
<button id="saveStudents">Save</button>
</div>
JavaScript
$(document).ready(function () {
$("saveStudents").click(function(){
var result = $("#enrolledStudents").sortable('toArray');
if(result !== null){ /* do some kind of check here. */
$.ajax({
url: '#Url.Action("Enrollment", "Classroom")',
data: { students: result },
type: 'POST',
traditional: true,
success : function(data) {
if (data.status) {
window.location = data.route;
}
}
})
} else {
/* notify ui that save didn't happpen */
}
});
});
Example Controller Action
When posting your data using Ajax, here's an example of how to pass the route
[HttpPost]
public ActionResult SomethingPost(SomeModel model) {
if (Request.IsAjaxRequest()) {
var json = new {
status = true,
route = #Url.RouteUrl("MyRouteName", new { /* route values */ })
};
return Json(json, JsonRequestBehavior.AllowGet);
}
}
Are you sure you are preventing the default behaviour (form POSTING) of the submit button ? use preventDefault to do so.
$("#update-enroll").click(function (e) {
e.preventDefault();
//rest of the code
});
EDIT : As per the comment
To do the redirect in the ajax handler, you need to return the URL to be redirected in a JSON Response back to the calle.
[HttpPost]
public ActionResult Classroom(string students)
{
//do some operaton
if(Request.IsAjax())
{
//This is an Ajax call
return Json(new
{
Status="Success",
NewUrl = Url.Action("Index","Home")
});
}
else
{
//Normal request. Use RedirectToActiom
return RedirectToAction("Index","Home");
}
}
Now in your ajax call check the JSON result and do the redirect.
$.ajax({
url: '#Url.Action("Enrollment", "Classroom")',
data: { students: result },
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if(data.Status=="Success")
{
window.location.href = data.Newrl;
}
else
{
alert("some error");
}
}
});
Check if you don't have the jquery files loaded twice. I had this behavior and the problem was files loaded twice.