Codeigniter insert to database via ajax from model - php

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!

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.

Passing a PHP variable to a modal and using it in MySQL query

I have a table with multiple edit buttons. Each edit button is supposed to open up a modal and I am trying to pass the delivery_id to it, so I can then use it in MySQL query
echo "<td><button type='button' class='btn dt_buttons' data-toggle='modal' data-id='$delivery_id' data-target='#editModal'>Edit</button></td>";
What's the best way of retrieving that value in the modal and using it as a variable? I thought that just using $delivery_id would work, but of course that would be too simple!
Code inside the modal:
<div id="editModal" class="modal fade" 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">Edit Purchase</h4>
</div>
<div class="modal-body">
<?
$query = "SELECT id, supplier_id, date as del_date, delivery_number, po_number, cost_value FROM store_purchases WHERE id = $delivery_id";
echo $query;
$retval = f_select_query($query, $datarows);
$lint_product_id = f_htmlspecialchars_decode($datarows[0]->id , ENT_QUOTES);
$supplier_id = intval($datarows[0]->supplier_id);
$delivery_date = $datarows[0]->del_date;
$delivery_number = intval($datarows[0]->delivery_number);
$lint_unit_cost = f_htmlspecialchars_decode($datarows[0]->cost_value , ENT_QUOTES);
$lint_unit_cost = floatval($lint_unit_cost);
$lint_unit_cost = number_format($lint_unit_cost, 2);
$department_id_dropdown = f_get_dropdown("supplier_name", "supplier_name", "supplier_master", $supplier_id, "id", " store_id = $store_id", '', '', '', false, false, true);
?>
<div class="container-fluid" id="div_user_master" class="ae_form" >
<form id="myForm" action="/platformDev/create_subscription.php" method="POST">
<?
echo "Supplier Name: <td class='text-right' id='department_id' style='width:20%;'> $department_id_dropdown </td> <input id='purch_id' name='purch_id' class='form-control purch_id' value='$product_id' type='hidden'/>";
echo "Delivery Date: <span class='required_field'><i class='fa fa-star fa-sm'></i> </span> <input class='form-control' tabindex='3' id='date' name='date' value= '$delivery_date' type='text'/> <br/>";
echo "Delivery Number: <input type='text' id='unit_cost' name='unit_cost' class='form-control unit_cost' style='width:80%;' value='$delivery_number' />";
echo "Invoice Cost: <input type='text' id='unit_cost' name='unit_cost' class='form-control unit_cost' style='width:80%;' value='$lint_unit_cost' /></div>";
?>
</form>
</div>
</div>
<div class="modal-footer">
<button class="btn form-btns btn-primary" style="float: left;" data-dismiss="modal" id="customButton">Add Purchase</button>
<button type="button" class="btn dt_buttons close_this ajax_forms" data-dismiss="modal">Close</button>
</div>
</div>
</div>
The code below will get the data-id value from the button that was clicked.
You can use this template:
$('#editModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var delivery_id = button.data('id'); // delivery id here
var modal = $(this)
modal.find('.modal-title').text('Delivery #' + delivery_id);
modal.find('.modal-body').html('content here');
});
https://getbootstrap.com/docs/4.0/components/modal/
https://getbootstrap.com/docs/3.3/javascript/#modals
I guess that you are trying to use that id to fetch records and populate the modal with that data.
If that's the case :
You can retrieve the data-id attribute value with Javascript and send Ajax request to your php script and query your database.
$('.dt_buttons').on('click', function()
{
var id = $(this).attr('data-id');
$.ajax
({
url: "your/url",
data:
{
id : id
},
method: 'POST'
}).success(function(response)
{
var json = response,
obj = JSON && JSON.parse(json) || $.parseJSON(json);
// say you have following fields.
var fid = obj[0].id;
var title = obj[0].title;
//retrieve record fields here.
// or just pass the `id` skipping the Ajax stuff above.
$('#editModal')
.find('span.doc-title').text(title).end()
.find('[name="id"]').val(id).end();
/* show modal.. */
$('#editModal').modal('show');
});
});

Insert data into mysql database using ajax in php multiform

Hey I am trying to insert into mysql/php/ajax with multiforms on a page.
The insert works fine, but form nr 2, sets form nr 1´s data into the mysql DB.
I have 4 forms on each page, it is a firecheck on a dorm, where I need to check 28 kitchens if they keep the standard firerules.
so what I need is the little goldcorn to make this work :) so each form, only respond on the data in that form.
Here is my code:
<div class="content">
<a class="hide" id="1a" name="1a">1A</a><br>
<form action="" id="1a" method="" name="1a" novalidate="novalidate">
<div class="wrapper">
<div class="table">
<br>
<br>
<div class="row header">
<div class="cell">
1A
</div>
<div class="cell"></div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Døre
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="door" name="door" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Skilte
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="skilt" name="skilt" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Nødlys
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="lys" name="lys" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Brandtæppe
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="b_t" name="b_t" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Brandspørjte
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="b_s" name="b_s" rows="3">Ok</textarea>
</div>
</div>
</div>
<input id="dato" name="dato" type="hidden" value="<?php echo date(">") ?> <!--class = "btn btn-success btn-block" -->/>
<button class = "send" id = "insert-data1a" name = "insert-data1a" onclick = "insertData1a()" type = "button">Insert Data</button><br>
<p id = "message1a"></p>
</div><!--end wrapper -->
</form>
</div><!--end content -->
<script type = "text/javascript">
function insertData1a() {
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "insert-data1a.php",
data: {door: door, skilt: skilt, lys: lys, b_t: b_t, b_s: b_s, dato: dato},
dataType: "JSON",
success: function (data) {
$("#message1a").html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
alert(err);
}
});
}
</script>
the next form, looks the same, but new insert-data name and form name.
Insert Data
<script type="text/javascript">
function insertData1b() {
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "insert-data1b.php",
data: {door: door, skilt: skilt, lys: lys, b_t: b_t, b_s: b_s, dato: dato},
dataType: "JSON",
success: function (data) {
$("#message1b").html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
alert(err);
}
});
}
</script>
<?php
include('db.php');
$door=$_POST['door'];
$skilt=$_POST['skilt'];
$lys=$_POST['lys'];
$b_t=$_POST['b_t'];
$b_s=$_POST['b_s'];
$dato=$_POST['dato'];
$stmt = $DBcon->prepare("INSERT INTO 1_a(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
$stmt->bindparam(':door', $door);
$stmt->bindparam(':skilt', $skilt);
$stmt->bindparam(':lys', $lys);
$stmt->bindparam(':b_t', $b_t);
$stmt->bindparam(':b_s', $b_s);
$stmt->bindparam(':dato', $dato);
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Probelm occur.";
echo json_encode($error);
}
?>
the one for b, looks almost the same
$stmt = $DBcon->prepare("INSERT INTO 1_b(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
In addition to Bakayaro's answer, if all your forms got the same fields, you can optimize your code to use only one javascript function and one PHP insert script.
Factorise your code ! Rembember one thing : DRY (Don't Repeat Yourself)
HTML
Add a click listener on each .send button instead of using onclick() on them
Add specific ID on each different form, with kitchen ID
Add data to .send button with related form's kitchen ID
Example for kitchen 1A:
<!-- Add specific ID with kitchen ID -->
<form action="" id="kitchen1a" method="" name="1a" novalidate="novalidate">
...
<!-- Add data to each .send button with related form's kitchen and remove onclick() -->
<!-- data-kitchen="1a" -->
<button class = "send" id = "insert-data1a" name = "insert-data1a" data-kitchen="1a" type = "button">Insert Data</button>
Don't use same ID on different HTML elements, as your a and form tag.
Javascript
Use click listener
Get active form's data from each field's name
Working example based on your code:
$('.send').on('click', function(e) {
var kitchen = $(this).data('kitchen');
var form = $('#kitchen' + kitchen);
var data = {
door: form.find('[name="door"]').val(),
skilt: form.find('[name="skilt"]').val(),
lys: form.find('[name="lys"]').val(),
b_t: form.find('[name="b_t"]').val(),
b_s: form.find('[name="b_s"]').val(),
dato: form.find('[name="dato"]').val(),
// add active kitchen in your POST data
kitchen: kitchen,
};
// AJAX code to send data to php file.
$.ajax({
type: "POST",
// use same PHP script for each forms
url: "insert.php",
data: data,
dataType: "JSON",
success: function (data) {
// use kitchen's specific message tag
$("#message" + kitchen).html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
// alert(err);
console.log(err);
}
});
});
PHP file
Use one single PHP script for each form and generate table name in your SQL query from given kitchen value.
Working example based on your code:
$kitchen = $_POST['kitchen'];
// if your kitchens are all formatted like this : 1a, 2c, 14a, ...
preg_match('/(\d)+([a-z])/', $kitchen, $matches);
$stmt = $DBcon->prepare("INSERT INTO " . $matches[1] . '_' . $matches[2] . "(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
Generated query for your 1a form:
INSERT INTO 1_a(door,skilt,lys,b_t,b_s,dato) VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)
If I do understand well, you have multiple forms on one page and the second form posts the values of the first form.
I think the problem is that you're using tha same ids on the fields of the forms.
Take a look at:
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
These are the fields from insertData1a() function and it's the same in the other function:
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
So basically the problem is that you're referencing the same fields in the second function.
The id attribute must be a unique id for an HTML element, so you should use different ids in each form or if you're already using different ids (you didn't post the html of the second form) you just have to rewrite the elements in your second function.

CakePHP 3 - AJAX saving issue and Uncaught SyntaxError: Unexpected identifier

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).

Submitting form via POST with jQuery and Ajax

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()

Categories