I have two routes:
Route::get('/download/{hash}','DownloadController#exists')->name('exists');
Route::post('/download/{hash}','DownloadController#verify')->name('verify');
Procedure:
Basically the user enters a URL e.g. localhost/download/56iq45agosasa the first route is called and the download.blade.php view is shown. There is a form, where the user has to input a password and when the submit button is clicked, an ajax request is sent to the second (post) route.
The DownloadController#verify returns the json but displays it in a blank window (see screenshot) But it should be returned in the download.blade.php view.
Somehow the form disappears and the ajax success function is not called.
Code snippets Download.blade.php:
#section('content')
<div class="container-fluid mt-5">
<div class="row justify-content-md-center">
<div class="col-md-4">
<form method="POST">
<label for="uploadPassword">Password</label>
<input type="password" name="password" class="form-control" id="uploadPassword" placeholder="Password" required="">
<button id="btn-submit" type="submit" class="btn btn-success mt-2">Submit</button>
{{ csrf_field() }}
</form>
</div>
</div>
</div>
#endsection
#push('scripts')
<script type="text/javascript">
$(".btn-submit").click(function(e){
e.preventDefault();
let password = $("input[name=password]").val();
$.ajax({
type:'POST',
url:"",
data:{
password:password
},
success:function(data){
console.log("I don't get shown");
//alert(data.success + " " + data.matches);
}
});
});
</script>
#endpush
DownloadController:
class DownloadController extends Controller
{
public function exists(Request $request, $hash)
{
// Some private mysql queries
// Return the hash to the download view
return view('download',[
'hash' => $hash
]);
}
public function verify(Request $request, $hash)
{
return response()->json(
['success'=>'Got Simple Ajax Request.']
);
}
}
So there are two things that will help improve this code:
Wrap the listener in a document.ready function to ensure it's attached when the button is available in the page. This is necessary if #push will make the script end up above the form declaration in the page.
Listen for the form submit event so you can capture the submit via any of the possible ways that one can submit a form (e.g. by pressing ENTER on an input)
#push('scripts')
<script type="text/javascript">
$(function () {
$("form").on('submit', function (e) {
e.preventDefault();
let password = $("input[name=password]").val();
$.ajax({
type:'POST',
url:"",
data:{
password:password
},
success:function(data){
console.log("I don't get shown");
//alert(data.success + " " + data.matches);
}
});
});
});
</script>
#endpush
The problem here is that the form gets submitted.
Instead of overriding button click with your jQuery function, use it to change submit handler like so
Prevent Default on Form Submit jQuery
Make sure you put id on the form.
Related
I have a form that opens inside a BS4 modal window. This contents of the form comes from an AJAX request and that part works fine. However, when I submit the form (again an AJAX request) and it returns some info without closing the modal, and then I submit again, it submits twice. If I submit again, it submits 3 times, etc etc, each time one more submit.
What I missing here? This is my code:
<div id="empModal">
... modal stuff here ...
<div id="NewCustomer" class="col-12 view">
<div id="NewCustomerErrors"></div>
<form name="create_account" class="needs-validation" novalidate>
<div class="form-group">
... form stuff here ...
</div>
<div class="pull-right mt-3">Add new customer</div>
<div class="pull-left mt-3">Back to Log In</div>
</form>
</div>
... modal stuff here ...
</div>
Part 1
$(document).ready(function () {
$("#empModal").on('click', '#customerNewSubmit', function(e) {
$('.needs-validation').on('submit', function(e) {
if (!this.checkValidity()) {
e.preventDefault();
e.stopPropagation();
}
e.preventDefault();
e.stopPropagation();
$(this).addClass('was-validated');
var values = $(this).serialize();
doCreateAccount(values);
});
$('.needs-validation').submit();
return false;
});
});
Part 2
function doCreateAccount(values) {
$.ajax({
url: 'ajax_controller.php',
type: 'post',
dataType: 'json',
data: values+'&act=new',
success: function (res) {
if (res.result_success == true) {
$("#userButton").html(res.result_content);
$('#empModal').modal('hide');
} else {
$("#addNewCustomerErrors").html(res.result_content);
}
},
});
}
from your part 1.
$('.needs-validation').submit();
Comment this code because this is submitting a form again after single submission.
I have form with $_POST type from second page,on first page i've loaded the form with this code :
<div class="option_dialog" id="search">
<div class="close_option">Search <img onclick="search()" style="float:right;height:20px" src="img/close.png">
</div>
<div id="search_content" style="overflow:scroll;max-height:400px">
<script>
$('#first_page_div').load('second_page.php #second_page_form');
</script>
</div>
</div>
When the function search() called using onclick the above code will excuted and load the form from second page...then i submit the form using this code :
$(function () {
$('#form_id').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'second_page.php',
data: $('#form_id').serialize(),
success: function () {
$('#first_page_search_result').load('second_page.php #searched_result');
search_result();
}
});
});
});
When form submited via ajax on first page,the second page should process his/her request and return the searched result on first page and execute search_result() which is another hidden div will be shown after returned result.
please tell me how to make this work?regards
I have a page with multiple forms. When the users fill in one of the forms, I want to send it to a server. However, I need the browser to keep displaying the original page, so that the users can submit other forms, if they wish to. Hence I cannot use the "action" attribute in the form and a "submit" type of button.
After consulting the jQuery.post docs, I arrived to the following solution:
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.11.3/jquery-ui.css">
<script src="jsFiles/jquery-2.1.3.min.js"></script>
</head>
<body>
<form id="form">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button" onclick="submitForm();"> Submit </button>
</form>
<script>
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
})
.done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
}
</script>
</body>
</html>
The above code does what I want it to do, but it has a very peculiar and disruptive side-effect of modifying my URL to include the parameters I'm posting.
So when I fill in my name and email, I'm "redirected" to myself, but with the name and email parameters appearing in the URL:
http://localhost:8080/Prototype/TestPost.html?name=Lev&email=Storytime%40gmail.com
Now, I definitely do not want "name=Lev&email=Storytime%40gmail.com" to be a part of my URL. These parameters are also not intended for TestPost.html but rather to SaveForm.jsp, so it's all very wrong.
I also want to mention that SaveForm.jsp works as expected. It receives the parameters, saves them to the database and returns a success response.
What am I missing?
Thanks.
EDIT
Thanks, everybody. I could not avoid the refresh using the "return false" statement, so I had to use jQuery's "on click" option. I also don't understand how using ajax explicitly would make any difference, since jQuery's documentation seems to say that the post is just a syntactic sugar for Ajax.
The complete code which worked for me was:
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.11.3/jquery-ui.css">
<script src="jsFiles/jquery-2.1.3.min.js"></script>
</head>
<body>
<form id="form" method="post">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button"> Submit </button>
</form>
<script>
$( document ).ready(function() {
$("#button").click(function( event ) {
event.preventDefault();
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
}).done(function() {
alert("The form was submitted successfully");
}).fail(function() {
alert("Error submitting the form.");
})
});
});
</script>
</body>
</html>
If you don't especify the method attribute on the form it will be GET by default, that's why you get the URL params. Also, because you aren't not stopping the default action, your form is being submitted (the reloading effect), so I recommend you the following code to help you:
<script>
$(function() { //executes js code after html has been loaded
$("#button").on("click", function(e) {
e.preventDefault(); //avoids to reload the page
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
}).done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
}
});
</script>
And remove the onclick at the button to have a cleaner HTML:
<button id="button"> Submit </button>
If you do not want to use jQuery's on click and still stick to the submit function you can just add return false; in the end to prevent the form from submitting.
Like below
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
})
.done(function() {
alert("The form was submitted successfully");
});
.fail(function() {
alert("Error submitting the form.");
})
return false;
}
Hope this helps.
I guess, you are not submitting the form by ajax.
Add return false;, to that it does not redirect and submit via ajax.
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData, function() {})
.done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
return false;
}
UPDATE:
This is the error:
412 (Precondition Failed)
I am trying to call a php script from ajax, I currently have the below ajax, which when the button in the form (also below) is clicked will call a php script passing it the form data, which will then be submitted to the database.
However, it is not working; and what's more I am just getting a blank error back, so I do not even know what is going wrong.
Could someon please point me in the right direction?
Thanks.
HTML form:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<!--<input id="report-submit" value="" name="submit" type="submit" onclick="submitReport()"/> -->
<button id="report-submit" name="submit" onclick="submitReport()"></button>
</form>
AJax call:
function submitReport()
{
var ID=$('#reportedID').val();
var reason=$('#reason-box').val();
var formData = "ID="+ID+"&reason="+reason;
alert(formData);
//This code will run when the user submits a report.
$.ajax(
{
url: 'submit_report.php',
type: "POST",
data: formData,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
}
Now I have already tested the php script, and that works fine, the problem started when I added the ajax call so I know it is something to do with the ajax not the php.
This should correct the problem with submitting:
Your jQuery Ajax call won't succeed because the POST data isn't supplied in the correct format.
If the ajax should succeed the form is also posted resulting in a 405 error.
<button id="report-submit" name="submit" onclick="submitReport(event)"></button>
function submitReport(event)
{
event.preventDefault();
....... // your code
}
Now the default action of your form will be prevented (resulting in a 405 error). And only the ajax request is submitted.
In the button element we pass the event object on to the function. We use event.preventDefault() to make sure the button doesn't run it's default action, which is submitting the form.
You could also prevent this by deleting the form element as a wrapper, but maybe you want to use other features (like validation) on the form.
Form data in a jQuery ajax request needs to be an object called data:
var formData = {"ID" : ID, "reason" : reason};
jQuery will reform this to a correct query string for the submit.
I would do it like this:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160"></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" type="submit" name="submit" value="submit"></button>
</form>
<script type="text/javascript">
jQuery("document").ready(function(){
var $ = jQuery
$("form").submit(function(){
var data = "";
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
url: "submit_report.php",
data: data,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
return false;
});
});
</script>
and then use $reason=$_POST['reason-box']; and $ID=$_POST['reportedID']; inside your PHP script
this is optional to choose the form for submitting data or you can do it without the HTML form this is what i do
<textarea id="reasonbox" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" ></button>
and the using folloing javascript and jquery style
<script type="text/javascript">
$(function() {
$("#report-submit").click(function(){
try
{
$.post("your php page address goes here like /mypage.php",
{
//in this area you put the data that is going to server like line below
'reasonbox':$("#reason-box").val().trim(),
'reportedID':$("#reportedID").val().trim()
}, function(data){
data=data.trim();
//this is data is sent back from server you can send back data that you want
//like message or json array
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>
I hope it helps
I have a form that looks as following:
<form accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
<div class="field">
<label for="username">Email:</label>
<input class="text" id="passwordEmail" name="username" required="required" size="30" type="text">
<div class="field-meta">Put in your email, and we send you instructions for changing your password.</div>
</div>
<div class="field">
<input id="submitPasswordRequest" class="full-width button" name="commit" tabindex="3" type="submit" value="Get Password">
</div>
<div class="field center">
Nevermind, I Remembered
</div>
I am trying to do the post via AJAX, so I did a simple test like this:
$("#submitPasswordRequest").click(function() {
var username = $('#passwordEmail').value();
console.log(username);
/*
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: { username: username}, // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
*/
return false;
});
However it seems that the click function is not triggered and it goes to posting the form via the regular form action. What am I doing wrong here? I want to handle this via AJAX.
When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:
<form onsubmit="javascript: return false;">
New style:
$('form').submit(function() { return false; });
And on submit you want to perform an ajax query:
$('form').submit(function() {
$.ajax({ }); // here we perform ajax query
return false; // we don't want our form to be submitted
});
Use jQuery's preventDefault() method. Also, value() should be val().
$("#submitPasswordRequest").click(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/1/
You can also listen for the form's submit event:
$("form").submit(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/2/
jquery and ajax
$('form id goes here).submit(function(e){
e.preventDefault();
var assign_variable_name_to_field = $("#field_id").val();
...
if(assign_variable_name_to_field =="")
{
handle error here
}
(don't forget to handle errors also in the server side with php)
after everyting is good then here comes ajax
datastring = $("form_id").serialize();
$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}
})
});
on php page
$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name
...
then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
You should use the form's submit handler instead of the click handler. Like this:
$("#formID").submit(function() {
// ajax stuff here...
return false;
});
And in the HTML, add the ID formID to your form element:
<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: $('form').serialize(), // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
return false;
});