I am trying to POST data from a form using jQuery & Ajax. However, when I check on my PHP to see if the form has been "submitted", it shows it has not because the MySQL code does not run. I am guessing my HTML is not setup correctly and therefore the Ajax request is not sending the data to my post-update.php script. Here is my code:
<script type="text/javascript">
$(document).ready(function() {
$('#ajax-remove-completion-date').click(function() {
$.ajax({
type:'POST',
url:'post-update.php',
data: dataString,
success: function(response) {
$('#success-remove-completion-date').removeClass('hidden');
}
});
});
});
HTML:
<form action="">
<div id="myModal1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel3">Remove Completion Date</h3>
</div>
<div class="modal-body">
<p>Are you sure you want to remove the students Completion Date?</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn blue" data-dismiss="modal" id="ajax-remove-completion-date">Yes</button>
<input type="hidden" name="submitted" value="remove-completion-date" />
</div>
</div>
</form>
PHP:
<?
session_id();
session_start();
require_once('assets/includes/mysql-connect.php');
/*Check to see if the completion date is being removed*/
if ($_POST['submitted'] == 'remove-completion-date') {
$query = "UPDATE students SET completion_date = NULL, completed = NULL WHERE student_id = {$_SESSION['student_id']} LIMIT 1";
$result = mysqli_query($dbc, $query);
}
?>
Where does dataString come from?
It's better if you define the data you want to send as an object. It's more readable and it's automatically converted to a query String.
$(document).ready(function() {
$('#ajax-remove-completion-date').click(function() {
$.ajax({
type:'POST',
url:'post-update.php',
data: {
submitted: 'remove-completion-date'
},
success: function(response) {
$('#success-remove-completion-date').removeClass('hidden');
}
});
});
});
If you want to take the value from the field, set submitted as:
$('input[name="submitted"]').val()
Related
This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 9 months ago.
I am trying to pass data to my php page:
<?php
var_dump($_POST);
if (isset($_POST['goal']) && isset($_POST['amount'])){
$goal = $_POST['goal'];
$amount = $_POST['amount'];
$array = array(
"goal" => $goal,
"amount" => $amount
);
echo json_encode($array);
}
However as a result of var_dump $_POST I keep getting an empty array, for some reason my ajax doesn't pass the neccessary data. I tried console.logging the value of fields that I am using and their value is correct it's just that data doesn't pass on the php page.
ajax:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
let amount = $("#amount").val();
let goal = $("#goal_name").val();
$.ajax({
method: "post",
url: "target-modal-code.php",
data:JSON.stringify( {
amount: amount,
goal: goal
}),
contentType:"application/json",
success: function (response){
$("#response").text(response);
console.log(amount);
console.log(goal);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
And my form is inside a modal :
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="enrollLabel">Change your goal</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="target-modal-code.php" name="target-form" id="target-form">
<div class="modal-body">
<form action="">
<div class="mb-3 input-control">
<label for="amount">Cost</label>
<input type="number" class="form-control" id="amount" name="amount"
placeholder="Amount">
<small class="message" id="message-password"></small>
<br>
</div>
<div class="mb-3 input-control">
<label for="goal_name">Goal</label>
<input type="text" class="form-control" id="goal_name" name="goal_name"
placeholder="Goal">
<small class="message" id="message-password"></small>
<br>
</div>
</form>
</div>
<p class="response" id="response"></p>
<div class="modal-footer">
<div class="response">
</div>
<button type="button" id="goalBTN" class="btn btn-warning">Save changes</button>
</div>
</form>
</div>
</div>
Updated answer after some live testing with Network tab in firefox web dev tools
The problem is that the current ajax code is not sending any of the elements because of wrong content-type. Let it detect content-type automatically. For jq ajax, default seems to be contentType: application/x-www-form-urlencoded even if you don't provide it specifically.
So, this worked:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
// let amount = $("#amount").val();
// let goal = $("#goal_name").val();
var formData = {
amount: $("#amount").val(),
goal_name: $("#goal_name").val(),
};
$.ajax({
method: "post",
url: "target-modal-code.php",
// datatype:"json",
//data:JSON.stringify(formData),
data: formData,
//contentType:"application/json",
//encode: true,
success: function (response){
$("#response").text(response);
// console.log(amount);
// console.log(goal);
console.log(formData);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
After little bit of fiddling, I noticed that it works if you DON'T provide it contentType at all. Otherwise, AJAX won't send GET or POST params to the server.... dont know why. I know it's weird but that's how it is in jquery ajax.
I have intentionally kept the comments for you to see what all I have tried.
So to summarize,
Don't stringify the form data,
Don't provide contentType to ajax
request.
Cheers.!
format send ajax:
$.ajax({
...
data : {
foo : 'bar',
bar : 'foo'
},
...
});
in your case: change data send format like:
data: {
amount: amount,
goal: goal
}
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.
I don't know what happens there. [
Here you see the Edit buttonedit(pencil) in actions when i uopdate the record modal will open.
When you click on edit(pencil) button modal will be open.
When i update the record first time its working fine and ajax runs one time. when i again update the record ajax runs twice and again update the record ajax run thrice. every time when i update the record the ajax run incremented
Here is my code:-
Html code of Button
enter code here
<button type="button" class="btn btn-info btn-edit editService"><i class="fa fa-pencil" aria-hidden="true"></i></button>// this button in foreach loop
My Modal:-
enter code here
<div class="modal fade" id="myModal-edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form id="subservicedata" role="form" method="POST" action="Javascript:;">
{{ csrf_field() }}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="add-cat">Edit Service</h4>
</div>
<div class="modal-body">
<div class="form-group row">
<span class="col-xs-3 add-cate-model">Service</span>
<div class="col-xs-8">
<input name="name" id="sname" class="form-control txtfield m-tb-10" type="text" placeholder="Service" value="">
<input type="hidden" name="id" id="id" value="">
<input type="hidden" name="serviceid" id="service_id" value="">
<input type="hidden" name="listid" id="list_id" value="">
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary editSubService">Submit</button>
</div>
</form>
</div>
</div>
My Jquery Code:-
enter code here
$(document).on ('click','.editService',function(){
var tdid = $(this).parents().parents().attr('id');
var service = tdid.split('-');
var subserviceid = service[1];
alert(subserviceid);
$.ajax({
type : "POST",
url : "get-service",
data : { id: subserviceid },
dataType: 'json',
success:function(resp){
if($.trim(resp)){
$('#myModal-edit').modal('show');
$('#sname').val(resp.name);
$('#id').val(resp.id);
$('#service_id').val(resp.service_id);
$('#list_id').val(resp.list_id);
$(document).on('click','.editSubService',function(){
$.ajax({
type : "post",
url : "edit-sub-service",
data : $("#subservicedata").serialize(),
success:function(resp){
if($.trim(resp)){
alert(resp);
alert(subserviceid);
$('#tr-'+subserviceid+' #tdid-'+subserviceid).html(resp);
$('#myModal-edit').modal('hide');
}else{
alert("Error"); return false;
}
},
error:function(){
alert("Something Went Wrong!");
}
});
});
} else{
alert("Failed"); return false;
}
}
});
});
And My laravel 5.2 function
enter code here
public function getCategoryService(Request $request){
if($request->ajax()){
$data = $request->all();
$servicedata= DB::table("session_subservices")->where('id',$data['id'])->first();
echo json_encode($servicedata);die;
}
}
public function editCategoryService(Request $request){
if($request->ajax()){
$data = $request->all();
//echo "<pre>"; print_r($data); die;
SessionSubservice::where('id', $data['id'])->update(array('name' =>$data['name']));
echo $data['name']; die;
}
}
The problem is that you append a new event every time the button is clicked.
You need to remove the first event if you want to retain your approach.
Change this $(document).on ('click','.editSubService',function(){
to this:
$(document).off('click').on('click','.editSubService',function(){
Other aproach is to create a function in your js and set it to be called in the html.
The problem is the .editSubSerice click handler:
$(document).on('click','.editSubService',function(){
...
}
You are adding this click handler in the success function of your ajax call which is part of another click handler, so every time that ajax call / click handler executes, you add an additional click handler and that causes the code to execute multiple times.
You should move that click handler to after (or before...) your other click handler so that it only gets called / binds once.
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!
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();