Update table after insert a new row to database with AJAX - javascript

I'll try to be as clear as I can. I'm trying to code a CRUD. I have a table that shows all the info about products. To register a new item I have a form in a modal and it sends the data with AJAX to a .php file called 'registro.php' where the data is inserted into the MySQL table.
I'd like to make that after clicking the 'Submit' button of the new-item form, the table auto-realoaded showing the new row too without refreshing the page.
The INSERT INTO is working fine but after inserting a new item, the <table> that displays all the data just disappears
So, this is my form # index.php
<div class="modal fade" id="myModalNorm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" id="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">×</span>
<span class="sr-only">Cerrar</span>
</button>
<h4 class="modal-title" id="myModalLabel"> Registrar un artículo </h4>
</div>
<div class="modal-body">
<!-- Modal form -->
<form name="nuevo_registro" id="nuevo_registro" action="" onsubmit="registrarNew(); return false">
<div class="form-group">
<label for="descripcion">Descripción</label>
<input type="text" class="form-control" id="descripcion" name="descripcion" placeholder="Descripción del artículo"/>
</div>
<div class="form-group">
<label for="precio">Precio</label>
<div class="input-group">
<span class="input-group-addon">Bs.</span>
<input type="text" class="form-control" id="precio" name="precio" placeholder="Precio"/>
</div>
</div>
<div class="form-group">
<label for="existencia">Existencia</label>
<input type="text" class="form-control" id="existencia" name="existencia" placeholder="Unidades en existencia"/>
</div>
<button type="submit" name="submit" id="submitmodal" class="btn btn-default">Guardar</button>
</form>
</div>
</div>
</div>
</div>
This is the ajax code at the bottom of index.php
$(document).ready(function() {
$('#nuevo_registro').submit(function(e){
e.preventDefault();
$.ajax({
url: 'registro.php',
type: 'POST',
data: $(this).serialize()
})
.done(function(data){
$('#myModalNorm').modal('toggle');
$('#lista_articulos').fadeOut('slow', function(){
$('#lista_articulos').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
});
And this is registro.php where the data is inserted into the MySQL table
<?php
if ( $_POST ) {
require_once 'dbconnection.php';
$descripcion=$_POST['descripcion'];
$precio=$_POST['precio'];
$existencia=$_POST['existencia'];
$query = "INSERT INTO producto (descripcion, precio, existencia, estado) VALUES ('$descripcion', '$precio', '$existencia', 'A')";
$conexion->query($query);
$conexion->close();
}
?>
Hope you can help me and thank you so much.

I needed to do that, one day, and here's my solution:
Send data to PHP file and INSERT to the mysql database
Get the last inserted ID, find all available data regarding that row
Make an array out of that data and json_encode it
On the main page with the table, find the table and prepend or append the data you just received.

Related

Jquery load whole page instead of only modal

I'm trying to make a "Create project" modal. At first i created it inside a partial view but i found it difficult to populate it with data from other models, so instead i decided to move the partial view content inside my actual razor page.
All works as it should but when I press the button to launch the modal, the current page is loaded in the background as well.
Here is the html for the modal code:
<div class="modal fade" id="add-project" tabindex="-1" role="dialog" aria-labelledby="addProjectLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addContactLabel">Create Project</h5>
</div>
<div class="modal-body">
<form asp-page-handler="ProjectModalPartial">
#*numele metodei*#
<input name="IsValid" type="hidden" value="#ViewData.ModelState.IsValid.ToString()" />
<div class="form-group">
<label asp-for="ProjectsModel.ProjectName">Title</label>
<input asp-for="ProjectsModel.ProjectName" class="form-control" placeholder="MyProject1" />
<span asp-validation-for="ProjectsModel.ProjectName" class="text-danger"></span>
</div>
<br />
<div class="form-group">
<label asp-for="ProjectsModel.ProjectDescription">Description</label>
<textarea asp-for="ProjectsModel.ProjectDescription" class="form-control" rows="3" placeholder="This is my first project"></textarea>
<span asp-validation-for="ProjectsModel.ProjectDescription" class="text-danger"></span>
</div>
<br />
<div class="center" style="padding-bottom:0px;">
<p style=" margin: 2px">Project Participants</p>
<select multiple id="TicketType" class="form-control dropdown-toggle" asp-for="ProjectsModel.ProjectParticipants" asp-items="new SelectList(Model.UserList)" style="width: 470px;"></select>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save</button>
</div>
</div>
</div>
And here is the jquery code,without the logic for saving:
$(function () {
var placeholderElement = $('#modal-placeholder');
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
//$(document.body).html(data).find('.modal').modal('show');
placeholderElement.html(data);
placeholderElement.find('.modal').modal('show');
});
});});
Is there another way of loading the modal, without the additional content?
Here is a photo so you better see what's happening
I managed to solve the problem.
Since I no longer have a partial view I don't need the placeholderElement anymore, so I can get rid of .find(modal) all together.
The code now looks like this:
$(function() {
var placeholderElement = $('#modal-placeholder');
$('button[data-toggle="ajax-modal"]').click(function(event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
$('#add-project').modal('show');
});
});
});

Ajax modal submit parse json response for errors in form, error message repeating itself over both fields

I've got a modal window that is submitting a form to a database via ajax and if an error occurs it will return a json response. This has been working well on modal windows with only one input field, but I have another modal window with 2 fields and the json response correctly returns error messages, for instance:
As you can see, both fields with the error are in the response. Like I said, my script works fine and will show the error for a form with only one text input, but I have two in this form (ignore the first select element, it is pre-filled via ajax). Here's my script that handles the ajax success and error responses:
$(document).ready(function () //function to process modal form via ajax
{
$('.modal-submit').on('submit', function(e){
e.preventDefault(); //prevent default form submit action
var data = $(this).serialize();
var type = $(this).find('input[name="type"]').val(); //get value of hidden input
var url = $(this).attr('action'); //get action from form
var modal = $(this).closest('.modal');
var modalInput = $(this).find('.form-row input'); //get input from form
var modalId = $(this).closest('.modal').attr('id');
$.ajax({
url:url,
method:'POST',
data:data,
success:function(response){
refreshData(newId = response.id, modalId); // set newId to the id of the newly inserted item, get modalId
modal.modal('hide'); //hide modal
$(modalInput).val(''); //clear input value
},
error:function(response){
$.each(response.responseJSON.error, function (i, error) {
console.log(data);
console.log(response.responseJSON.error);
$(modalInput).addClass('input-error');
$('#' + modalId + ' .backend-error').html(error[0]); //return error from backend
});
}
});
});
});
Here's the html for the modal window with multiple inputs:
<!-- Add New Model Modal -->
<div class="modal fade" id="modelModal" tabindex="-1" role="dialog" aria-labelledby="modelModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modelModalLabel">Add new asset model</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" class="modal-submit" autocomplete="off" action="{{ action('AddAssetController#addDescriptor', ['type' => 'model']) }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="type" value="model">
<div class="form-row">
<div class="col-md-12 mb-3">
<label for="inputManufacturerModel">Manufacturer *</label>
<div class="input-group">
<select name="inputManufacturerModel" id="inputManufacturerModel" class="form-control" required="required" onclick="refreshData()">
<option value="0">Select manufacturer...</option>
</select>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-3">
<label for="inputModelNew">New model name *</label>
<div class="input-group">
<input type="text" name="inputModelNew" id="inputModelNew" class="form-control" placeholder="Add manufacturer model name" required="required">
</div>
<div class="backend-error"></div>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-3">
<label for="inputModelNoNew">New model # *</label>
<div class="input-group">
<input type="text" name="inputModelNoNew" id="inputModelNoNew" class="form-control" placeholder="Add manufacturer model #" required="required">
</div>
<div class="backend-error"></div>
</div>
</div>
<div class="float-right">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- / Add New Model Modal -->
Result of error response:
Do I need to loop over the errors? How do I get the relevant error to show under the correct input field?
In ajax error don't use this
$(modalInput).addClass('input-error') because this will add the class to all modal's input and this will set the error to all modal's input. $('#' + modalId + ' .backend-error').html(error[0]);
Use input Id to set error like in your case $('#inputModelNew').parent('.input-group').siblings('.backend-error').addClass('input-error').html(error[0])

Show modal on submit form

Here's the code of an Angular 4 component used to collect contact information from visitors:
.html:
<form (submit)="onCreateContact()">
<div class="form-group">
<input type="text" [(ngModel)]="contactname" name="contactname" class="form-control form-control-lg" placeholder="Name">
</div>
<div class="form-group">
<input type="email" [(ngModel)]="contactemail" name="contactemail" class="form-control form-control-lg" placeholder="Email">
</div>
<div class="form-group">
<input type="text" [(ngModel)]="contactphone" name="contactphone" class="form-control form-control-lg" placeholder="Phone">
</div>
<input type="submit" class="btn btn-outline-light btn-block" data-toggle="modal" data-target='#addContactModal'>
</form>
<!-- Modal -->
<div class="modal fade" id="addContactModal" tabindex="-1" role="dialog" aria-labelledby="addContactModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addContactModalLabel">Contact</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Thanks for contacting us! We will get in touch with you shortly.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
.ts:
onCreateContact() {
let contact = {
contactname: this.contactname,
contactemail: this.contactemail,
contactphone: this.contactphone
}
return this.http.post('api/contacts/add', contact).map(res => res.json()).subscribe(data => {
if(data.success) {
console.log(data);
} else {
console.log('Failed to add contact');
}
}
);
}
All contact fields are required; the data is not passed to the backend if not all fields are filled.
Currently, the Bootstrap modal popups every time I press the submit button, even when the data is not passed. How can I show it only when the data is actually passed to the server?
You are toggling the modal when the user clicks on the submit button.
What you need to do is, toggle the modal from component class(.ts) after getting the response from the backend.
So in your ".ts" file add below line under the imports section
declare var $: any;
Then toggle modal after receiving response from backend as below
onCreateContact() {
return this.http.post('api/contacts/add', contact).map(res => res.json()).subscribe(data => {
if(data.success) {
console.log(data);
$('#addContactModal').modal('show'); // Add this line
} else {
console.log('Failed to add contact');
$('#errorModalId').modal('show'); // If you are planning to show error modal when something goes wrong.
}
});
}
Don't forget to remove data-toggle and data-target attribute from submit button.
Hope this helps.

show the sucess popup after form submit form?

Here i added one form with data model in codeigniter views page
<a class="handCursor " href="javascript:void(0)" id="franchise">Franchisee </a>
<!-- Modal -->
<div class="modal fade" id="franchisee_signup" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form action="<?php echo base_url();?>general/general_form" method="POST" name="signup">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel"><i class="fa fa-desktop"></i> Request For Franchisee Program</h4>
</div>
<div style="clear: both;"></div>
<div class="modal-body clearfix">
<div class="bk_lft" style="width:100%;">
<div class="bk_gr" style="width:100% !important">
<div class="contact_form2">
<div class="bk_roominfo">
<div class="clearfix"></div>
<div class="frm_clmn">
<label>First Name: <em style="color:#F00;">*</em></label>
<input name="first_name" id="txt_name" type="text">
<input name="form_type" id="company_name" type="hidden" value="franchise">
</div>
<div class="frm_clmn1">
<label>Last Name: <em style="color:#F00;">*</em></label>
<input name="last_name" id="txt_lname" type="text">
</div>
<div class="frm_clmn">
<label>Phone: <em style="color:#F00;">*</em></label>
<input name="mobile" id="txt_mobile" type="text">
</div>
<div class="frm_clmn1">
<label>Email: <em style="color:#F00;">*</em></label>
<input name="email" id="txt_email" type="text">
</div>
<div class="frm_clmn1" style="width:100%;">
<label>Message:<em style="color:#F00;">*</em></label>
<textarea name="message" id="txt_message" cols="" rows="" style="resize:none;"></textarea>
</div>
<div class="bk_bt" style="float:left; margin-top:12px;">
<button type="submit" name="send_contact_enq" id="send_contact_enq" value="Continue" style="float:left;">Send</button>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
This is the form and we add the insert query in controller
public function general_form()
{
$post = $this->input->post();
unset($post['send_contact_enq']);
$insert_id = $this->custom_db->insert_record('corporate_form_reqlist',$post);
redirect(base_url()."general/index");
}
after submitting the form while inserting into db and we redirect to front page . we need before redirect from controllers is there is any possible to show the success popup after close the popup message redirect happened .
we tried all my logic which i know but not get the correct response
try passing some value as param and give success message by checking that in redirected page..
redirect(base_url()."general/index?status=success");
and in general/index file
if(isset($_GET['status']) && $_GET['status'] == "success"){
echo "Successfull Message";
}
if($insert_id=='success'){//change success based on the returned value of the model
echo "<script>
alert('Success');
window.location.href='".base_url('general/index')."';
</script>";
}
You can use ajax function for your form that will send data to PHP to execute general_form tasks without redirecting. PHP returns true if successfully inserts record to db and javascript then triggers alert() or prompt() and windows.location = "your redirection link"

Bootstrap modal stay open after form submit and page refresh

I hava a bootstrap modal form that i use to send a 4 field message. After the submit button is press i want to show the user a "thank you" message. But instead of that my form is closing and the page is refreshing.
How can i do for the modal form to stay open in order to display below the submit button the message.
Thank you!
<section class="modal-form">
<!-- Modal Video first page -->
<div class="modal fade" id="participa-modal" tabindex="-1" role="dialog" aria-labelledby="participa-modal">
<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"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Participă la un demo!</h4>
</div>
<div class="modal-body">
<div class="form-group">
<form id="form" method="post" class="contact" action="" enctype="multipart/form-data" data-parsley-validate>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" name="homepage_firstname" id="homepage_firstname" class="form-control-contact" placeholder="Nume" required>
</div>
<div class="form-group">
<input type="email" name="homepage_email" id="homepage_email" class="form-control-contact" placeholder="Email" required>
</div>
<div class="form-group">
<input type="text" name="homepage_phone" id="homepage_phone" class="form-control-contact" placeholder="Telefon" data-parsley-type="number" minlength="10" maxlength="10" required>
<input type="hidden" name="inner_message" id="inner_message" value="Participare demo curs!">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control-contact" name="homepage_message" id="homepage_message" placeholder="Scrisoare de intentie"></textarea>
</div>
</div>
</div>
<div class="form-actions">
<input type="hidden" name="homepagesubmitted" value="TRUE" />
<button type="submit" class="btn orange sign-in-btn">Înscrie-te</button>
</div>
<?php echo $homepage_send ?>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- End Modal Video first page -->
</section>
UPDATE:
Ok. So i've manage to make it work the following code $(function () {
var frm = $('#participa-modal');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
location.reload();
}
});
ev.preventDefault();
});
});
The quetion is how can i replace alert('ok') to point for a thank you in the same pop-up under the SEND button.
$(".modal-body form").submit(function(e) {
var url = "ActionScript.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), // serializes the form's elements.
success: function(data) {
$(this).html("Thank you!!!");
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
check the above code for your requirement
Terms Used
$(".modal-body form") class and child form selector in order to target your submitting form
.submit( to trigger event on submit of your form
type: "POST" is for secure traversing of data, by method post
.serialize() is to gather (assemble) and send the posting data
success: is a callback in order to proceed while the submission is successful.

Categories

Resources