submission of bootstrap form with dynamic form ids - php

I am listing user's records along with edit link, upon clicking on edit link bootstrap modal form loads
My Page has following code (not sure if there is any better way to create modal dynamically)
after changes when user submits modal form, modal will disappeared and update message will be shown on users.php page
but my alert box shows same form id for every modal's submit button i click (i.e. the first modal's form id) and shows blank datastring (form seriralize)
I want to pass respective form's data to process.php
below is part of my users.php
<?php whlie($row=mysql_fetch_array($result)){?>
<div id="editkey" class="modal hide fade" style="display: none; ">
<div class="modal-header">
<a class="close" data-dismiss="modal">X</a>
<h3>Edit users Details</h3>
</div>
<div>
<form id="keyfrm<?=$row['id'];?>">
<fieldset>
<input type="hidden" name="keyid" value="<?=$row['id'];?>">
<div class="modal-body">
<ul class="nav nav-list">
<li class="nav-header text-left"><p>Name :</p></li>
<li class="nav-header text-left"><p><input type="text" name="name"></p></li>
</ul>
</div>
<fieldset>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-success" id="submit">submit</button>
Close
</div>
I have js file that contains
$(document).ready(function(){
$('#submit').click(function() {
var formID = $('form').attr('id');
alert(formID);
var datastring = $(this).closest('form').serialize(); // may be working
alert(datastring);
$.ajax({
type: 'POST',
url: 'update_user.php',
data: datastring ,
success: function(msg) {
alert(msg);
var data=msg.split('|');
$(data[0]).modal('hide');
$('#result').html('');
$('#result').fadeOut("slow");
if(data[1]==='Success'){
$('#result').css('background-color','#DDF9B3');
$('#result').text("Data is updating...please wait for changes to take effect");
window.setTimeout(function(){location.reload()},3000)
}else{
$('#result').css('background-color','#FE9898');
$('#result').text("Error Occured");}
//$('#result').html(msg);
$('#result').fadeIn("slow");
$("#result").delay(4200).fadeOut(800);
}
});
event.preventDefault();
});
});
any help will be appreciated

Get the formID same way you get the data:
var formID = $(this).closest('form').attr('id');
alert(formID);
var datastring = $(this).closest('form').serialize();

Related

Simple addition within php action on ajax posted variables prior to submitting to database (Data type issues as data is coming back from ajax call)

I'm new to ajax and hoping someone can help figure out how to add two form inputs. I have a hidden input that is getting the total sheets from a database. I also have an addSheets input that is getting the total of sheets to add. I'm posting code from my modal as well as the ajax and action. Any advice is greatly appreciated.
(index)
<html>
<body>
<div class="modal fade" id="addSheetsModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add Paper</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body px-4">
<form action="" method="post" id="form-addSheets-data">
<input type="hidden" name="id" id="id">
<input type="hidden" name="sheets" id="sheets">
<div class="form-group">
<input type="text" name="addSheets" class="form-control" id="addSheets" placeholder="">
</div>
<div class="form-group">
<input type="submit" name="addSheetQty" id="addSheetQty" value="Add Paper" class="btn btn-success btn-block">
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<script language="javascript" type="text/javascript">
// AJAX Edit Paper - Receive (Gets ID)
$("body").on("click", ".receiveBtn", function(e){
e.preventDefault();
r_edit_id = $(this).attr('id');
$.ajax({
url:"action.php",
type:"POST",
data:{r_edit_id:r_edit_id},
success:function(response){
data = JSON.parse(response);
console.log(data);
$("#id").val(data.id);
$("#sheets").val(data.sheets);
}
});
});
// Edit Paper - Update (Sums)
$("#addSheetQty").click(function(e){
if($("#form-addSheets-data")[0].checkValidity()){
e.preventDefault();
$.ajax({
url:"action.php",
type:"POST",
data: $("#form-addSheets-data").serialize()+"&action=addSheetQty",
success:function(response){
console.log(response);
Swal.fire({
title: 'Sheets added successfully!',
icon: 'success',
showConfirmButton: false,
timer: 1500
})
$("#addSheetsModal").modal('hide');
$("#form-addSheets-data")[0].reset();
showAllPapers();
}
});
}
});
</script>
<?php
// ACTION
if(isset($_POST['r_edit_id'])){
$id = $_POST['r_edit_id'];
$row = $db->getPaperById($id);
echo json_encode($row);
}
if(isset($_POST['action']) && $_POST['action'] == "addSheetQty"){
$id = $_POST['id'];
$sheets = $_POST['sheets'] + $_POST['addSheets'];
$db->updateSheetQty($id,$sheets);
}
?>
In the database the sheets column is varchar(255). In the php_error.log I'm getting this response: PHP Warning: A non-numeric value encountered in /Applications/MAMP/htdocs/PaperInventory/action.php on line 116 which is this line ($sheets = $_POST['sheets'] + $_POST['addSheets'];) in my code above.
Thanks for any input and help understanding this.

Ajax called page with button not triggering modal window with form variable

I have this following Ajax call which is trying to get some data in certain intervals
$(document).ready(function() {
x();
function x() {
var FD = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "qaVtagAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
$("#inputFieldDisplay").html(result);
}
});
return false;
}
setInterval(x, 5000);
});
$("#assignQaOa").click(function() {
// trigger modal
});
Content of the Ajax call page qaVtagAjax.php as below
echo '<form method="post"> <div class="card" style="position: relative; border-color: black; !important ">
<div class="card-body">
<div class="row">
<input type="text" name= "srNum" id="srNum" value = "someValue" hidden>
<div class="col-sm"><button class="btn-primary modalButton" type="submit" name = "assignQaOa" id = "assignQaOa" title="Click to assign to some operator">Assign</button></div>
</div>
</div>
</div>
</form>
<br>';
As you can see there is a button in the form called assignQaOa. I want to trigger a modal window by clicking this button as show earlier
$("#assignQaOa").click(function() {
//trigger modal by doing Eg: $('#myModal').modal('show');
alert("Modal window showing");
});
As a first step, I tried to alert some message. But nothing is happening when I click the button. Does anyone have some idea why this way?
NB: Actual qaVtagAjax.php file has more html and php contents. Those are working correctly. So I simplified that codes for understanding the problem.
Edit 1
Following is the modal codes that I am using from bootstrap
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" 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="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<input type="text" id="tagSerial" name="tagSerial" hidden>
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Also I edited the button click code as below based on the suggestion. This time if I gave a simple alert, it is working. But modal is not showing
$(document).on("click", "#assignQaOa", function() {
//Alert is working. Eg: alert("some message");
$('#exampleModalCenter').modal('show'); //This is not working
});
Edit 2
Some post suggested the possibility that two time bootstrap.js was typed in the document. But for my case, it is not the case too. I only typed it once and I am using as below
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
Does anyone know why this happening? As I mentioned in comments, if I removed the class fade from modal, then modal will show for a split second with this $('#exampleModalCenter').modal('show'); code
Edit 3
By doing e.preventDefault(), I am able to stop the form submission and show modal successfully. But now I have an element in the modal window that supposed to get some $_POST values from form submission. How can I get that $_POST value in the modal at this situation? My Javascript code as below
$(document).on("click", "#assignQaOa", function(e) {
$('#exampleModalCenter').modal('show');
$('#tagSerial').val($("#srNum").val());
e.preventDefault();
});
The following is the element in the modal window
<input type="text" id="tagSerial">
After many trial and errors, I found issue was due to I am using type = submit for the button. When I changed type = button, modal triggered and showed correctly. But I am still puzzled why when I used type = submit and removed the class fade, modal showing for a split second. Probably there is a work around to show it correctly too. I hope some expert from stack overflow can find out and tell me the problem.
Anyway I still couldn't use this type = button for my scenario due to I need to get the values from a form submission when this button clicked. If use type = button, I cannot submit and get the values of the form through a $_POST method.
Edit 1
After got help from stack overflow member #Swati, realized that submit will refresh the page and that is why when used submit, modal is showing only for a split second. With her help I modified the code as below and able to solve my problem
$(document).on("click", "#assignQaOa", function(e) {
$('#exampleModalCenter').modal('show');
var sr = $(this).closest(".card-body").find("input[name='srNum']").val();
$('#tagSerial').val(sr);
e.preventDefault();
});
The above code will stop form submission. Also it will grab the input field srNum value and show it in the modal even without submitting form.

Codeigniter insert to database via ajax from model

I currently have a page with a single form element. Upon entering a value into the text box, a modal window pops up showing the value you have entered.Upon clicking confirm the value is then entered into the database. This is working fine but I'm looking to have another modal window popup when the insert is successful but I am struggling with it.
I'm thinking of going down the route of submitting the form via ajax and then showing the confirmation modal but I can't seem to get it working. I'm not sure if its the fact that I'm using two modal windows or what it is really.
<form action="<?php echo base_url()."index.php/create/createHospital"; ?>" method = "post" name = "form1" id ="form1" >
<div class="hospital_container">
<h3 class = "hospital_header"><b>Enter Hospital Information</b></h3>
<label for="hospitalName" class = "labelForm">Name:</label>
<input type="text" class = "input2" id="hospitalName" name="hospitalName" class = "newUserForm">
<button type="button" id = "hospital_submit_button" class = "hospital_submit_button" data-toggle="modal" data-target="#userModal">Add New Hospital</button>
</div>
</form>
<!-- MODAL -->
<div id="userModal" class="modal fade" role="dialog">
<h3 class="modal-title_user">Create New Hospital?</h3>
<div class="modal-body">
<h4 id = "h4modal_user_hosp"> Hospital Information</h4>
<div id ="modal_hosp_container">
<br> <label class = "modallabeluser"> Hospital:</label> <p class = "modaluser" id = "hospital1" name = "hospital1"></p>
</div>
<button type="submit" id = "overlaysubclass2"> Yes,Complete</button>
<button id = "editoverlay" data-dismiss="modal"> No,Edit Info</button>
</div>
</div>
When confirming the value in the modal window I am using:
$('#hospital_submit_button').click(function() {
var hospitalName = $('#hospitalName').val();
$('#hospital1').text(hospitalName);
});
$('#overlaysubclass2').click(function(){
document.form1.submit();
});
This was the ajax call I have at the moment but I'm unsure how to tie it in with the rest of the code?
$(function() {
$("#form1").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "<?php echo base_url()."index.php/create/createHospital"; ?>",
type: "post",
data: $(this).serialize(),
success: function(d) {
alert(d);
}
});
});
});
Alternatively, does anyone have an idea of how to achieve the modal another way?
Thanks in advance
Model
function create_hospital($data){
$theData = array(
'hospitalName' => $this->input->post('hospitalName'),
);
$insert = $this->db->insert('hospitals', $theData);
return $insert;
}
Controller
function createHospital()
{
// $hospital=$this->input->post('hospitalName');
// echo $hospital;
$theData = array(
'hospitalName' => $this->input->post('hospitalName'),
);
$this->user_model->create_hospital($theData);
//$data['message'] = 'Data Inserted Successfully';
redirect('Admin/add_hospitals');
}
MODAL I WANT TO POPUP ON SUCCESSFULL INSERT TO DB
<h3 class="modal-title_user">Confirm?</h3>
<div class="modal-body">
<h4 id = "h4modal_user_hosp"> Hospital Information</h4>
<div id ="modal_hosp_container">
<p> confirmed</p>
</div>
<input type = "submit" name="submit" value = "Yes,Confirm" id = "confirmbutton">
<input type = "submit" name="submit" value = "No,Edit Info" id = "editoverlay" data-dismiss="modal">
</div>
</div>
Would it not be a case of using:
success: function(data) {
// alert("success");
$("#confirmModal").modal("show");
}
Modify Html as
<form id ="form1" >
<div class="hospital_container">
<h3 class = "hospital_header"><b>Enter Hospital Information</b></h3>
<label for="hospitalName" class = "labelForm">Name:</label>
<input type="text" class = "input2" id="hospitalName" name="hospitalName" class = "newUserForm">
<button type="button" id = "hospital_submit_button" class = "hospital_submit_button" data-toggle="modal" data-target="#userModal">Add New Hospital</button>
</div>
</form>
<!-- MODAL -->
<div id="userModal" class="modal fade" role="dialog">
<h3 class="modal-title_user">Create New Hospital?</h3>
<div class="modal-body">
<h4 id = "h4modal_user_hosp"> Hospital Information</h4>
<div id ="modal_hosp_container">
<br> <label class = "modallabeluser"> Hospital:</label> <p class = "modaluser" id = "hospital1" name = "hospital1"></p>
</div>
<button type="button" id = "overlaysubclass2"> Yes,Complete</button>
<button id = "editoverlay" data-dismiss="modal"> No,Edit Info</button>
</div>
</div>
Now use jquery Ajax as
<script type="text/javascript">
$(function() {
$("#hospital_submit_button").on("click", function(event) {
event.preventDefault();
var DataString=$("#form1").serialize()
$.ajax({
url: "<?php echo base_url(); ?>index.php/create/createHospital",
type: "post",
data:DataString ,
success: function(data) {
alert(data);
}
});
});
});
</script>
Now You have to print value from controller method as
function createHospital(){
$hospital_name=$this->input->post('hospitalName');
$theData = array(
'hospitalName' => $hospital_name
);
$hospital_id= $this->user_model->create_hospital($theData);
if($hospital_id>0){
echo $hospital_id;
}
}
Model as follow
function create_hospital($data){
$this->db->insert('hospitals',$data);
return $this->db->insert_id();
}
Then you will get ajax success (alert) as your last inserted Id what you will pass to the input field then click on the submit button .
Hope it will work.
Thank you!

Using ajax to pass a jquery string to php

I have been working this for a while and have found numerous clues here on SO, but nothing is working yet. I'm trying to create a dynamic drop down in a form that the user can add to by selecting an "add new" option which brings up a modal window in which the new option can be typed. I use jquery to bring up the window and capture the input and ajax to (hopefully) post the text and retrieve it in php. I see on the console that that the new option is captured in the javascript and ajax makes a post, but the post array is empty.
My code is all in the view. When an "add new" is selected a modal window pops up in which text can be entered. I want to capture the entered text in the view without submitting and display it in the updated options list.
<legend>Animal Info</legend>
<div class="control-group <?php if (form_error('animal_species')) { echo 'error'; } ?>">
<label class="control-label">Species</label>
<div class="controls">
<?php # Add "Add New"
$options = $species + array('addnew' => 'Add New');
echo form_dropdown('animal_species', $options,
set_value('animal_species', (isset($my_data->animal_species)) ? $my_data->animal_species: ''),
'id = "animal_species"',
'class', 'addnew');
echo form_error('animal_species', '<span class="help-inline">', '</span>');
?>
</div>
</div>
<?php
if(isset($new_option))
{
$new_option = $_POST['new_option'];
$species = array($new_option => $new_option) + $species;
var_dump($new_option);
}
?>
<script type="text/javascript">
$('#upload_form option[value="addnew"]').click(function(){
// Show modal window
$('#add-new').modal('show');
$('#add-new-submit').on('click', function(){
// Get new option from text field
var new_option = $('#add-new-text').val();
console.log(new_option);
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/upload_page",
data: {new_option:'new_option'}
}).fail(function (jqXHR, textStatus, errorThrown){
console.error("The following error occured: " + textStatus, errorThrown);
});
$('#add-new').modal('toggle');
});
//});
});
</script>
<!-- add-new field -->
<div class="modal small hide fade" id="add-new" tabindex="-1" role="dialog" aria-labelledby="add-new-fieldLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="add-new-fieldLabel">Add New Field</h3>
</div>
<div class="modal-body">
<p>Would you like to add a new item?</p>
<input type="text" id="add-new-text" name="add-new" placeholder="Type the new option">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="add-new-submit" name="add-new-submit"/>Add</button>
</div>
</div><!-- /add-new field -->
Right now the string new_options gets captured in the console but is NULL in the php, so ajax isn't posting for some reason. Is this because I'm trying to update the same page?
Change it to :
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/upload_page",
dataType: 'text',
data: {new_option : 'new_option'}
}).fail(function (jqXHR, textStatus, errorThrown){
console.error("The following error occured: " + textStatus, errorThrown);
});
if you're going to be able to access it with :
$_POST['new_option'];
in PHP.
Without keys, it would be just $new_option = $_POST; to get the string
since you are taking your posted value as $_POST['new_option']..you need to pass the data object as new_option in ajax...
try this
...
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/upload_page",
dataType: 'text',
data:{'new_option':new_option}, //<---here
});
console.log(new_option);
.....

Finding id of elements

i have this bit of html.
(Link at bottom)
Its output of php code for status updates, it has view comments and post comment link, the post comment link uses jquery to add a textarea and submit button below that status update. and the view comments shows the comments to that status update below that status update.
So i use php looping so there will be obviously more than 1 status updates at most times(depends on how much friends users have) so i cant have an element like 'textelement', i will need to have elements like 'textelement1' and 'textelement2'
So i used php to add the id of the status update in the end of the links like _id so the element id becomes view_comments_1.
So i want to use jquery to find out which element has been clicked so that i can add a text box and show comments below the right status update instead of showing it below all status updates.
HTML
<div class="wrapbg">
<span class="corners-top"><span></span></span>
<div id="content"><br/>
Whats new?
<hr class='hr1'>
<div class='stbody' id='stbody'>
<div class='stimg'>
<img src='uploads/profile_pics_small/Anonymous_Blueprint_Wallpaper_by_co.jpg' /></img>
</div>
<div class='sttext'>
Welcome yoall!!
<div class='sttime'>By LUcase</div>
<br><br>
<a href=''>0 Likes</a> <a href=''>1 Dislikes</a>
</div>
<a href=''>unDislike</a> <a id='comment_now_1' href=''>Comment</a> <a id='view_comments1' data-id-1 = '1' href=''>View comments</a> <div id='emptydiv1'> </div></div>
<div class='stbody' id='stbody'>
<div class='stimg'>
<img src='uploads/profile_pics_small/wood_texture_by_pabloalvin-d1igijr.jpg' /></img>
</div>
<div class='sttext'>
hi
<div class='sttime'>By nicknick</div>
<br><br>
<a href=''>0 Likes</a> <a href=''>0 Dislikes</a>
</div>
<a href=''>Like</a> <a href=''>DisLike</a> <a id='comment_now_4' href=''>Comment</a> <a id='view_comments4' data-id-4 = '4' href=''>View comments</a> <div id='emptydiv4'> </div></div></div>
<span class="corners-bottom"><span></span></span>
</div>
JavaScript
//Gotta find out which status update we are dealing with!
jQuery("document").ready(function(){
jQuery(".likebtn").click(function(e) {
var id=jQuery(this).attr("data-id");
jQuery.post('like.php', {'id': id}, function(data) {
alert("Your like.php has been called");
}, "json");
e.preventDefault();
});
jQuery(".dislikebtn").click(function(e) {
});
//gotta figure out which status update we are dealing with!
//attache the click event to the anchor tag
$("#comment_now").live("click",function(e){
//prevent the default behaviour of following the link
e.preventDefault();
$("#comment_now").remove();
//find the textarea element, and after it, put an input tag
$(".sttext").after('<textarea id="comment_text" name="comment"></textarea> <br> <button id = "post_button" class="action greenbtn"><span class="label">Comment</span></button> <a id="cancel_comment" href="">Cancel</a> <br id="com_spacing">');
});
//gotta figure out which status update we are dealing with!
$("#cancel_comment").live("click",function(event){
event.preventDefault();
$("#comment_text").remove();
$("#cancel_comment").remove();
$("#post_button").remove();
$("#com_spacing").remove();
$("#view_comments").before('Comment ');
});
$("#view_comments").live("click", function(e){
e.preventDefault();
var id=jQuery(this).attr("data-id");
$.ajax({
url: 'query_comments.php?status_id='+id,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
},
success: function( data ) {
$('#emptydiv').html(data);
}
});
});
});
Please help me out :)
You know that html forms can send arrays, right?
<input type="text" name="textelement[]" value="First Element" /><br/>
<input type="text" name="textelement[]" value="Second Element" /><br/>
PHP Code:
foreach($_POST['textelement'] as $somethingSomething){
echo $somethingSomething, "\n";
}
Prints out:
First Element
Second Element
add a class to to action buttons and pass the comment id as data attribute like so:
<a class="commentBtn" href='' data-commentid="1">Comment</a>
and than you can read out the id easily with jquery:
$(".commentBtn").live("click",function(e){
var id = $(this).data('commentid');
e.preventDefault();
// do something with id…
});

Categories