I need send data to the database without refreshing page.
Home Blade :
<form class="chat" id="message" action="#" method="post">
<input type="hidden" name="_token" id="_token" value="{{ csrf_token() }}">
<li>
<div class="panel-footer">
<div class="input-group">
<input type="text" name="message" class="" placeholder="Type your message here..." />
<span class="input-group-btn">
<button type="submit" class=" btn-success btn-sm searchButton" id="save" >
Send
</button>
</span>
</div>
</div>
</li>
</form>
Controller :
public function message(Request $data)
{
$ins = $data->all();
unset($ins['_token']);
$store = DB::table("chatbox")->insert([$ins]);
return Redirect('Users/home')->with('message',"success");
}
Ajax :
<script>
$(document).on("click", ".save", function() {
$.ajax({
type: "post",
url: '/Users/message',
data: $(".message").serialize(),
success: function(store) {
},
error: function() {
}
});
});
</script>
At present when I send data it is automatically refreshing the whole page but only the particular form need to be refreshed.
You need to prevent the default form submission, and use the script instead
$(document).on("click", "#save", function(e) {
e.preventDefault(); // Prevent Default form Submission
$.ajax({
type:"post",
url: '/Users/message',
data: $("#message").serialize(),
success:function(store) {
location.href = store;
},
error:function() {
}
});
});
and instead of returning a redirect, return the url from the controller and let the script handle the redirect
public function message(Request $data)
{
$ins = $data->all();
unset($ins['_token']);
$store = DB::table("chatbox")->insert([$ins]);
session()->flash('message', 'success');
return url('Users/home');
}
You should change the type of the button from submit to button like :
<button type="button" class=" btn-success btn-sm searchButton" id="save" >end</button>
Or prevent the default action (submit) using e.preventDefault(); like :
$(document).on("click",".save",function(){
e.preventDefault(); //Prevent page from submiting
...
...
});
NOTE : Note also that you don't have button with class save but with id save so the event handler should looks like :
$(document).on("click", "#save", function(){
________________________^
You have to handle function inside javascript/jquery form submit funtion and use e.preventDefault() to stop HTML to submit the form.
Try your ajax code in the below code type.
$('#message').submit(function(e) {
e.preventDefault();
//your ajax funtion here
});
You can reset/refresh your form in success function
$("#message").trigger("reset");
Remove return Redirect('Users/home')->with('message',"success"); and just return an array like
return ['message' => 'success'];
Related
I have form containing a button, when clicked it displays a modal window with another form containing an input and a send / cancel button.
I want to serialize the data in this modal form and send it to a remote server via AJAX.
For some reason when I look the the console I can't see the serialized data, I can only see Email=
Can someone look at my code and tell me where I'm going wrong please? Should this work?
HTML
<form id="feedbackForm">
<input class="button" id="bad" src="bad.png" type="image">
</form>
<div aria-hidden="true" class="modal" id="modal" role="dialog" tabindex="-1">
<form id="emailForm">
<div class="form-group">
<input class="form-control" name="Email" type="text">
</div>
<div class="modal-footer">
<button class="btn" type="submit">Send</button>
<button class="btn" data-dismiss="modal" id="closeModal" type="button">Cancel</button>
</div>
</form>
</div>
AJAX
<script>
$(document).ready(function() {
var request;
$("#feedbackForm").on("touchstart, click", function(e) {
e.preventDefault();
var serializedData = $("#emailForm").serialize();
$('#modal').modal('toggle');
$("#emailForm").on("submit", function(e) {
e.preventDefault();
request = $.ajax({
url: "MyURL",
type: "post",
data: serializedData
});
request.done(function(response, textStatus, jqXHR) {
console.log(serializedData); // displays Email=
});
});
});
});
</script>
If I understand correctly when the user clicks the touchstart
You serialize the form
You open the modal containing the form
You overwrite the submit event to send your ajax
The thing is that your variable has already been given the values of the form before it is populated with the user data. (If he is opening the modal for the first time)
Just get your data from a function of ajax submit at the correct moment like this:
data: getSerializedData()
and the function
function getSerializedData(){
return $("#emailForm").serialize();
}
I have a Bootstrap page that is dynamically created using PHP, and on the page there are 25+ forms that are used to edit records.
The form submits to the server using jQuery Ajax script which works as expected on the first form, but when the second form is edited and submitted it submits form 1 and 2, and when I go to form 3 it will submit forms 1, 2, and 3
Here is the HTML:
<tr id="375987">
<td width="20%">audio controls to play wav file</td>
<td width="80%">
<div class="form-group">
<form id="375987">
<textarea class="form-control" id="rec_txt" name="rec_txt" rows="4">There is text from the Database</textarea>
<input type="text" id="event_num" name="event_num" value="" />
<button type="submit" id="correct_stt" class="btn btn-outline-success my-2 my-sm-0" OnClick="update_stt()">Edit</button>
<input type="hidden" id="rec_id" name="rec_id" value="375987" />
<input type="hidden" name="act" value="correct_stt" />
</form>
</div>
</td>
<td>
<a href="#" class="btn btn-primary a-btn-slide-text" onClick="hiderow('375987')">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<span><strong>Hide</strong></span>
</a>
</td>
</tr>
<!-- 25+ forms ..... -->
And here is the Java:
function update_stt() {
var url = "function_ajax.php"; // the script where you handle the form input.
$('form[id]').on('submit', function(e) {
$.ajax({
type: 'POST',
url: url,
data: $(this).serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
$(e.target).closest('tr').children('td,th').css('background-color', '#000');
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
});
e.preventDefault();
});
}
How can I identify only the id of the form that I want submitted, or submit only the form on that row?
You use a submit button which will automatically submit the form, but you also add a click event to it using the onclick attribute, so it will execute the associated function and submit the form. All that is unnecessarily complicated.
Remove the onclick attribute on your button:
<button type="submit" id="correct_stt" class="btn btn-outline-success my-2 my-sm-0">Edit</button>
And change your code to:
$('#375987').on('submit', function(e) {
var url = "function_ajax.php"; // the script where you handle the form input.
$.ajax({
type: 'POST',
url: url,
data: $(this).serialize(),
success: function(data) {
console.log('Submission was successful.');
console.log(data);
$(e.target).closest('tr').children('td,th').css('background-color', '#000');
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
},
});
e.preventDefault();
});
If you want all your forms to use the same function, then simply replace the selector $('#375987') with $('form'):
$('form').on('submit', function(e) { ... }
If you only want to select some forms, not all, then you can give them the same class and then select them by that class, like <form class="ajaxed">:
$('form.ajaxed').on('submit', function(e) { ... }
You can give id to forms and use
$('#formid').submit();
in your case
$('#375987').submit();
But that id is used by your tr div too. You should consider using id for form only
It's because each time you click the button and call update_stt() you are attaching again the .on() listener.
This is why you end up with more and more submit requests.
$('form[id]').on('submit', function (e) {
This line of code should only be called once not on every click.
ALSO: you said you build these on the backend so you could pass the ID straight to the function:
update_stt(375987)
Then you can use this:
function update_stt(passedNumber) { ...
Then you can use the id number in the call
Your mixing jQuery and vanilla JS a lot here, might make sense to try a larger refactor.
I'm currently creating a subscription form using jQuery. My problem is I want to make this form stay in the same page after user click "SUBSCRIBE" button and when the process is successful, the text on button "SUBSCRIBE" change to "SUBSCRIBED".
Below is the code :
HTML:
<form action="http://bafe.my/sendy/subscribe" class="subcribe-form" accept-charset="UTF-8" data-remote="true" method="post">
<input type="hidden" name="authenticity_token" />
<input type="hidden" name="list" value="ttx7KjWYuptF763m4m892aI59A" />
<input type="hidden" name="name" value="Landing" />
<div class="form-group">
<div class="input-group">
<input type="email" name="email" class="form-control" placeholder="Masukkan email anda" />
<span class="input-group-btn"><button type="submit" class="btn btn-primary">SUBSCRIBE<i class="fa fa-send fa-fw"></i></button></span>
</div>
</div>
</form>
jQuery:
$(".subcribe-form").submit(function(){
var validEmail = true;
$("input.form-control").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("has-error");
validEmail = false;
} else{
$(this).removeClass("has-error");
}
});
if (!validEmail) alert("Please enter your email to subscribe");
return validEmail;
});
You can use event.preventDefault to prevent the form submission but you also need to send the data to the server so for this you can use jQuery ajax ( see below code )
$(".subcribe-form").submit(function(event){
event.preventDefault()
var validEmail = true;
$("input.form-control").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("has-error");
validEmail = false;
}
else{
$(this).removeClass("has-error");
}
});
if (!validEmail) { alert("Please enter your email to subscribe");
}else {
//for valid emails sent data to the server
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $('.subcribe-form').serialize(),
success: function(serverResponse) {
//... do something with the server Response...
}
});
}
return validEmail;
});
Add preventDefault so that form submission is prevented
$(".subcribe-form").submit(function(event){
event.preventDefault()
use serialize and post to send your data to desired url
Just handle the form submission on the submit event, and return false:
if using AJAX : (With ajax you can either do that, or e.prenventDefault (), both ways work.)
$(".subcribe-form").submit(function(){
... // code here
return false;
});
If using simple form :
$(".subcribe-form").submit(function(e){
... // code here
e.preventDefault();
});
In my opinion it would be easier to do it using PHP. If you do not want to use PHP, then you can ignore this answer.
If you want to give it a try, you can do the following:
1. Remove the action attribute from the form tag.
2. Write PHP code similar to:
if (isset($_POST['submit']) { // "submit" is the name of the submit button
onSubmit();
}
function onSubmit() {
/* your code here */
}
This is how I stay on the same page, a minimal example using jQuery:
<form id=f
onsubmit="$.post('handler.php',$('#f').serialize(),d=>r.textContent+=rd.innerHTML=d);return false">
<textarea name=field1 id=t>user input here</textarea>
<input type=submit>
</form>
<textarea id=r width=80></textarea>
<div id=rd></div>
The key is to return false from the form onsubmit handler.
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 login form where are two buttons - "login" and "forgot password?" And I need to check what button user clicked.
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
</form>
var_dump($_POST) says:
array(2) { ["email"]=> string(0) "" ["password"]=> string(0) "" }
I am trying both ways (input type=submit and button type=submit) but none of them send the "submit" value.
(I am using jquery ajax)
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php", /* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function(data){
$("#login-error").html(data);
},
error:function(){
$("#result").html('There is error while submit');
}
});
});
Please do you know where the problem can be? I know, there are lot of threads about value of button but nothing works for me. I also tried this example:
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_button_value2
The .serializeArray() or .serialize() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button. Data from file select elements is not serialized.
Refer..
http://api.jquery.com/serialize
http://api.jquery.com/serializeArray
jQuery serializeArray doesn't include the submit button that was clicked
This is one way to do it, concatening data string with specific clicked button name attribute:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit">Login</button>
<button type="button" name="forgot" class="submit">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize() + '&' + this.name;
console.log(values);
/* Send the data using post and put the results in a div */
$.ajax({
url: "login.php",
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
But better would be to target specific server side script depending which button is clicked, e.g:
HTML:
<form id="loginForm">
<div class="login-error" id="login-error"></div>
<input type="text" id="email" name="email">
<input type="password" id="password" name="password">
<button type="button" name="login" class="submit" data-url="login.php">Login</button>
<button type="button" name="forgot" class="submit" data-url="forgot.php">Forgot password?</button>
</form>
JQ:
$("#loginForm").on('click', '.submit', function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Get some values from elements on the page: */
var values = $(this).closest('form').serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: $(this).data('url'),
/* here is echo var_dump($_POST); */
type: "post",
data: values,
success: function (data) {
$("#login-error").html(data);
},
error: function () {
$("#result").html('There is error while submit');
}
});
});
It will be a lot easier to check if you name the submit input and the button differently.
You currently have this set up like this:
<input type="submit" name="submit" value="Login">
<button type="submit" name="submit" value="Forgot password?">Forgot password?</button>
Try changing the name of the button to something like:
name="forgot"
then you can run a check on it such as
if (isset($_POST['submit'])){
stuff here
}
and a separate check for
if (isset($_POST['forgot'])){
stuff here
}
If there is not event in function then it will not prevent the submit function and by default get will be called and and $_POST will be empty for sure
Change
$("#loginForm").click(function(){
/* Stop form from submitting normally */
event.preventDefault();
To
$("#loginForm").click(function(event){
/* Stop form from submitting normally */
event.preventDefault();
Make one more change
data: values,
To
data:$("#loginForm").serialize(),
Remove one submit type there should be only one submit type make it type of button and call onbutton click functiuon to submit via ajax it will work same as submit.