Laravel Batch Update Data Based on Checked Checkboxes Error - ajax

I have a table that has checkboxes on the left column that looks like this :
Table
What I want to try to do is assign a surveyor name using the select option in a modal to the surveyor column for all of the checked rows.
Modal
If I checked the first 4 rows of the table and then click the "Try Assign", it will only fill the last checked row (4th row), not all of the checked rows.
I think I've already used Foreach in my Controller so I don't know yet what is wrong with my code.
Result
This is my modal code :
<div class="modal fade" id="city-modal" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="CityModal"></h4>
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="CityForm" name="CityForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name" id="labelname" class="col-sm-2 control-label">Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter City Name" maxlength="50">
</div>
</div>
<div class="form-group">
<label for="name" id="labelpopulation" class="col-sm-2 control-label">Population</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="population" name="population" placeholder="Enter City Population" maxlength="50">
</div>
</div>
<div class="form-group">
<label id="labelsurveyor" class="col-sm-2 control-label">Surveyor</label>
<div class="col-sm-12">
<select class="form-control select2" id="surveyor_id" name="surveyor_id" ">
<option value="">--Select Surveyor--</option>
#foreach($users as $surveyor)
<option value="{{ $surveyor->id }}">
{{$surveyor->name}}
</option>
#endforeach
</select>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-save">Save changes</button>
</div>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
This is my JavaScript code for assigning the surveyor:
$(document).on('click', '.try-assign', function(e) {
var cityId = [];
var svrid;
$('.checkbox:checked').each(function() {
cityId.push($(this).val());
console.log(cityId);
});
if (cityId.length > 0) {
$.ajax({
type: "PUT",
url: "{{ url('try-assign') }}",
data: {
cityId,
svrid
},
dataType: "json",
success: function(res) {
$('#CityModal').html("Assign Surveyor");
$('#city-modal').modal('show');
$('#labelname').attr('hidden', true);
$('#labelpopulation').attr('hidden', true);
$('#labelsurveyor').attr('hidden', false);
$('#id').val(res.id);
$('#name').val(res.name).attr('hidden', true);
$('#population').val(res.population).attr('hidden', true);
$('#surveyor_id').val(res.surveyor_id).attr('disabled', false);
$('#surveyor_id').trigger('change');
svrid = res.surveyor_id;
}
});
} else {
alert('Please select atleast one row');
}
});
This is my tryAssign() function on the Controller :
public function tryAssign(Request $request)
{
$cityId = $request->cityId;
$svrid = $request->svrid;
foreach ($cityId as $key => $value) {
$city = City::find($value);
$city->surveyor_id = $svrid;
$city->update();
}
return Response()->json($city);
}
And, this is my route :
Route::put('try-assign', [CityController::class, 'tryAssign']);

Related

Edit Data on Modal Using Ajax

I want to edit my data on a modal and I can't pass my data from JSON to the modal.
I tried to print my JSON using console.log() function and it works fine. But when I'm trying to pass the data to my modal, it doesn't work.
Here's my script:
$(document).on('click', '.editBtn', function(e){
e.preventDefault();
edit_id = $(this).attr("id");
$.ajax({
url:"action.php",
method:"POST",
data:{edit_id:edit_id},
dataType:"json",
success:function(data){
// data = JSON.parse(response);
console.log(data);
$('#id').val(data.id); //id name of the modal; the hidden type
$('#fname').val(data.fname);
$('#lname').val(data.lname);
$('#email').val(data.email);
$('#phone').val(data.phone);
}
});
});
Here's how I encode my JSON:
if (isset($_POST['edit_id'])){
$id = $_POST['edit_id'];
$row = $db->getUserById($id);
echo json_encode($row);
}
And here's my code for getUserByID():
public function getUserById($id){
$sql = "SELECT * FROM users WHERE id = ?";
$stmt = $this->conn->prepare($sql);
$stmt->execute([$id]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
Btw, here's my code for the modal:
<div class="modal fade" id="editModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit User</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body px-4">
<form accept="" method="post" id="edit-form-data">
<input type="hidden" name="id" id="id">
<div class="form-group">
<input type="text" name="fname" class="form-control" id="fname" required>
</div>
<div class="form-group">
<input type="text" name="lname" class="form-control" id="lname" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" id="email" required>
</div>
<div class="form-group">
<input type="tel" name="phone" class="form-control" id="phone" required>
</div>
<div class="form-group">
<input type="submit" name="update" id="update" value="Update User" class="btn btn-primary btn-block">
</div>
</form>
</div>
</div>
</div>
</div>
I've already figured it out. My code in script is incomplete. It should be data[0].id etc.

Cannot save value using ajax in laravel

I'm using laravel and trying to save data using post through ajax but data is not saved in database. I'm getting following error: jquery.min.js:2 POST http://localhost:8000/admin/products/attributes/add 500 (Internal Server Error). My code is as follows:
view:
<script>
$("#add_attributes_info").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success'+msg);
}
});
});
</script>
<form action="#" id="frmattributes" method="POST">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price"/>
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
Controller:
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->data);
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
You should use:
$productAttribute = ProductAttribute::create($request->all());
However you should keep in mind this is very risky without validation.
You should add input validation and then use:
$productAttribute = ProductAttribute::create($request->validated());
Use $request->all();
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->all());
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
PS : I made some changes to get it works
Hope this help
<head>
<title></title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function submitForm() {
$.ajax({
type: "POST",
url: '../admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success' + msg);
}
});
}
</script>
</head>
<body>
<form id="frmattributes">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price" />
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info" type="button" onclick="submitForm()">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
</body>
</html>
So in the controller, change the $request->data with :
$productAttribute = ProductAttribute::create($request->all());
or also check what the request contains, before creating you can check using:
dd($request->all());

Laravel Vue.js API: axios' PUT method doesn't send any data to controller

I'm trying to update some data in Model using API in Laravel and Vue.js
but I can't do this because axios doesn't send any data to server, I'm checking the data right before sending and they exist (I use FormData.append to add all fields)
I check data before sending using the code:
for(var pair of formData.entries()) {
console.log(pair[0]+ ': '+ pair[1]);
}
and I get this result:
You can check the appropriate code:
[function for updating]
updateStartup() {
let formData = new FormData();
formData.append('startup_logo', this.update_startup.startup_logo);
formData.append('country_id', this.update_startup.country_id);
formData.append('category_id', this.update_startup.category_id);
formData.append('startup_name', this.update_startup.startup_name);
formData.append('startup_url', this.update_startup.startup_url);
formData.append('startup_bg_color', this.update_startup.startup_bg_color);
formData.append('startup_description', this.update_startup.startup_description);
formData.append('startup_public', this.update_startup.startup_public);
axios.put('/api/startup/' + this.update_startup.id, formData, { headers: {
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error.response);
});
}
[controller method where I should receive data]:
public function update(Request $request, $id) {
return $request; // just for checking if I get data
...
}
[HTML with vue.js where I use object which I send in updateStartup function]:
<!-- Modal edit -->
<div class="modal fade editStartUp" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<img src="/admin/images/modal-cross.png" alt="Close">
</button>
</div>
<div class="modal-body">
<form method="POST" enctype="multipart/form-data" #submit.prevent="updateStartup">
<h4 class="sel-c-t">Select category</h4>
<div class="submit-fields-wr">
<select name="category" v-model="update_startup.category_id" class="selectpicker select-small" data-live-search="true" #change="updateCategoryDetails()">
<option v-for="category in categories" :value="category.id" :selected="category.id == update_startup.category_id ? 'selected' : ''" >{{ category.name }}</option>
</select>
<select v-if="update_startup.is_admin" name="country" v-model="update_startup.country_id" class="selectpicker select-small" data-live-search="true" #change="updateCountryDetails()">
<option v-for="country in countries" :value="country.id" :selected="country.id == update_startup.country_id ? 'selected' : '' ">{{country.name }}</option>
</select>
</div>
<div class="submit-fields-wr">
<input type="text" placeholder="Startup name" v-model="update_startup.startup_name">
<input type="url" v-model="update_startup.startup_url" placeholder="URL">
</div>
<textarea v-model="update_startup.startup_description" name="startup_description" placeholder="Describe your startup in a sentence.">
</textarea>
<div v-if="!update_startup.is_admin">
<h4 class="sel-c-t bold">Contact details:</h4>
<div class="submit-fields-wr">
<select name="country" v-model="update_startup.country_id" class="selectpicker select-small" data-live-search="true" #change="updateCountryDetails()">
<option v-for="country in countries" :value="country.id" :selected="country.id == update_startup.country_id ? 'selected' : '' ">{{country.name }}</option>
</select>
<input type="text" placeholder="Your Name" v-model="update_startup.contact_name">
</div>
<div class="submit-fields-wr">
<input type="text" v-model="update_startup.contact_phone" placeholder="Your phone number">
<input type="email" v-model="update_startup.contact_email" placeholder="Your email address">
</div>
</div>
<p class="upl-txt">Company’s logo.<span>(upload as a png file, less than 3mb)</span></p>
<div class="file-upload">
<div class="logo-preview-wr">
<div class="img-logo-preview">
<img :src="update_startup.startup_logo" alt="logo preview" id="img_preview">
</div>
</div>
<label for="upload" class="file-upload_label">Browse</label>
<input id="upload" #change="onFileUpdated" class="file-upload_input" type="file" name="file-upload">
</div>
<div class="preview-divider"></div>
<h4 class="sel-c-t bold">Preview:</h4>
<div class="preview-wrapper-row">
<a href="#" class="start-up-wr">
<div class="start-up-part-1 edit">
<div class="flag-cat-wr">
<div class="flag-wr">
<img :src="update_startup.country_flag" :alt="update_startup.country_name">
</div>
<div class="category-wr">
{{ update_startup.category_name }}
</div>
</div>
<img :src="update_startup.startup_logo" :alt="update_startup.startup_name" class="start-up-logo">
</div>
<div class="start-up-part-2">
<h4 class="startup-name">{{ update_startup.startup_name }}</h4>
<p class="startup-description">
{{ update_startup.startup_description }}
</p>
</div>
</a>
<div class="color-picker-btns-wr">
<div>
<input type="text" class="color_picker" v-model="update_startup.startup_bg_color">
<button class="colo_picker_btn">Background Color</button>
</div>
<div class="modal-bottom-btns">
<div class="btn-deactivate-active">
<button type="submit" class="btn-deactivate" #click="deactivateExistingStartup()">Deactivate</button>
<button type="submit" class="btn-activate" #click="activateExistingStartup()">Activate</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Modal edit -->
[Additional info - also when I open modal(where I have form for updating) I change form data accordingly to startup id]:
showUpdateStartup(startup) {
setTimeout(() => {
$('.selectpicker').selectpicker('refresh');
}, 50);
this.update_startup.id = startup.id;
this.update_startup.category_id = startup.category.id;
this.update_startup.category_name = startup.category.name;
this.update_startup.startup_name = startup.name;
this.update_startup.startup_description = startup.description;
this.update_startup.startup_url = startup.url;
this.update_startup.startup_logo = startup.logo;
this.update_startup.startup_bg_color = startup.startup_bg_color;
this.update_startup.contact_id = startup.contact.id;
this.update_startup.contact_name = startup.contact.name;
this.update_startup.contact_phone = startup.contact.phone;
this.update_startup.contact_email = startup.contact.email;
this.update_startup.country_id = startup.contact.country.id;
this.update_startup.country_flag = startup.contact.country.flag;
this.update_startup.country_name = startup.contact.country.name;
this.update_startup.is_admin = startup.contact.is_admin;
this.update_startup.startup_public = startup.public;
},
Let me know if you have any additional questions
Thank you guys a lot for any help and ideas!
Try using formData.append('_method', 'PATCH') with axios.post method.
Return the input data instead of the Request object from your controller:
return $request->input();

pass multiple checkbox value using ajax in codeigniter to the database

iam trying to pass multiple check box value to the database using ajax.But this code is not working,please help me to find the answer. This is my jquery and ajax
jQuery(".bus-cat-drop").change(function(event) {
$('.check').html("");
var businesscategoryid = $(this).val();
hitURL = baseURL + "user/postbusiness/get_businesscategoryid/";
alert(baseURL + "user/postbusiness/get_businesscategoryid");
//alert(businesscategoryid);
jQuery.ajax({
type : "POST",
dataType : "json",
url : hitURL,
data : { categoryid : businesscategoryid }
}).done(function(data){
$.each(data, function(key,value) {
//alert(key);
//alert(value.value);
/* var opt = $('<option />');
opt.val(value.value);
opt.text(value.label);
$('#subcategory').append(opt);
$('#subcategory').get(0).selectedIndex = 1; */
$('.check').append("<input name=check[]:checked type=checkbox>"+value.label+"</br>");
$('.check').push(this.value);
});
});
iam trying to pass multiple check box value to the database using ajax.But this code is not working,please help me to find the answer. Here is my view.
<form client ="form" id="bus-reg-form" action="<?php echo base_url().'user/postbusiness/DirectoryCategory/'.$userId ?>" method="post" role="form">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="company">Name of Business / Company </label>
<input type="text" class="form-control required" id="company" name="company" value="<?php echo $company_name;?>">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="Category">Category</label>
<select class="form-control bus-cat-drop" id="businesscategory" name="businesscategory">
<option value="0">Select Category</option>
<?php
if(!empty($list_directorycategory))
{
foreach ($list_directorycategory as $rl)
{
?>
<option value="<?php echo $rl->dr_cat_id; ?>"><?php echo $rl->dr_cat_name;?></option>
<?php
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<div class="subcategory-dropdown">
<label for="subcategory"> Sub Category [Maximum 3 subcategory]</label>
<div class="check" name="check[]" >
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="Business-Offer">
<label for="business">Business Offer / Highlights</label>
<textarea class="form-control required" title="Business description" id="business" rows="6" name="business"></textarea>
</div>
</div>
</div>
</div>
<div class="row">
<div class="control-group col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-group">
<label for="Tags">Tags [Maximum 10 tags]</label>
<input type="text" class="form-control required" id="tags" name="tags">
</div>
</div>
</div>

AJAX within a modal inserting a form in CodeIgniter

Been struggling with this for about 4 hours, I'm attempting to have a modal drop down (Twitter bootstrap modal) that contains a form to create a Company. This is built in CodeIgniter.
I'm having issues with input type="submit" and input type="button".
I only have 1 required field, which is Company Name. If I use input type="button", the validation will fire correctly inside of the modal, however the form will only INSERT just the company name, along with company_id, user_id, active, and cdate.
Now if I use input type="submit", all the data inserts fine. However, the validation breaks and I get a "Page cannot be found" after clicking "Create Company", the data is still inserting though.
Any ideas? Thanks! New to AJAX...
My AJAX function:
$(document).ready(function(){
$('#create_btn').live('click', function(){
//we'll want to move to page specific files later
var name = $('#name').val();
$.ajax({
url: CI_ROOT + "members/proposals/add_client",
type: 'post',
data: {'name': name },
complete: function(r){
var response_obj = jQuery.parseJSON(r.responseText);
if (response_obj.status == 'SUCCESS')
{
window.location = CI_ROOT + response_obj.data.redirect;
}
else
{
$('#error_message2').html(response_obj.data.err_msg);
}
},
});
});
});
My controller function which handles the insert:
function add_client()
{
$this->form_validation->set_rules('name', 'Company Name', 'trim|required|xss_clean');
load_model('client_model', 'clients');
load_model('industry_model');
$user_id = get_user_id();
$company_id = get_company_id();
if (!$user_id || !$company_id) redirect('home');
if ($_POST)
{
if ($this->form_validation->run() == TRUE)
{
$fields = $this->input->post(null , TRUE);
$fields['user_id'] = $user_id;
$fields['company_id'] = $company_id;
$fields['active'] = 1;
$fields['cdate'] = time();
$insert = $this->clients->insert($fields);
if ($insert)
{
$this->message->set('alert alert-success', '<h4>Company has been added</h4>');
header('location:'.$_SERVER['HTTP_REFERER']);
}
else
{
$this->message->set('alert alert-error', '<h4>There was an issue adding this Company, please try again</h4>');
}
}
else
{
$err_msg = validation_errors('<div class="alert alert-error">', '</div>');
$retval = array('err_msg'=>$err_msg);
$this->ajax_output($retval, false);
}
}
$this->data['industries'] = array(0=>'Select Industry...') + $this->industry_model->dropdown('industry');
$this->insertMethodJS();
$this->template->write_view('content',$this->base_path.'/'.build_view_path(__METHOD__), $this->data);
$this->template->render();
}
And finally, my view:
<div class="modal hide fade" id="milestone" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="width: 600px !important;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Add a Company</h3>
</div>
<div class="modal-body">
<?php echo form_open_multipart(base_url().'members/proposals/add_client', array('class' => '', 'id' => 'client_form'));?>
<div id="error_message2"></div>
<div class="row-fluid">
<div class="span5">
<input type="hidden" name="cdate" id="cdate" value="" />
<div class="control-group">
<label class="control-label">Company Name: <span style="color: red;">*</span></label>
<div class="controls">
<input type="text" id="name" name="name" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Company Abbreviation:<span style="color: red;">*</span></label>
<div class="controls">
<input type="text" id="abbreviation" name="abbreviation" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Company Image: </label>
<div class="controls">
<input type="file" name="client_image" size="20" />
</div>
</div>
</div>
<div class="span5">
<div class="control-group">
<label class="control-label">Website:</label>
<div class="controls">
<input type="text" id="website" name="website" value=""/>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span5" style="margin-top: 25px;">
<div class="control-group">
<div class="controls">
<p><strong>Client</strong></p>
</div>
</div>
<div class="control-group">
<label class="control-label">Address 1:</label>
<div class="controls">
<input type="text" id="address1" name="address1" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Address 2:</label>
<div class="controls">
<input type="text" id="address2" name="address2" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">City:</label>
<div class="controls">
<input type="text" name="city" id="city" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">State:</label>
<div class="controls">
<?= form_dropdown('state', usa_state_list(), set_value('state'), 'id=state'); ?>
</div>
</div>
<div class="control-group">
<label class="control-label">Zip:</label>
<div class="controls">
<input type="text" id="zip" name="zip" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">Country:</label>
<div class="controls">
<?= form_dropdown('country', country_list(), set_value('country'), 'id=country'); ?>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button type="submit" class="btn btn-primary" id="create_btn">Create Company</button>
</div>
</form>
</div>
So again, to summarize. With input type="button", my validation works great within the modal and only the Company Name is inserting into the database along with company_id, user_id, active, and cdate.
Now, with input type="submit", all data inserts great, however validation fails and I get a redirect to a page cannot be found.
Again, thanks!
The issue is with your ajax function call.
You need to prevent the form from firing (and thus submitting via post to the url in action):
Change:
$('#create_btn').live('click', function(){
To:
$('#create_btn').live('click', function(e){
e.preventDefault();
This should fix the issue. If it doesn't, let me know and I'll do more digging. I would also recommend switching live to on so that you future-proof yourself. on handles the same stuff as live, bind, etc. in a single function with more efficiency.
Edit: To explain what's going on (and why you must use e.preventDefault();), it is because <input type="submit"> will actually submit the form to the url specified in the <form> tag's action attribute. Thus, what's happening with your code is that your javascript is running as soon as you click the button, and then the native browser submit event is occurring immediately afterwards.

Resources