I want to insert data with the help of bootstrap modal. But I've got an error on the action index. So the button I've added couldn't run. Did I make any wrong thing in coding?
Controller
function user_action(){
if ($_POST['action'] == "Tambah"){
$data=array(
'kodebayar' => $this->input->post('kodebayar'),
'nama' => $this->input->post('nama'),
'harga' => $this->input->post('harga')
);
$this->bpem_m->create($data);
}
}
View Of Modal
<div class="modal fade text-xs-left" id="modalpem" tabindex="-1" role="dialog" aria-labelledby="myModalLabel35" aria-hidden="true">
<div class="modal-dialog modal-sm">
<form method= "post" id="form_pem">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<fieldset class="form-group floating-label-form-group">
<label for="Kode">Kode <span class="required">*</span></label>
<input type="text" class="form-control" name="kodebayar" id="kodebayar" placeholder="Kode Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="nama">Nama <span class="required">*</span></label>
<input type="text" class="form-control" name="nama" id="nama" placeholder="Nama Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="projectinput7">Biaya Perbulan <span class="required">*</span></label>
<div class="input-group">
<span class="input-group-addon">Rp.</span>
<input type="number" class="form-control" placeholder="Biaya Perbulan" aria-label="Amount (to the nearest dollar)" name="harga" id="harga">
<span class="input-group-addon">.00</span>
</div>
</fieldset>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-warning" name="action" value="Tambah"/>
</div>
</div>
</form>
</div>
</div>
JS
$(document).on('submit','#form_pem', function(event){
event.preventDefault();
var kodebayar = $('#kodebayar').val();
var nama = $('#nama').val;
var harga = $('#harga').val;
var postData = new FormData(this);
if(kodebayar != '' && nama != '' && harga != ''){
$.ajax({
url:"<?=site_url('bpem/user_action')?>",
method: "POST",
data: postData,
contentType: false,
processData: false,
cache: false,
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
alert(data);
$('#form_pem')[0].reset();
$('#modalpem').modal('hide');
dataTable.ajax.reload();
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});
}
else{
alert("Silahkan isikan semua data!");
}
});
You can use serialize()
var datastring = $("#form_pem").serialize();
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
return type is json
EDIT: I use event.preventDefault to prevent the browser getting submitted in such scenarios.
Related
// save new employee record
$('#saveEmpForm').submit('click',function(){
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
});
<form id="saveEmpForm" method="post">
<div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add New Employee</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-md-2 col-form-label">Jenis</label>
<div class="col-md-10">
<input type="text" name="jenis" id="jenis" class="form-control" required>
<input type="hidden" id="input_id" name="input_id" class="form-control " value="{$input_id}">
</div>
</div>
<div class="form-group row">
<label class="col-md-2 col-form-label">Jarak</label>
<div class="col-md-10">
<input type="text" name="jarak" id="jarak" class="form-control" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>
Save function in controller file
public function save(){
$data=$this->inputs_model->saveEmp();
echo json_encode($data);
}
Save function in Model
public function saveEmp(){
$data = array(
'input_id' => $this->input->post('input_id'),
'jenis' => $this->input->post('jenis'),
'jarak' => $this->input->post('jarak'),
'created_at' => date("Y-m-d h:i:sa"),
'updated_at' => date("Y-m-d h:i:sa")
);
$result=$this->db->insert('input_jenis_industri',$data);
return $result;
}
The code are as stated above, my ajax function to save the data is not working. It is not saving the data in the db. What can cause the problem?
My ajax function calls the InputPembangunan/save to save the data, then the controller try to the save data using the save() function. It is saved using the model saveEmp()
The following is incorrect, there is no click involved in a submit event
$('#saveEmpForm').submit('click',function(){
Change to
$('#saveEmpForm').submit(function(event){
event.preventDefault()// prevent normal form submit
without refreshing the page you have to call event.preventDefault() method after submit event.
replace this
$('#saveEmpForm').submit('click',function(){
with
$('#saveEmpForm').on('submit',function(){
event.preventDefault()
Change this
<button type="submit" class="btn btn-primary">Save</button>
to
<button type="button" class="btn btn-primary">Save</button>
You can onlick() method. Actually I used like this;
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" onclick="save()" class="btn btn-primary">Save</button>
</div>
than add jquery
function save() {
// ajax adding data to database
var formData = new FormData($('#form')[0]);
$.ajax({
URL: "<?php echo site_url('InputPembangunan/save')?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
success: function(data) {
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else {
//do something
}
},
error: function(jqXHR, textStatus, errorThrown) {
//do error form
}
});}
Use the following way,
$( "#saveEmpForm" ).submit(function( event ) {
event.preventDefault();
/** Your Existing Code ***/
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
/** Your Existing Code ***/
});
Also, you can check the jQuery reference from this link:
https://api.jquery.com/submit/#submit
Replace
$('#saveEmpForm').submit('click',function(){
with
$(document).off('submit','#saveEmpForm').on('submit','#saveEmpForm',function(event) {
event.preventDefault(); //to prevent default submit action
...rest of the code
})
also check for any errors on the browser dev tool
I try to submit form via ajax, below is the form.
<form class="form-vertical" method="POST" id="request-form" action="/post_handler?request=add_data" enctype="multipart/form-data">
<div class="form-group">
<label for="date_inp" class="control-label">Date</label>
<input class="form-control hasDatepicker" id="datepicker" type="text" name="date">
</div>
</div>
<div class="form-group">
<label for="file_inp">Upload File</label>
<div>
<input class="form-control" id="file_inp" type="file" placeholder="Upload File" name="file">
</div>
</div>
<div class="form-group">
<div>
<button type="submit" class="btn btn-default submit-button" onclick="on_click_form_submit(event);">Submit</button>
</div>
</div>
</form>
This is the click function.
on_click_form_submit = function(event) {
event.preventDefault();
var form_data = new FormData($('#request-form')[0]),
form_url = '/' + $('#request-form')[0].action.split('/').pop();
console.log('url: ' + form_url);
$.ajax({
url: form_url,
type: 'POST',
data: form_data,
dataType: 'json',
encode: true
})
.done(function(response) {
alert(response);
})
.fail(function(xhr, status, error) {
alert(xhr.responseText);
});
return false;
};
When I click submit, it reports
Uncaught TypeError: Illegal invocation
at add (jquery-1.9.1.js:7340)
at buildParams (jquery-1.9.1.js:7392)
at Function.jQuery.param (jquery-1.9.1.js:7360)
at Function.ajax (jquery-1.9.1.js:7863)
at Object.on_click_form_submit (spa.shell.js:301)
Per the docs, jQuery's $.ajax accepts:
Type: PlainObject or String or Array
So, your form_data should be in one of those formats - it should not be an instantiation of a FormData. It depends on what your backend is expecting, but one option would be to convert the form's values to an object with serializeArray():
on_click_form_submit = function(event) {
event.preventDefault();
var form_data = $('#request-form').serializeArray(),
form_url = '/' + $('#request-form')[0].action.split('/').pop();
console.log('url: ' + form_url);
$.ajax({
url: form_url,
type: 'POST',
data: form_data,
dataType: 'json',
encode: true
})
.done(function(response) {
alert(response);
})
.fail(function(xhr, status, error) {
alert(xhr.responseText);
});
return false;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-vertical" method="POST" id="request-form" action="/post_handler?request=add_data" enctype="multipart/form-data">
<div class="form-group">
<label for="date_inp" class="control-label">Date</label>
<input class="form-control hasDatepicker" id="datepicker" type="text" name="date">
</div>
</div>
<div class="form-group">
<label for="file_inp">Upload File</label>
<div>
<input class="form-control" id="file_inp" type="file" placeholder="Upload File" name="file">
</div>
</div>
<div class="form-group">
<div>
<button type="submit" class="btn btn-default submit-button" onclick="on_click_form_submit(event);">Submit</button>
</div>
</div>
</form>
I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!
My server generates a csrfToken, which is inserted into the following element:
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
The {{_csrfToken}}, is used for templating, but at run time is replaced at the server with the actual token.
<div class="formContainer">
<form class="form-horizontal signupform" role="form" action="/process?form=signupform" method="POST">
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
<div class="form-group">
<label for="fieldName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control"
id="fieldName" name="name">
</div>
</div>
<div class="form-group">
<label for="fieldEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" required id="fieldName" name="email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-default">Register</button>
</div>
</div>
</form>
</div>
{{#section 'jquery'}}
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
{{/section}}
How do I update my jQuery call to include the token ? Right now it is generating errors because the token is not included...
Try this, you did not post anything in fact. I did not test it, if it fails, maybe you should collect data manually.
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
+ var payload = $(this).serializeArray()
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
+ data: payload,
success: function(data){
if(data.success){ $container.html('<h2>Thank you</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
though it looks like it's a duplicate post still as far as answer is concerned this is how you should do check this SO post
and I am writing the code for you here
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer');
var token = $('input[name="_csrf"]').attr('value')
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', token);
}
});
$.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
I have a JSON returned data from a pho function that looks as follows:
[{"id":"15","activity_type":"call","activity_title":"Call to check "}]
Here the script that initiates the request (actvitiy.js)(Edited)
$(document).on("click", ".view_contact_activity", function () {
var this_activity_id = $(this).closest('.feeds').find('#this_activity_id').val();
$('#view-contact-activity').modal('show');
$.ajax({
url: '../includes/functions/contact-functions.php',
data: {view_activity_id:this_activity_id},
dataType:'json',
Success: function(response){
$('#activity_id').val(response[0].id);
$('#activity_type').val(response[0].activity_type);
}
});
});
The modal where i need the values to show:
<div class="modal fade" id="view-contact-activity" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<div class="portlet-body form">
<form class="form-horizontal" role="form" id="view-contact-activity-form" method="post">
<div class="form-group">
<label class="col-sm-3 control-label col-lg-3"> Activity Title</label>
<input type="text" name="activity_id" id="activity_id" value="">
<label class="col-sm-3 control-label col-lg-3"> Activity Type</label>
<input type="text" name="activity_type" id="activity_type" value="">
<div class="modal-footer">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" name="create-new-account" class="btn btn-danger" id="edit">Edit Activity</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
The modal shows but no data is passed into the modal. Any ideas what i might be doing wrong here.
EDIT: Adding PHP function that returns the JSON
function view_activity(){
global $connection;
$activity_id = $_POST['view_activity_id'];
$get = "SELECT * FROM contact_activities WHERE activity_id = '$activity_id' "
or die("Error: ".mysqli_error($connection));
$query = mysqli_query($connection, $get);
$activitiy_field = array();
while ($activity_array = mysqli_fetch_array($query)){
$activity = array(
'id' => $activity_array['activity_id'],
'activity_type' => $activity_array['activity_type'],
'activity_title'=>$activity_array['activity_title'],
'activity_details'=>$activity_array['activity_details'],
'activity_status'=>$activity_array['activity_status'],
'activity_details'=>$activity_array['activity_details'],
'activity_details'=>$activity_array['activity_details'],
);
$activitiy_field[] = $activity;
}
echo json_encode($activitiy_field);
}
if (isset($_POST['view_activity_id'])) {
view_activity();
}
Thank you.
Use .val() instead of .html().
$('#activity_id').val(response.id);
$('#activity_type').val(response.activity_type);
Modified: Your javascript should look like this:
$(document).on("click", ".view_contact_activity", function () {
var this_activity_id = $(this).closest('.feeds').find('#this_activity_id').val();
$('#view-contact-activity').modal('show');
$.ajax({
url: '../includes/functions/contact-functions.php',
data: {view_activity_id:this_activity_id},
dataType:'json',
Success: function(response){
$('#activity_id').val(response[0].id);
$('#activity_type').val(response[0].activity_type);
}
});
});
After digging on multiple sites. i found a similar question that could help.
$(document).on("click", ".view_contact_activity", function () {
var this_activity_id = $(this).closest('.feeds').find('.id #this_activity_id').val();
$('#view-contact-activity').modal('show')
$('#view-contact-activity').on('show.bs.modal', function() {
$modal = $(this);
$.ajax({
url: '../includes/functions/contact-functions.php',
data: {view_activity_id:this_activity_id},
dataType:'json',
success: function(response){
// Find the elements in the modal
$modal.find('#activity_id').val(response[0].id);
$modal.find('#activity_type').val(response[0].activity_type);
}
});
});
});