I want to make a simple CRUD using modal bootstrap and Jquery submit button and framework that i use is laravel 5.2, below is my controller, modal, jquery and routes, the problem is when i click save changes nothing happen, is there anything im doing wrong?
MODAL
<div class="modal fade" id="addModal" 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">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Add Barang</h3>
</div>
<div class="modal-body" id="addModal">
<form id="tambahform" class="form-horizontal" role="form">
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<input type="text" id="client-nama" name="clientName" class="form-control" placeholder="Your Name">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn-add btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
JQuery
$(document).ready(function(){
var check1=0;
$('#tambahform').submit(function(e){
if (check1==0){
$("#addModal").animate({scrollTop:0}, 'slow');
}else{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url:'form/insert',
data:formData,
type:'POST',
contentType: false,
processData: false,
success:function(data){
$("#addModal").hide();
window.location.reload(true);
}
});
}
return false;
});
Controller
public function insert(){
$nama = Input::get('nama');
$this->nama = Input::get('clientName');
$query = DB::table('profile')->insert(array('nama'=>$nama));
}
ROUTES
Route::get('form/insert', 'FormController#insert');
You need to define the method you will be using to submit the form as. There is no method mentioned so it is submitting its default, GET.
so you form tag should look like this:
<form method="POST" id="tambahform" class="form-horizontal" role="form">
In the url, you need to give it a full path or else it will give a 404 not found error. Take a look at this code:
e.preventDefault();
var formData = $(tambahform).serialize(); //<--use Serialize
$.ajax({
url:'form/insert.php', //<--add full path including the files extension here
data:formData,
type:'POST',
contentType: false,
processData: false,
success:function(data){
$("#addModal").hide();
window.location.reload(true);
}
Instead of this
Route::get('form/insert', 'FormController#insert');
use this
Route::post('form/insert', 'FormController#insert');
Related
I have problem regarding inserting my data in the database, so I have module where I need to insert the information of the song. So I just test the lower version of the laravel (5.0 Laravel Version) and Ajax for submitting the request to the backend. Now when I press the submit button it shows error of.
TokenMismatchException in VerifyCsrfToken.php line 46:
Error:
One thing is the token is sending to the backend
I will share to you guys my sample code that I already created. Please see the codes below.
Routes::
Route::post('/add_song','HomeController#add_song');
Front End::
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$(document).ready(function(){
$('.btn_add_music').on('click',function(e){
var song_title = $('#song_title').val();
var song_artist = $('#song_artist').val();
var song_lyrics = $('#song_lyrics').val();
var currentToken = $('meta[name="csrf-token"]').attr('content');
// var data = new FormData();
// data.append('song_title',song_title);
// data.append('song_artist',song_artist);
// data.append('song_lyrics',song_lyrics);
// data.append('currentToken',currentToken);
var formData = '_token=' + $('.token').val();
$.ajax({
url: '/add_song',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
success:function(res) {
console.log(res);
},
error:function(err) {
console.log(res);
}
// ... Other options like success and etc
})
});
});
Back End::
public function add_song(Request $request) {
dd($request->all());
$song_title = $request->get('song_title');
$song_artist = $request->get('song_artist');
$song_lyrics = $request->get('song_lyrics');
return response()->json('Success Inserted');
}
Html::
<div class="modal fade" id="ModalSong" 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">Ready to Add New Song?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<input type="hidden" class="token" name="_token" value="<?php echo csrf_token(); ?>">
<div class="col-md-6">
<div class="form-group">
<label for="title"><b>Title:</b></label>
<input type="text" class="form-control" id="song_title">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="artist"><b>Artist:</b></label>
<input type="text" class="form-control" id="song_artist">
</div>
</div>
</div>
<div class="form-group">
<label for="comment"><b>Lyrics:</b></label>
<textarea class="form-control" rows="5" id="song_lyrics"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-danger btn_add_music" type="button">Submit</button>
</div>
</form>
</div>
</div>
I believe you are sending your token wrong. That syntax seems off, but not my expertise area. Try the following instead.
var formdata= new FormData();
fd.append('_token', $('.token').val());
This is a little different from the method of submitting a form via static form value in modal. Using the same method is not working because AJAX not submitting the form value from the shown modal. So,
html
load form
modal
<div class="modal fade" id="xModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="xModalLabel">loading...</h4>
</div>
<div class="modal-body">...</div>
<div class="modal-footer">
<button type="button" class="btn btn-link waves-effect">SAVE CHANGES</button>
<button type="button" class="btn btn-link waves-effect" data-dismiss="modal">CLOSE</button>
</div>
</div>
</div>
</div>
jquery
//clear modal
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
//submit form
$('#xModal').on('shown.bs.modal',function (e) {
e.preventDefault();
var form=$(this).find('form').serialize();
$('#save_btn').on('click',function(){
$.ajax({
url:'inc/data.php',
type:'POST',
data:form,
success : function(data){
console.log(data);
}
});
});
});
data.php
<?
print_r($_POST);
?>
remote_form.html
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="xModalLabel">Reg Form</h4>
</div>
<div class="modal-body">
<form>
<input type="text" name="fname" /><br />
<input type="text" name="lname" /><br />
<input type="text" name="email" />
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link waves-effect" id="save_btn">SAVE</button>
</div>
</div>
Thanks, any comment is welcome!
Delegate your click event, move the event outside the on('shown.bs.modal') event
$(document).on('click', '#save_btn',function(){
var form=$(this).closest('form').serialize();
$.ajax({
url:'inc/data.php',
type:'POST',
data:form,
success : function(data){
console.log(data);
}
});
});
You can set ids to input fields and then getting data from that id as follows.
<input type="text" name="fname" id="fname"/>
and on the script do like this.
//submit form
$('#xModal').on('shown.bs.modal',function (e) {
e.preventDefault();
$('#save_btn').on('click',function(){
var fname = $("#fname");
$.ajax({
url:'inc/data.php',
type:'POST',
data:{
fname = fname
},
success : function(data){
console.log(data);
}
});
});
});
I have a problem in bootstrap modal. I want to add caption of an image using bootstrap model.
For the modal section I have done this,
<!-- Modal content Start-->
<form method="POST">
<!-- Modal -->
<div class="modal fade" id="myModal<?php echo $i;?>" role="dialog">
<input type="hidden" id="image_id" name="image_id" value="<?php echo $Array->image_id;?>" >
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Image Caption</h4>
</div>
<div class="modal-body">
<input type="text" id="caption" name="caption" placeholder="Caption" value="<?php echo $Array->image_caption;?>"/>
</div>
<div class="modal-footer">
<button class="btn btn-success" id="btn_caption">submit</button>
Close
</div>
</div>
</div>
</div>
</form>
<!-- Modal End Here -->
For the ajax part I have done this,
$(document).ready(function(e) {
$("button#btn_caption").click(function(){
var postData = $(this).serialize();
alert(postData);
$.ajax({
type: "POST",
url: "process.php",
data: postData,
success: function(msg){
//alert('successfully submitted')
},
error: function(){
alert("failure");
}
});
});
});
For the process.php file I put these lines,
<?php
include('require/admin_header.php');
if (isset($_POST['caption'])) {
$caption=strip_tags($_POST['caption']);
$image_id=strip_tags($_POST['image_id']);
echo '<pre>';
print_r($_POST);
// Data base update code
echo 'Update Done';
}?>
Now, the problem is the database is not updating with the value. <?php echo $Array->image_caption;?> it print the value from the database in the modal. But when I do this alert(postData);, it alert nothing. Can any one help me that where I am making the mistake?
Thanks in advance for help.
Replace
var postData = $(this).serialize();
with
var postData = $("#form_id").serialize();
<form method="POST" id="form_id">
</form>
I solve the question like this way,
This is the modal part,
<!-- Modal content Start-->
<form id="contactForm1" action="process.php">
<!-- Modal -->
<div class="modal fade" id="myModal<?php echo $i;?>" role="dialog">
<input type="hidden" id="image_id" name="image_id" value="<?php echo $Array->image_id;?>" >
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Image Caption</h4>
</div>
<div class="modal-body">
<input type="text" id="caption" name="caption" placeholder="Caption" value="<?php echo $Array->image_caption;?>"/>
</div>
<div class="modal-footer">
<button class="btn btn-success" id="btn_caption">submit</button>
Close
</div>
</div>
</div>
</div>
</form>
<!-- Modal End Here -->
This is the ajax part,
<script>
// Attach a submit handler to the form
$( "#contactForm1" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
id = $form.find( "input[name='image_id']" ).val(),
caption1 = $form.find( "input[name='caption']" ).val(),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( url, { image_id: id, caption: caption1} );
// Put the results in a div
posting.done(function( data ) {});
});
</script>
And the PHP part is like this,
<?php include('require/admin_header.php');
if (isset($_REQUEST['caption'])) {
$caption=$_REQUEST['caption'];
$image_id=$_REQUEST['image_id'];
// Update SQL
echo 'Update Done';
}?>
Thanks for those who interest to solve the question. Thanks once again.
You can use this code, in your ajax code:
var postData = new FormData($("#form_id")[0]);
and in your open form tag, you must add enctype="multipart/form-data" to upload image.
<form method="POST" enctype="multipart/form-data" id="form_id">
<input></input>
</form>
Am trying to submit data using modal bootstrap but i can't get it to work. The page will contain more than one modal to enable user to easily update their details.Here the code.
<div class="modal fade" id="overview-modal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Overview</h4>
</div>
<form id="overview_form" action="neuro/update_profile.php" class="form-horizontal" >
<div class="modal-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Overview</label>
<div class="col-sm-10">
<textarea class="form-control" id="overview_input" cols="20" rows="10" name="overview_textarea">
</textarea>
<input type="hidden" name="url"/>
</div>
</div>
<div class="form-group">
</div>
</div>
<div class="modal-footer">
<div class="btn-group">
<input type="submit" id="save" class="btn btn-success" value="Save"/>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
This is the javascript that will handle the form submission to the php file
<script>
$(document).ready(function () {
$("#save").submit(function () {
var formData = $("form#overview_form").serialize();
var my_url = "neuro/update_profile.php";
$.ajax({
type: "POST",
url: my_url,
data: formData ,
success: function (msg) {
$("#overview-modal").modal('hide');
},
error: function () {
alert("Error encounted");
}
});
return false;
});
});
</script>
The php is in a folder called neoro/update_profile ,since i will be using more than one modal in the profile page i have decided to append a url on the form attributes so that it can be easily processed in the php
$profile = new Profile();
$url = $_POST['url'];
if (isset($url)) {
if ($id == "overview") {
$overview = $_POST['overview'];
$profile->save_overview($user_id, $overview);
return TRUE;
}
} else {
header("Location: ./profile.php");
}
This is full of errors
You are sending the form via GET method and accessing it via POST method
Your URL field is empty
you are using action field and also submit simultaneously
your jquery code is not correct
you are using $id variable in your php code which is undefined
Corrected code:
<form id="overview_form" class="form-horizontal" method="post">
<input type="hidden" name="url" value='yoururl'/>
Do this:
$('#overview_form').submit(// your code here);
Instead of on #save, since you are submitting form not button 😉
Or
Even you can achieve same thing on #save but with click function as below
$('#save').click( // here your code );
I have been trying to get this form to load for a couple days now, but all I can get is the form to submit to a page (not what I want, I want the form to submit and then close the modal and then put a success message from news.php into the div "thanks" holder).
Can anyone spot the issue I am having where it will one load the "news.php" page?
<div id="thanks"></div>
<div class="modal fade" id="newsModal" tabindex="-1" role="dialog" aria-labelledby="newsModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="newsModalLabel">Add a News Post</h4>
</div>
<div class="modal-body">
<form class="addNew" role="form" method="POST" action="news.php">
<div class="form-group">
<input type="text" name="title" class="form-control" id="title" placeholder="Enter title here...">
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="7" placeholder="Enter news post here..."></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="addNews">Add News Post</button>
</form>
</div>
</div>
</div>
</div>
and the javascript is:
<script type="text/javascript">
$(document).ready(function () {
$("button#addNews").click(function(){
$.ajax({
type: "POST",
url: "news.php",
data: $('form.addNew').serialize(),
success: function(msg){
$("#thanks").html(msg) //hide button and show thank you
$("#newsModal").modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
</script>
You didn't pass the event object to your click binding :
<script type="text/javascript">
$(document).ready(function (e) { // pass the event object
$("button#addNews").click(function(){
e.preventDefault(); // disable the POST of the form by the submit button
$.ajax({
type: "POST",
url: "news.php",
data: $('form.addNew').serialize(),
success: function(msg){
$("#thanks").html(msg) //hide button and show thank you
$("#newsModal").modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
Oops, I forgot the BootPly of my test.
I just replaced your POST request to a GET one, I don't know how to make POST request inside BootPly.
button#addNews is the submit button for the form, also it's click event is binded with an ajax call. When it is clicked, ajax process begins to execute while the form is being submitted.
You need to remove <form... start & end tags.