Confirmation Message not working Using Ajax Codeigniter - javascript

I am fetching data from database using ajax in codeigniter and now i am trying to put "delete confirmation box"
in controller but that button is not working,
Here is controller file/code
$user['result']=$this->crud->AddMember($data);
foreach($user['result'] as $row) {
echo "<td>";
<input type="hidden" name="id" value="'.$id.'">
<input type="submit" class="btn btn-danger btn-sm" value="Delete" name="delete" onclick="return confirm('Are you sure you want to delete this item')">
</form>';
echo "</td>";
}
Here is view file
<form method="post" name="myForm" class="form-horizontal" id="user_form" enctype="multipart/form-data">
<input type="text" class="form-control" id="FlatNumber" name="FlatNumber" placeholder="">
<button type="submit" class="btn btn-primary btn-lg" id="butsave">Add Details</button>
</form>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
event.preventDefault();
var FlatNumber = $('#FlatNumber').val();
if(FlatNumber == '') {
alert("Please enter Flat Number");
}else{
$.ajax({
url:"<?php echo base_url() . 'index.php/Member/AddRecord'?>",
type: "POST",
data: {FlatNumber : FlatNumber},
dataType: "html",
success: function(msg){
alert(msg);
if (msg == 'exist') {
$("#successs").hide();
}else{
$("#errorr").hide();
}
}
});
}
});
});
</script>

It is because onclick works only for elements who already on this page. after ajax response it will not work so you need to use code like this.
$(document).on("click",".btn-danger", function(){
});

Related

How to serialize form data by number in javascript and submit with a specific number

I'm working on a personal project, where I've more forms than one (comment forms under each post). Each form I give a number according to post id.
<form id="postCommentsForm<?php echo $ansRow['id'];?>" class="form">
<div class="input-group mb-3">
<a href="user/<?php echo $username;?>">
<img class="p-1 m-0" src="images/<?php echo $userAvatar;?>" width="35" height="35" alt="<?php echo $userAvatar;?> profile picture">
</a>
<input name="post_comment<?php echo $ansRow['id'];?>" id="add_comments" type="text" autofocus autocomplete="off" class="add_comments form-control pl-3 pr-3" placeholder="<?php echo $userFname;?>, type something" aria-label="Recipient's username" aria-describedby="button-form">
<input type="text" hidden id="question_id" name="question_id" value="<?php echo $row['id'];?>">
<input type="text" hidden id="answer_id" name="answer_id" value="<?php echo $ansRow['id'];?>">
<input type="text" hidden id="session_id" name="session_id" value="<?php echo $_SESSION['id'];?>">
<div class="input-group-append">
<button class="btn btn-secondary submit-comments" type="submit" name="submit_comment<?php echo $ansRow['id'];?>" id="postComments">Comment</button>
</div>
</div>
</form>
javascript code
$(document).ready(function() {
$("[id^=postCommentsForm]").on("submit", function(e) {
e.preventDefault();
var add_comments = $("#add_comments").val();
var question_id = $("#question_id").val();
var answer_id = $("#answer_id").val();
// var session_id = $("#session_id").val();
if(add_comments == "" ){
$("#error-message").html("All fields are required!").slideDown();
$("#success-message").slideUp();
}else{
//Ajax
$.ajax({
url: "include/forms-data/comments.php",
type: "POST",
data: {
add_comments: add_comments,
question_id: question_id,
answer_id: answer_id
},
success: function(data) {
if (data != 0) {
$("[id^=postCommentsForm").trigger("reset");
$("#success-message").html("Question Added Successfully!").slideDown();
$("#error-message").slideUp();
} else {
//alert("Can't save record");
$("#error-message").html("Something went wrong!").slideDown();
$("#success-message").slideUp();
}
}
});
}
});
});
How I can fetch #comments(postID here), and submit form data successfully under the postID?
I hope I define well the question.
Jquery's "starts with selector" can help. check out here
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
var element_id = this.getAttribute("id");
});
});
Live Demo:
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
console.log($(this).attr('id'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='comments1'>b</button>
<button id='comments2'>a</button>

Laravel dynamic form input text and upload file

I have a problem when I add input type="file" to the dynamic form insert
all works before I tried to add input type="file"
also, I got no error message on the browser
addMore.blade.php
<form name="add_name" id="add_name" enctype="multipart/form-data">
<input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" />
<input type="file" name="proposal[]" id="proposal" class="form-control name_list" />
<button type="button" name="add" id="add" class="btn btn-success">Add More</button> //add dynamically input
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
here the ajax
$('#submit').click(function(){
$.ajax({
url:postURL,
method:"POST",
data:$('#add_name').serialize(),
type:'json',
success:function(data)
{
if(data.error){
printErrorMsg(data.error);
}else{
i=1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display','block');
$(".print-error-msg").css('display','none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
// location.href = "http://www.example.com/ThankYou.html"
}
}
});
});
//note the dynamic add input filed button already works #add
//already tried remove serialize() still not work
//also i got no error message on the browser
here the HomeController.php
public function addMorePost(Request $request){
$name = $request->name;
$proposal = $request->file('proposal')->store('proposals'); //already change to ->file(proposal[]) not work
for ($count = 0; $count < count($name); $count++) {
$data = array(
'name' => $name[$count],
'proposal' => $proposal[$count] //already change 'proposal[]' but not work
);
TagList::create($data);
}
return response()->json(['success' => 'done']);
}
you are using serialize while sending data via ajax, you need to pass FormData with ajax.
Below is a complete code for sending file with ajax, and also you can trigger event when form is submitted so you can get entire formdata:
<form name="add_name" id="add_name" enctype="multipart/form-data" action="home" method="post">
#csrf
<input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" />
<input type="file" name="proposal[]" id="proposal" class="form-control name_list" />
<button type="button" name="add" id="add" class="btn btn-success">Add More</button>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$('#add_name').submit(function(e) {
e.preventDefault();
var form = $(this);
var formData = new FormData(this);
$.ajax({
url: form.attr('action'),
method: "POST",
data: formData,
type: 'json',
processData: false,
contentType: false,
success: function(data) {
if (data.error) {
printErrorMsg(data.error);
} else {
i = 1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display', 'block');
$(".print-error-msg").css('display', 'none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
// location.href = "http://www.example.com/ThankYou.html"
}
}
});
return false;
});
</script>
HomeController.php
public function addMorePost(Request $request){
$name = $request->name;
$proposal = $request->file('proposal');
foreach ($proposal as $file) {
$file->store('proposals');
}
for ($count = 0; $count < count($name); $count++) {
$data = array(
'name' => $name[$count],
'proposal' => $proposal[$count] //already change 'proposal[]' but not work
);
TagList::create($data);
}
return response()->json(['success' => 'done']);
}

Inserting through AJAX page is refreshing [duplicate]

This question already has answers here:
insert query with ajax without reloading whole page
(2 answers)
Closed 4 years ago.
Inserting the data through AJAX it's working but pages refreshing, why is that give a feedback to fix this issues.
This is my ajax code
<script>
$(document).ready(function(){
$("#button").click(function(){
var postId=$("#postId").val();
var userId=$("#userId").val();
var postComm=$("#postComments").val();
$.ajax({
url:'../validate/inserPostComm.php',
method:'POST',
data:{
poId:postId,
usId:userId,
poco:postComm
},
success:function(data){
//alert(data);
}
});
});
});
</script>
Here I'm using HTML
<form>
<input type="hidden" id="postId" name="postId" value="<?php echo $_GET["postId"]; ?>">
<input type="hidden" id="userId" name="userId" value="<?php echo $_SESSION["u_id"]; ?>">
<textarea placeholder="Post your comment" id="postComments"></textarea>
<button type="submit" id="button"><i class="fa fa-paper-plane"></i></button>
</form>
You are facing it due to the button having input type “Submit”
<button type="submit" id="button"><i class="fa fa-paper-plane"></i></button>
Just change it to normal “button”
<button type="button " id="button"><i class="fa fa-paper-plane"></i></button>
Easy fix: Add a preventDefault(). Notice the 'e' I added to your click function.
<script>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault();
var postId=$("#postId").val();
var userId=$("#userId").val();
var postComm=$("#postComments").val();
$.ajax({
url:'../validate/inserPostComm.php',
method:'POST',
data:{
poId:postId,
usId:userId,
poco:postComm
},
success:function(data){
//alert(data);
}
});
});
});
</script>
You can prevent the default submit button behavior - submitting the form - with event.preventDefault();
<script>
$(document).ready(function(){
$("#button").click(function(event){
// prevent the default submit button behaviour
event.preventDefault();
var postId=$("#postId").val();
var userId=$("#userId").val();
var postComm=$("#postComments").val();
$.ajax({
url:'../validate/inserPostComm.php',
method:'POST',
data:{
poId:postId,
usId:userId,
poco:postComm
},
success:function(data){
//alert(data);
}
});
});
});
</script>
another ajax i'm using but some issue is coming page is refreshing.
<script>
function inspire(x){
var insPer =$("#insPer"+x).val();
var insPos =$("#insPos"+x).val();
$.ajax({
url:'../validate/inspire.php',
method:'POST',
data:{
u_id:insPer,
p_id:insPos
},
success:function(data){
//alert(data);
}
});
}
</script>
this is html code
<input type="hidden" id="insPer<?php echo $p_id; ?>" name="insPer" value="<?php echo $_SESSION["u_id"]; ?>">
<input type="hidden" id="insPos<?php echo $p_id; ?>" name="insPos" value="<?php echo $p_id; ?>">
<a href="#" onclick="inspire(<?php echo $p_id; ?>);">
Better do this
$(document).ready(function(){
$("form#comment").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
// console.log(formData);
$.ajax({
url: '../validate/inserPostComm.php',
type: 'POST',
data: formData, //The Form data contain array (postId,userId,postComments)
success: function (data) {
// do something if success
},
error: function(xhr, ajaxOptions, thrownError) {
//If error thrown here
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="comment" method="post" enctype="multipart/form-data">
<input type="hidden" id="postId" name="postId" value="...">
<input type="hidden" id="userId" name="userId" value="...">
<textarea placeholder="Post your comment" id="postComments" name="postComments"></textarea>
<button type="submit" id="button"><i class="fa fa-paper-plane"></i></button>
</form>

Update data using AJAX and codeigniter failed

I want to update my data using Codeigniter and AJAX for submit response..
This is my View
<form id="form_update" action="<?php echo base_url() ?>admin/update_derap_info" method="POST" role="form">
<textarea cols="80" id="editor1" name="isi" rows="10" class="form-control" >
</textarea>
<input type="submit" value="Simpan" class="btn btn-sm btn-primary" name="update_info_pemesanan">
</form>
My Controller
$data = array
(
'isi'=> ltrim(rtrim($this->input->post('isi')))
);
$this->info_derap->update($this->input->post('id_info'),$data);
echo'<div class="alert alert-success">Terimakasih, pesan anda sudah kami terima. Pemberitahuan selanjutnya kami beritahunak lewat email.</div>';
exit;
My Model
function update($id,$data){
$this->db->where($this->id, $id);
$this->db->update($this->table, $data);
}
And here is my AJAX
<script type="text/javascript">
$("#form_update").submit(function (e){
e.preventDefault();
$("#loader").show();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url:url,
type:'POST',
data:$("#form_update").serialize(),
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
});
</script>
I can update My data if I press click submit 2 times, but when I submit just 1 time , it cannot update.
What's wrong?
You cant update with form. Use this
<form action="" method="" role="form">
<textarea cols="80" id="editor1" name="isi" rows="10" class="form-control" ></textarea>
<input type="submit" value="Simpan" class="btn btn-sm btn-primary" name="update_info_pemesanan" id="form_update">
</form>
in AJAX
<script type="text/javascript">
$(function(){
$("#form_update").click(function(event){
event.preventDefault();
$("#loader").show();
var editor1= $("#editor1").val();
$.ajax(
{
type:'post',
url:"<?php echo base_url() ?>admin/update_derap_info",
data:{editor1:editor1},
success:function($data)
{
$("#response").html(data);
$("#loader").hide();
fillgrid();
}
});
});
});
</script>
in Controller
$text_area = $this->input->post('editor1')
So in $text_area Contain text which you input in your form
You should use the following code on your controller:
$this->info_derap->update($this->input->post('id_info'),$data);
Also, make sure there's a field called id_info in the corresponding view.
what a message if you using debug, you can inspect request...
you can insert or adding some javascript function "espace" your request form for example
escape($("editor1").val());

Submit form via Enter key and Submit button both

Hi I have form and following things are bothering me:
1. Form does not submit on pressing enter.
2. When i press enter in input field then Search Now button needs to be pressed
twice to search places.
Form is displayed as below:
<form method="POST" id="mylocform" action="">
<h3 class="animated slideInLeft delay-2">
<input type="text" placeholder="Start Typing Your Location" id="geocomplete"
style="color:black;width:100%;padding:5px;height:45px;border-radius:5px"
autocomplete="off" class="chkmeloc" onblur="checkmylocform()"/></h3>
<input type="submit" class="btn btn-default btn-lg animated fadeInUpBig delay-3"
style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>
</form>
Validation goes like below:
$(document).ready(function(){
$("form#mylocform").submit(function(event) {
event.preventDefault();
validate();
});
});
function checkmylocform(){
var checkOdlen = $(".chkmeloc").val().length;
if(checkOdlen==0){
$(".chkmeloc").css("border-color","#F05F68");
$(".chkmeloc").focus();
$(".chkmelocmess").html('<button type="submit" class="btn btn-default
btn-lg" style="background: #FFF;color:red">
<i class="fa fa-warning text-red"></i>
Select Your Location</button>');
return false;
}
else{
$(".chkmeloc").css("border-color","#0C9");
$(".chkmelocmess").html('<input type="submit" class="btn btn-default
btn-lg" style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>');
return true;
}
}
function validate(){
$.each($('form :input'),function(){
$(this).blur().change();
});
if(!checkmylocform()){
return false;
}
else{
submitform();
}
}
Submit Form has code to submit form via ajax as below. Please help me to get out of this situation.
$("Your selector").keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$(input[type = submit]).click();
return false;
}
});
look at this site:
http://tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
the site says that enter key is automaticly a submit in al browser
Try This
File index.html :
<form class="form-inline" action="" method="POST">
<input type="password" name="token" placeholder="Enter Facebook access token..." class="subscribe-email">
<button type="submit" class="btn">Start!</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
File script.js :
$('.get_token form').submit(function(e) {
e.preventDefault();
var postdata = $('.get_token form').serialize();
$.ajax({
type: 'POST',
url: 'assets/submit_token.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else {
$('.error-message').hide();
$('.success-message').hide();
$('.get_token form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
});

Categories

Resources