I am working on a html page which is supposed to submit a post request with request body to my server like below
<html>
<head>Customer app</head>
<body>
<div>
<table>
<tr>
<td>Customer Id :</td>
<td>
<form name="submitform" method="post">
<input type="text" id="customerId" name="customerId"/>
<input type="submit" value="Submit">
</form>
</td>
</tr>
</table>
</div>
</body>
<script>
$(document).ready(function(){
$("#submitform").click(function(e)
{
var MyForm = JSON.stringify($("#customerId").serializeJSON());
console.log(MyForm);
$.ajax({
url : "http://localhost:7777/ola-drive/customer/ride",
type: "POST",
data : MyForm,
});
e.preventDefault(); //STOP default action
});
});
</script>
</html>
It does not work as expected throwing 404 Not Found getting redirected to http://localhost:7777/customerapp.html. But form data corresponding to the request submission seems to be correct.
Can someone help me fix the issue with my html code submit POST request redirection ?
Your issue is in this line:
$("#submitform").click(function(e)
Your form does not have an id but a name, so you can write:
$('[name="submitform"]').click(function(e)
That is the reason because your form is giving you a redirection error.
$('[name="submitform"]').click(function (e) {
e.preventDefault();
$.ajax({
url: "http://localhost:7777/ola-drive/customer/ride",
type: "POST",
data: {"customerId": $("#customerId").val()},
success: function (result) {
//do somthing here
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<tr>
<td>Customer Id :</td>
<td>
<form name="submitform" method="post">
<input type="text" id="customerId" name="customerId"/>
<input type="submit" value="Submit">
</form>
</td></tr>
</table>
</div>
You are already created form using html, you can add action attrbiute with value for post url like
<form name="submitform" method="post" action="/ola-drive/customer/ride">
Unless you want to use ajax, you create your data form manually
you have this:
$("#submitform").click(function(e){...}
The first problem is you are selecting an input tag, instead the Form. The second is rather the action desired, in this case should be "submit". And if you already are using JQuery you might be interested in save some space using the method 'serialize()'. Try:
$('form').on('sumbit', function(e){
e.preventDefault();
$.ajax({
url: // your path
type: 'post',
data: $(this).seialize(),
...})
})
And use an id for Form, it's easier to select it.
Related
I'm using spring boot and thymeleaf.
Managing to call a spring controller method on click of first submit button.
I'm trying for a Ajax call on hit of second submit button , how can I achieve it?
Ajax call for the second submit button
$(document).ready(function() {
$("#download").click(function() {
var checked = [];
$('.checkbox:checked').each(function() {
checked.push($(this).val());
});
console.log(checked);
$.ajax({
type: "POST",
url: "selectedsalesDownload",
data: {
name: checked
},
success: function(msg) {
console.log(mgs);
alert(msg);
}
});
});
});
<form name="salesList" th:action="#{/selectedsales}" th:object="${sales}" method="post">
<div class="container">
<hr>
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th>SELECT</th>
<th>Mandy Name</th>
<th>GSTIN</th>
</tr>
</thead>
<tbody>
<tr id="salesDataTable" th:each="tempSales:${sales}">
<td>
<input class="checkbox" type="checkbox" th:name="selected" th:value="${tempSales.ID}" />
</td>
<td th:text="${tempSales.mandyName}"></td>
<td th:text="${tempSales.gstin}"></td>
</tr>
</tbody>
</table>
<div>
<input type="submit" value="SELECT" name="submit" class="btn btn-primary btn-sm mb-3" />
<input id="download" type="submit" value="DOWNLOAD" name="download" class="btn btn-primary btn-sm mb-3" />
</div>
</div>
</form>
Controller Method for first submit button
#PostMapping("/selectedsales")
public String selectedSales(
#RequestParam(value = "selected", required = false) List<Integer> selectedList,
Model model
) {
//...
}
Controller Method for second submit button
#RequestMapping(value = "/selectedsalesDownload")
#ResponseBody
public String toDownload(#RequestParam("name") List<Integer> list) {
return "msg";
}
I'm not able to get into "toDownload" method in the controller on click of second submit button instead I'm getting into first submit button controller method "selectedSales".
And also I need to send the checked box value which is stored in the javascript array variable "checked" to spring controller method "toDownload".
Need Solution.
Two things here...
You aren't preventing the second submit button from submitting the form normally. Either use a button type...
<input id="download" type="button" ... />
or make sure you prevent the default event action
$("#download").on("click", function(e) {
e.preventDefault()
// and so on
})
#RequestParam list parameters should be sent with the following format for the greatest compatibility
name=1&name=2&name=3...
Unfortunately, the default for jQuery is
name[]=1&name[]=2&name[]=3...
probably for compatibility with PHP. You can change this though via the traditional option
$.ajax({
method: "POST",
url: "selectedsalesDownload",
data: {
name: checked
},
traditional: true, // 👈 note the value here
success: function(msg) {
console.log(mgs);
alert(msg);
}
});
See https://api.jquery.com/jquery.ajax/ and more specifically https://api.jquery.com/jQuery.param/
Why do you need two submit buttons? Which one actually completes the form?
Adding the following code to your JS would immediately solve the issue, but ultimately you really should change one of those submit inputs to type="button" as well. This will prevent the default functionality of the form element and you can then override it with your own code:
$("form").submit(function(){
event.preventDefault();
// Your other code to execute on form submission
});
When I am submitting the FORM using SUBMIT button, it takes me to the ACTION page. But I want to stay in same page after submission and show a message below the form that "Submitted Successfully", and also reset the form data. My code is here...
<h1>CONTACT US</h1>
<div class="form">
<form action="https://docs.google.com/forms/d/e/1FAIpQLSe0dybzANfQIB58cSkso1mvWqKx2CeDtCl7T_x063U031r6DA/formResponse" method="post" id="mG61Hd">
Name
<input type="text" id="name" name="entry.1826425548">
Email
<input type="text" id="email" name="entry.2007423902">
Contact Number
<input type="text" id="phone" name="entry.1184586857">
Issue Type
<select id="issue" name="entry.1960470932">
<option>Feedback</option>
<option>Complain</option>
<option>Enquiry</option>
</select>
Message
<textarea name="entry.608344518"></textarea>
<input type="submit" value="Submit" onclick="submit();">
</form>
<p id="form_status"></p>
</div>
You need to use Ajax for sending Data and no refresh the page.
//Jquery for not submit a form.
$("form").submit( function(e) {
e.preventDefault();
return false;
});
//Ajax Example
$.ajax({
data: {yourDataKey: 'yourDataValue', moreKey: 'moreLabel'},
type: "POST", //OR GET
url: yourUrl.php, //The same form's action URL
beforeSend: function(){
//Callback beforeSend Data
},
success: function(data){
//Callback on success returning Data
}
});
Instead of adding onclick="submit()" to your button try capturing the submit event. In your submit function you also need to return false and prevent default to prevent the form from not submitting and taking you to the action page.
Using jQuery it would look something like this:
$("#id_form").on("submit", function(e){
//send data through ajax
e.preventDefault();
return false;
});
I have a lot of buttons, each opens its form . How do I get the input value of form opened at the moment, and post it on my server, like post("/addOrders", valueOfinputs)?
https://jsfiddle.net/ave6uvez/21/
<div class="rows">
<div class="row">
<button class="open">Buy</button>
<form id="myform" action="/index" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="namee" name ="name" >
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone</label>
<input type="phone" name = "phone" >
</div>
<button class="ave" >Close</button>
<INPUT type="submit" id = "submit" class = "close" value="Submit">
<!---- <button id="submit" class="close"></button>-->
</form>
</div>
</div>
try this,
$("#submit").click(function(e){
$.post("/addOrders",$("#myForm").serialize());
return null;
})
.serialize() will put all form elements data into the request
Also you need to give different id for different Forms submit button and you have to do the above code for each submit button
Hope this works for you.
This is a simple reference:
// this is the id of the forms, set the form ids accordingly.
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
I'm trying to submit a form using PHP and Ajax. But the problem is that sometimes it inserts one value, sometimes 2, sometimes all, and now it is inserting nothing. Why is it happening? How can I correct it?
Here's my code:
Ajax
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: "submitform.php",
type: "POST",
data: $("form").serialize(),
success: function(data){
alert("well");
},
error: function(){
alert("Error");
}
});
});
});
HTML
<form id="signupform" name="form1" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input type="text" name="name" placeholder="Enter your name" required /></td>
<td rowspan="3"><div class="propic"><img id="imgid" src="images/dp.png" /></div>
<input id="imgInput" type="file" name="image"/></td>
</tr>
<tr>
<td><input type="text" name="username" placeholder="Enter username" required /></td>
</tr>
<tr>
<td><input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required /></td>
</tr>
<tr>
<td><input type="password" name="password" maxlength="12" placeholder="Enter password" required /></td>
<td><input id="button" type="submit" name="submit" value="Sign Up" /></td>
</tr>
</table>
</form>
PHP
<?php
$conn=mysqli_connect("localhost", "root", "", "winkcage");
//$im=$_SESSION["pathsession"];
$nam=""; $usernam=""; $phon=""; $pass="";
$nam=$_POST["name"];
$usernam=$_POST["username"];
$phon=$_POST["phone"];
$pass=$_POST["password"];
$signquery="INSERT INTO signup(name, username, phone, password) VALUES('$nam', '$usernam', '$phon', '$pass')";
$signqueryrun=mysqli_query($conn, $signquery);
?>
NOTE: I don't want to insert image value right now. I'll insert it later when this problem is fixed.
You may have entered a ' quote and it killed your sql statement. This is called sql injection. To prevent sql injection you can use pdo prepared statements. You will also want to hash passwords to prevent people from stealling them if they get access to your database. Hashing password is a one way encryption that is easy to check.
$pdo = new PDO("mysql:host=$db_host;dbname=$DB_name", $user, $pass);
$sql = "INSERT INTO signup(name, username, phone, password) VALUES(':name', ':username', ':phone', ':pass')";
if ($con = $pdo->prepare($sql)) {
$con->execute([
':name' => $_POST["name"],
':username' => $_POST["username"],
':phone' => $_POST["username"],
':pass' => $_POST["password"]
]);
}
As far as the html and javascript goes. Catch the submitted form with jquerys .submit() function.
$('form').submit(function(e){
e.preventDefault();
$.post('submit.php',$(this).serialize(),function(response){
alert('complete');
}).error(function(){
alert('wrong');
});
});
This makes sure than any submit event triggers the ajax.
Since you are using a form with a submit button, when you click the button it will submit the form. You may be having a conflict between the AJAX action and the form submit. Try preventing the default action on the button click and see if it works as follows:
$(document).ready(function(){
$("#button").click(function(event){
if($("form").get()[0].checkValidity()){
$.ajax({
url: "submitform.php",
type: "POST",
data: $("form").serialize(),
success: function(data){
alert("well");
},
error: function(){
alert("Error");
}
});
});
}
event.preventDefault();
});
You assign your onclick to a button element, but there is no button element on your page, your button is an input element. Change that to a button and it may work. I personally would advise using ids, rather than element types, I think it makes things clearer, and will allow you to have more than one element of the same type without breaking your code.
Change
$("button").click(function(){
to
$("#button").click(function(){
and
data: $("form").serialize(),
to
data: $("#signupform").serialize(),
I have this bit of code:
<form name="myUploadForm" method="post" action="/scripts/upload.do" enctype="multipart/form-data" id="fileUpload">
<table width="100%" border="0">
<tr>
<td>
<input type="file" name="xlsFile" size="60" value="test.xls">
<input type="button" value="Upload File" name="upload_xls">
</td>
</tr>
</table>
</form>
Right now I can upload the file with Struts but it refreshes the page. How do I do this without the page refreshing?
What worked for me:
On the form tag, I have target="hidden-iframe"
the hidden i-frame on the page looks like this:
<iframe name="hidden-iframe" style="display: none;"></iframe>
The important thing to underline here is that the form is referencing the name attribute of the frame and not the id.
You can post form with jQuery and get the result back.
$('#formId' ).submit(
function( e ) {
$.ajax( {
url: '/upload',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
success: function(result){
console.log(result);
//$("#div1").html(str);
}
} );
e.preventDefault();
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formId" action="/upload" enctype="multipart/form-data" method="post">
<input type="text" name="title"><br>
<input type="file" name="upload" multiple="multiple"><br>
<input type="submit" value="Upload">
</form>
<div id="div1">
</div>
There are two methods:
HTML5 supports File API.
Create a hidden iframe, point the property 'target' of the form to the iframe's id.
If you can use jQuery, you can use something like jQuery File Upload.