I have a form in a modal that saves data in a table (Food). The table has the following fields:
ID
Category
Type
When I load the page, I straight away get an Uncaught SyntaxError: Unexpected identifier (managefood:393); I've commented in the code below which line this refers to.
Opening the modal and filling in the fields works fine. Saving however fails, upon refreshing the page and checking MySQL, no new data has been entered. I'm not really sure how to check where my AJAX POST has failed (for example if say one of the form inputs is broken, and since those fields are required, that would explain it not saving).
I re-Cake baked my Model as well for the table, just to check if there was an issue in the Model, but that didn't fix it.
Below is the code that includes the button and script that opens the modal, the modal itself with the form inputs, and the script that saves the data.
$(document).ready(function() {
$("#newsavebutton").click(function() {
$.post("<?= $host . $basepath ?>/food/add.json", {
category: $('#category').val(),
type: $('#type').val() //line 393
};);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<button onclick="newFood()" class="btn btn-primary btn-xl page-scroll wow tada">New Food</button>
<script>
function newFood() {
$('#newfoodModal').modal('show');
}
</script>
<div class="modal fade" id="newfoodModal" tabindex="-1" role="dialog" aria-labelledby="newfoodLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title" id="newfoodLabel">New Food</h3>
<br>
<div>
<div class="col-sm-12">
<label for="category" id="newCategoryLabel" style="text-align: left">Category</label>
<select name="category" id="newCategory" onchange="newchangeCategory()" class="form-control">
<option value="" disabled selected hidden>Select a category</option>
<option value="Fruit">Fruit</option>
<option value="Vegetable">Vegetable</option>
</select>
</div>
<div class="col-sm-12">
<label for="type" id="newTypeLabel" style="text-align: left">Type</label>
<select name="type" id="newType" class="form-control"></select>
</div>
//this script enables for the second select to change based on the first - if Fruit is chosen as the category for example, only fruit options are shown in the Type select.
<script type="text/javascript">
var typeOptions = {};
typeOptions['Fruit'] = [
'Apple',
'Pear',
'Banana',
'Plum',
'Peach'
];
typeOptions['Vegetable'] = [
'Broccoli',
'Carrot',
'Pumpkin'
];
function newchangeCategory() {
var categoryChoice = document.getElementById('newCategory');
var typeChoice = document.getElementById('newType');
var selectedCategoryChoice = categoryChoice.options[categoryChoice.selectedIndex].value; //line 340
console.log(selectedCategoryChoice);
while (typeChoice.options.length) {
typeChoice.remove(0);
}
var typesAvailable = typeOptions[selectedCategoryChoice];
if (typesAvailable) {
var i;
for (i = 0; i < typesAvailable.length; i++) {
var type = new Option(typesAvailable[i], typesAvailable[i]);
typeChoice.options.add(type);
}
}
};
</script>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close
</button>
<button id="newsavebutton" type="button" class="btn btn-primary" data-dismiss="modal">Save changes
</button>
</div>
</div>
</div>
</div>
Below is also the code for the Add function in the Controller:
public function add()
{
$food = $this->Food->newEntity();
if ($this->request->is('post')) {
$food = $this->Food->patchEntity($food, $this->request->data);
if ($this->Food->save($food)) {
$this->Flash->success(__('The food has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The food could not be saved. Please, try again.'));
}
}
$this->set(compact('food'));
$this->set('_serialize', ['food']);
}
As far as I see this is a syntax error.
Your code is as follows:
$.post("<?= $host . $basepath ?>/food/add.json", {
category: $('#category').val()
type: $('#type').val() //line 393
};);
Try adding a coma , after line 392, before the type: property declaration. Like so:
$.post("<?= $host . $basepath ?>/food/add.json", {
category: $('#category').val(), //<-- here
type: $('#type').val() //line 393
};);
Regarding the error handling issue: According to the jQuery documentation you cana use the .done(), .fail() and .always() methods to see whether the POST request itself fails or is successful. For example:
$.post("<?= $host . $basepath ?>/food/add.json", {
category: $('#category').val(), //<-- here
type: $('#type').val() //line 393
})
.done(function(data) {
console.log(data);
alert( "success" );
})
.fail(function(error) {
console.log(error);
alert( "error" );
});
That way you can see what the POST returns and what the erorr is (if any).
Related
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 have two elements of members data such as id and some other info in a modal which are hidden input elements inside my modal, I bind data from a anchor tag using javascript, example of data element in the anchor tag:
data-column="'.htmlspecialchars($column, ENT_QUOTES, 'utf-8').'"
Javascript example to bind into the modal:
$('#EnterExpiryModal').on('show.bs.modal', function (e) {
var memberID = $(e.relatedTarget).data('id');
$('#memID232').val(memberID);
var cola3 = $(e.relatedTarget).data('column');
$('#column3').val(cola3);
});
Having the relevant data for the members in question in my modal (modal code snippet below):
<div class="modal" id="EnterExpiryModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div id="ExpiryError"></div>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Please enter document expiry date</h4>
<br>
<form class="form-horizontal" method="post" id="ExpiryDateForm">
<div class="form-group">
<input id ="memID232" name="memID232" class="form-control" type="hidden">
</div>
<div class="form-group">
<input id ="column3" name="column3" class="form-control" type="hidden">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Date</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<div class="clearfix">
<div id="date" data-placement="left" data-align="top" data-autoclose="true">
<input name="date" type="text" class="form-control hasDatepicker" placeholder="Choose Date">
</div>
</div>
</div>
</div>
</div>
<div class="middleme"><p><i class="fa fa-info-circle iwarner" aria-hidden="true"></i><small> These documents can be uploaded again at any time...</small></p></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="expirySubmit" name="expirySubmit" class="btn clocumsbtn">Confirm</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
The above code produces the below modal:
As you can see user is prompted to enter a expiry date in the form field and click confirm.
However the issue I am having is when I hit submit the form does submit, my jQuery validation does all the necessary checks before submitting using ajax, but my hidden input elements don't submit with the values as they should, they appear to be empty, but the datepicker (date) field is populated - I know the values populate with the required data I need.
Here's what the modal looks like without the elements being hidden:
Here is the validation:
$("#ExpiryDateForm").validate({
rules:
{
memID232: {
required: true,
minlength: 0
},
column3: {
required: true,
minlength: 0
},
date: {
required: true,
minlength: 3
}
},
messages:
{
memID232: "There's an error",
column3: "There's an error",
date: "Please enter the expiry date",
},
submitHandler: submitExpiryDate
});
here's the submit handler:
function submitExpiryDate() {
var data = $("#ExpiryDateForm").serialize();
$.ajax({
type : 'POST',
url : 'enterdocexpiry.php',
data : data,
beforeSend: function() {
$("#expirySubmit").html('<span class="fa fa-spinner"></span> please wait...');
},
success : function(responses) {
if(responses=="1"){
$('#ExpiryError').removeClass('animated shake');
$("#ExpiryError").fadeIn(1000, function(){
$('#ExpiryError').addClass('animated shake');
$("#ExpiryError").html('<div class="alert alert-danger"> <span class="fa fa-exclamation"></span> Sorry there was an error!</div>');
});
}
else if(responses=="updated"){
$("#ExpiryError").fadeIn(2000, function(){
$("#expirySubmit").html('<span class="fa fa-spinner"></span> updating...');
$("#ExpiryError").html("<div class='alert alert-success'><span class='fa fa-check-square-o'></span> Added Expiry Date!</div>");
setTimeout(function(){
window.location.href="manage_docs.php";
},2000);
});
}
else {
$("#ExpiryError").fadeIn(1000, function(){
$("#ExpiryError").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#expirySubmit").html('<span class="glyphicon glyphicon-log-in"></span> Some other error');
});
}
}
});
return false;
}
here the php:
require "database.php";
$memberID = $_POST['memID232'];
$column = $_POST['column3'];
$date = DateTime::createFromFormat('d/m/Y',$_POST['dates']);
$expiryDate = $date->format("Y-m-d");
$docploaded = "Yes";
if (isset($_POST['expirySubmit'])) {
if ($column == "passport") {
$statement = $conn->prepare('UPDATE memberdocs SET pexpiry=:expiryDate,puploaded=:docploaded WHERE m_id=:memberID');
$statement->bindParam(':expiryDate', $expiryDate);
$statement->bindParam(':docploaded', $docploaded);
$statement->bindParam(':memberID', $memberID);
$statement->execute();
if($statement->execute() ):
echo 'updated';
else:
echo "1";
endif;
}else if ($column == "crb") {
$statement = $conn->prepare('UPDATE memberdocs SET cvexpiry=:expiryDate WHERE m_id=:memberID');
$statement->bindParam(':expiryDate', $expiryDate);
$statement->bindParam(':memberID', $memberID);
$statement->execute();
if($statement->execute() ):
echo 'updated';
else:
echo "1";
endif;
}
}
Now I have done some troubleshooting and it seems the datepicker is the issue here. If I remove the datepicker (date) form field and replace it with a standard free text input field my form submits successfully with the memID232 input field and column3 input field populated, executing my php script, I've tried to be as clear as possible I hope the screenshots and snippets help, any advice?
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 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()