After form submit redirect without refresh using Ajax in laravel 8 - ajax

I am developing multi Step Form Submit without refresh. collect the data from 1st step 2nd step collect some date, 3rd step collect some date & finally submit data in the database. Can you tell me how to fix this.
My blade template.
<form id="post-form" method="post" action="javascript:void(0)">
#csrf
<div>
<input class="form-input" type="text" id="ptitle" name="ptitle" required="required"
placeholder="What do you want to achieve?">
</div>
<button type="text" id="send_form" class="btn-continue">Continue</button>
</div>
</form>
Ajax Script
$(document).ready(function() {
$("#send_form").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var ptitle = $('#ptitle').val();
$.ajax({
url: "{{route('create.setp2') }}",
method:'POST',
data: {_token:_token,ptitle:ptitle},
success: function(data) {
alert('data.success');
}
});
});
Web.php router
Route::post('/setp2', [Abedoncontroller::class, 'funcsetp1'])->name('create.setp2');
Controller method
public function funcsetp1(Request $request) {
$postdata=$request->input('ptitle');
return response()->json('themes.abedon.pages.create-step-2');
}

Related

Success function not being called after making AJAX request codeigniter

When I make an AJAX call from view and pass form data to the controller. I get a couple of problems. First, the code inside success is never executed, and second, the page is being refreshed even though it is an AJAX call. Can anyone tell me where am I doing wrong?
I have seen a lot of questions since yesterday but none of them were able to solve my problem.
Model code
public function insert_user($name, $email) {
$data = array();
$data['name'] = $name;
$data['email'] = $email;
$data['created_at'] = date('y-m-d');
$this->db->insert('all_users', $data);
return true;
}
Controller code
public function insert_user () {
$data = $this->input->post();
$name = $data['name'];
$email = $data['email'];
$this->User_model->insert_user($name, $email);
$this->load->view('view');
}
Ajax request code
const insertBtn = $(".insert-btn");
insertBtn.on("click", function () {
const name = $(".insert-form input[type=name]");
const email = $(".insert-form input[type=email]");
$.ajax({
url: "<?php echo base_url() ?>index.php/Users/insert_user",
type: "post",
data: {name, email},
dataType: "json",
success: function () {
$("body").append("Request made successfully");
}
})
});
My form looks something like this:
<form class="insert-form" action="<?php echo base_url() ?>index.php/Users/insert_user" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<button class="insert-btn">Insert Data</button>
</form>
NOTE: I am able to successfully insert data into the database.
The browser is submitting the form before your AJAX code gets a chance to run/finish.
Instead of binding an event to the click event of the button, you want to bind to the submit event of the form. Then you want to cancel the browser's default action. This is done via the e.preventDefault(); method.
Also, dataType: "json" is not needed here. dataType tells jQuery what kind of data your AJAX call is returning. You generally don't need it as jQuery can automatically detect it. Plus, if you are not returning a JSON document, then this may cause a problem.
const insertForm = $(".insert-form");
insertForm.on("submit", function (e) {
const name = insertForm.find("input[type=name]");
const email = insertForm.find("input[type=email]");
e.preventDefault();
$.ajax({
url: "<?php echo base_url() ?>index.php/Users/insert_user",
type: "post",
data: {name, email},
success: function () {
$("body").append("Request made successfully");
}
})
});
Controller code
public function insert_user () {
$data = $this->input->post();
$name = $data['name'];
$email = $data['email'];
$data = $this->User_model->insert_user($name, $email);
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
Ajax request code
const insertBtn = $(".insert-btn");
insertBtn.on("click", function () {
const name = $(".insert-form input[type=name]");
const email = $(".insert-form input[type=email]");
$.ajax({
url: "<?php echo base_url() ?>Users/insert_user", // <?php echo base_url() ?>controller_name/function_name
type: "post",
data: {name, email},
dataType: "json",
success: function () {
$("body").append("Request made successfully");
}
})
});
form looks something like this:
<form class="insert-form" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<button class="insert-btn">Insert Data</button>
</form>
The page was being refreshed because I had a button that was acting as submit button on changing it to the input of the type button it does not submits the form and we don't see the page being refreshed. And also the AJAX request made also runs successfully.
<form class="insert-form" action="<?php echo base_url() ?>index.php/Users/insert_user" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<input type="button" class="insert-btn" value="Insert Data">
</form>

Ajax call is being accidently triggered

I'm creating a login page and at the bottom of the pop-up form, there is another button that takes you to the registration page. The issue appears to be that when navigating to the new page it all sits under the original sign-in form which uses an ajax call to check if the user exists so when they try to submit the registration form it then calls that ajax call from the sign-in form.
Sign-in form
<div id="myForm">
<form onsubmit="return false;" id="loginForm">
<h1>Login</h1>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="psw" placeholder="Enter Password" name="psw" required>
<div id="message" class="alert-danger"></div>
<br />
<button type="submit" id="submit" class="btn">Login</button>
<button type="button" class="btn cancel" onclick="closeForm();">Close</button>
</form>
<div class="d-inline">
<button class="btn-info">#Html.ActionLink("User Registration", "SignUp", "SignUp_SignIn")</button>
</div>
</div>
Then the ajax call is
$(document).ready(function () {
$("form").on('submit', function (event) {
var data = {
'email': $("#email").val(),
'psw': $("#psw").val()
};
$.ajax({
type: "POST",
url: 'SignUp_SignIn/CredentialCheck',
data: data,
success: function (result) {
if (result == true) {
$("#message").text("Login attempt was successful");
}
else {
$("#message").text("Email/Password didn't match any results");
}
},
error: function () {
alert("It failed");
}
});
return false;
});
});
After looking at the comments I realized that the reason that the login form was being called from the layout.cshtml so when the ajax call was being called it was grabbing all the form tags that existed on any page that was loaded up. After changing the ajax so it was calling a specific id for the login form instead of form it allowed for proper actions to take place.
An example of what I'm refusing to
$(document).ready(function () {
$("form").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});
The above will try to redirect you on the submit of any form that is loaded up, but if we go through and change the way it accesses the form like below then it will only work if the one specific form is submitted.
$(document).ready(function () {
$("#loginForm").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});

ajax form in CodeIgniter - sending generated form

I want to open a modal and get the content (the formular) form the controller. These steps work fine.
Now I have the formular inside the modal. How I can submit these formular and process it with the same controller function?
At the Moment I do the Ajax-Call in this way
$('.modaldisconnect').click(function(){
var modid = $(this).attr('modid');
$.ajax({
url: "<?php echo base_url() ?>admin/module/disconnect_form",
method: "POST",
data: {modid:modid},
// Callback function that is executed after data is successfully sent and received
success: function(data){
// Print the fetched data of the selected phone in the section called #phone_result
// within the Bootstrap modal
$('.modal-ajax-content').html(data);
// Display the Bootstrap modal
$('#disconnect_modal').modal('show');
},
error: function(error){
// Show error message
alert('error');
}
});
});
This is the form which will be generate from the controller by the call above
echo' <div class="modal-body">
<div id="modul_disc_infos">
<span class="module-headlines-title">'._l("modul_name").': <span id="disc_modulname">'._l('module_'.$result->folder.'_titel').'</span></span>
<span class="module-headlines-subtitle">'._l("modul_disconnect_deadline").': <span id="disc_enddate">'.$enddate.'</span></span>
</div>
<div id="modul_disc_check">
<div class="alert alert-danger" role="alert">'._l("modul_disconnect_disclaimer").'</div>
<hr>
<input type="checkbox" name="check_disclaimer" value="1"> '._l("modul_disconnect_disclaimer_check").'
<input type="hidden" name="modid" value="'.$this->input->post('modid').'">
<input type="hidden" name="formstep" value="1">
'.$errormsg.'
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">'._l('close').'</button>
<button type="button" class="btn btn-danger" id="submit_disconnect" >'._l('modul_disconnect_now').'</button>
</div>';
By the way - is there a better way to parse the values of the formular instead one by one like in my code "var modid = $(this).attr('modid');"?
I've solved that in this way that i do 2 different ajax call, starts with a click or submit on the form or a specific button. One call generate the form, one call handle the form. For me it works and its a little bit flexibel to use the same functions for different jobs.
//Formular for disconnection
$('.modaldisconnect').click(function(){
var modid = $(this).attr('modid');
$('#ajax_modal_title').html('<?php echo _l('modul_disconnect'); ?>');
$.ajax({
url: "<?php echo base_url() ?>admin/module/disconnect_form",
method: "POST",
data: {modid:modid},
// Callback function that is executed after data is successfully sent and recieved
success: function(data){
// Print the fetched data of the selected phone in the section called #phone_result
// within the Bootstrap modal
$('.modal-ajax-content').html(data);
// Display the Bootstrap modal
$('#ajax_modal').modal('show');
},
error: function(error){
// Show error message
alert('error');
}
});
});
//Handle the disconnection
$("#ajax_form").on("submit", function (event) {
event.preventDefault();
subform=$('input[name="subform"]').val();
$.ajax({
url: "<?php echo base_url() ?>admin/module/"+subform+"_form",
type: "POST",
data: $('#ajax_form').serialize(),
success: function(result){
$('.modal-ajax-content').html(result);
},
error: function(error){
// Show error message
alert('error');
}
});
});

AJAX Post to MVC Controller model every time empty

I am trying to send some data from a modal dialog to my controller with Ajax. But my modelfields are always null, but I enter my actionmethod in the controller.
This is a shortend version of my cshtml-file.
#model anmespace.MyModel
<form method="post" id="formID">
...
<div class="row">
<div class="col-md-5">#Resource.GetResource("MyModal", "Firstname")</div>
<div class="col-md-7"><input type="text" class="form-control" id="firstname" value="#Html.DisplayFor(model => model.FirstName)"></div>
</div>
...
<input type="submit" class="btn btn-primary" value="Submit" />
</form>
<script>
$("#formID").on("submit", function (event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("ActionName", "Controller")",
data: frmValues,
success: function (data) {
alert(data);
}
});
});
</script>
Sorry MVC/Ajax are really new for me.
If you want to bind the form data to model then, the names of HTML elements should match with Model properties.
Note: name attribute value of html input field should match to the property of a model.
When you use form and submit button then it will try to reload the page by posting data to the server. You need to prevent this action. You can do this by returning false on onSubmit event in the Form element.
When you use jquery, do not forget to keep the ajax call/events inside the $(document).ready(function(){}) function.
I have written a simple code which takes First Name as input and makes an ajax call on clicking on submit button.
Html & Jquery Code:
<script>
$(document).ready(function() {
$("#formID").on("submit", function(event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("PostData", "Home")",
data: frmValues,
success: function(data) {
alert(data.FirstName);
}
});
});
});
</script>
<div>
<form method="post" id="formID" onsubmit="return false;">
<input id="FirstName" name="FirstName"/>
<input type="submit" value="submit" />
</form>
</div>
My Model :
public class Person
{
public string FirstName { get; set; }
}
Action Method:
public ActionResult PostData(Person person)
{
return Json(new { Success = true, FirstName = person.FirstName });
}
Output:

Can't get form data to post via AJAX using Fancybox

I'm using Fancybox to have a contact form pop up when a link is clicked. Then it POSTs the form data to a php file, an email goes out and a success message comes back.
After I submit my form is that the page reloads and the data seems to go nowhere. If I submit the form without using AJAX it works fine but then loads a new page.
Form:
<div style="display:none">
<div id="questions">
<form id="question-form" action="" method="POST">
<p>Name</p> <input type="text" name="name">
<p>Email</p> <input type="text" name="email">
<p>Item</p> <input type="text" name="item">
<p>Message</p><textarea name="message" rows="6" cols="25"</textarea>
<br/>
<input type="submit" value="Send">
</form>
</div>
</div>
Script
$("#question-form").bind("submit", function() {
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "/includes/question-mailer.php",
data : $(this).serializeArray(),
success : function(data) {
$.fancybox(data);
}
});
return false;
});
What am I doing wrong?
It was a simple mistake, I was putting the script above in its own <script> tags instead of in the main fancybox attach script. My final code is:
<script type="text/javascript">
$(document).ready(function(){
$("a.lightbox").fancybox({
'transitionIn' : 'fade',
'transitionOut' : 'fade',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : false
});
$("#question-form").bind("submit", function() {
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "/includes/question-mailer.php",
data : $(this).serializeArray(),
success :function(data){
$.fancybox(data);
}
});
return false;
});
});
</script>

Resources