I have over the last week managed to setup a page which on click of a check box saves its data to a database directly my only issue now is how to save the new values to the right column in the database.
I have 3 checkboxes with different values and names that are posted through ajax to the other page. I'm unsure of how to proceed with this.
Here is a snippet of my code:
<script type="text/javascript">
$(function() {
$("input[type='checkbox']").on('click', function() {
var $this = $(this);
var isChecked = $this.prop('checked');
var checkVal = isChecked ? $this.attr('id') : $this.attr("value");
var userid = $this.attr('name');
$.ajax({
type: "GET",
url: 'request.php?uname=' + checkVal +'&id=' + userid,
success: function(data) {
//Success
if(data == 1){
alert('Data was saved in db!');
}
//Failure
if(data == 0){
alert('Data was NOT saved in db!');
}
}
});
});
});
The Html
<form id="frm" name="frm">
<td><input name="29" type="checkbox" id="Paid" value="Waiting on Payment" checked="checked" /></td>
<td><input name="30" type="checkbox" id="Repaired" value="Waiting on Repairs" /></td>
<td><input name="31" type="checkbox" id="With Student" value="Awaiting Pickup" /></td>
</form>
Here's the database structure as well:
name: test
Paid
repair
Returned
What I am finding myself unable to do is how to tell the Mysql query which column to save the new value in because the GET function is only pulling in the value on the other page and I can't get it to separate them so that the paid check will only save in the paid column and so on..
Here is the request page so that page that gets the value:
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
// error happened
print(0);
}
mysql_select_db('test');
// sanitize the value
$value = mysql_real_escape_string($_GET['uname']);
$id = mysql_real_escape_string($_GET['id']);
// start the query
$sql = "INSERT INTO `test` VALUES ( NULL, 2, 3, '$value')";
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
What you need, is to define the columns in your INSERT, like this:
INSERT INTO `test` (col1, col2, col3, ...) VALUES ( NULL, 2, 3, '$value')
Where 'col1', 'col2', etc are your columns. That way you can define the columns you need. In VALUES() you'll only put the values for the previously defined columns. For example:
INSERT INTO `person` (name) VALUES ('tom')
Related
I have a form with a button that can add dynamic input fields, and it's creating an ajax issue. My ajax post is giving me 500 errors
But My console log for data right now is this:
but I need to insert these as
insert into ticker_content (ticker_id, content)
values (1, 'one'), (1, 'two');
If that makes sense.
So basically, the problem is i have multiple inputs at any given time (containing text values) and a hidden input in the form that gives me my correct ticker ID.
However, I need to make my array contain elements that each have the input text value and the ticker ID. So for every input that's created and filled, I need to assign the value of that form's hidden input to it as well so I can sent them as pairs to my foreach loop and insert.
Here's my addticker.php that's being called for the insert:
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO ticker_content (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}
So basically for every Items[] value, I need to insert with the same hidden field.
Here's my form and JS code for reference. The first JS block is mainly for the functionality of dynamically adding inputs, but the last JS block is the ajax using serializeArray();
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/> <!--form starts with one input-->
<button type="button" class="moreItems_add">+</button> <!--button dynamically adds input, up to 10 per form-->
<input type="hidden" name="tickerID" id="tickerID" class="tickerIdClass" value="<?php echo $ticker['ticker'] ?>"><!--hidden input used for tickerID-->
<input type="submit" name="saveTickerItems" value="Save Ticker Items"> <!--submit button-->
</form>
<?php endforeach;?>
<!-- This is the functionality for each form to click the '+' button and create new inputs -->
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $(this).closest('form').find('.tickerIdClass').val(); //get value of hidden input for form
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
<!-- This is the ajax call to send all filled out and created inputs from form along with the hidden input -->
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serializeArray();
console.log(data);
$.ajax({
type: "POST",
url: "addticker.php",
data: $("#Items").serializeArray(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
Firstly, you are missing a semicolon in your code (which is likely causing your 500 error).
Secondly, if you want to bundle all the fields from the form as a single query, the following will build out a query similar to what you noted earlier in your question as:
INSERT INTO ticker_content (ticker_id, content) VALUES(1, 'one'), (1, 'two'), ...
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
$addTicker = "INSERT INTO ticker_content (tickerID, content) values";
foreach ($items as $item){
$addTicker .= "('$tickerID', '$item'),";
}
$addTicker = substr($addTicker, 0, -1); // Eat that last comma
$mysqlConn->query($addTicker);
Your HTML also needs some work because the id attribute should be unique on the page. Since you are duplicating the form, you should do something like the following:
<form id="Items<?php echo $ticker['ticker']?>" class="tickerform" method="post">
And then update your javascript:
// Using $(this) in Jquery allows you to access the
// element that is making the method call (in this case, the form)
$(".tickerform").submit(function(e) {
e.preventDefault();
var data = $(this).serializeArray();
console.log(data);
$.ajax({
type: "POST",
url: "addticker.php",
data: data, // Don't need to serialize again, 'var data' is still in scope.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
I am trying to clear the txtSubTotal text box after clicking the PROCEED button. It's not working though I tried some code examples, even in SO.
btnProceed/HTML
<input type="submit" name="btnProceed" id="btnProceed" value="PROCEED" onclick="clearSubTotal();"/>
clearSubTotal()/JS
function clearSubTotal() {
$('#txtSubTotal').val('');
}
txtSubTotal
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" value="<?php
$sql=mysqli_query($connection,"select sum(amount) from sales_temp");
$row = mysqli_fetch_array($sql);
echo $row[0];
?>"/>
form/HTML
<form id="manageSalesForm" name="manageSalesForm" method="post" action="<?php echo BASE_URL?>includes/functions/sales_functions.php">
Appreciate your help on this.
NOTE: Found that on the second button press, the text box clears. How to set this correctly for the first button perss?
ADD button/JS
function submitdata() {
var listItemName = document.getElementById("listItemName").value;
var listStock = document.getElementById("listStock").value;
var txtUnitPrice = document.getElementById("txtUnitPrice").value;
var txtQuantity = document.getElementById("txtQuantity").value;
var listCustomer = document.getElementById("listCustomer").value;
var txtReceiptNo = document.getElementById("txtReceiptNo").value;
var TheDate = document.getElementById("TheDate").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = {listItemName:listItemName, listStock: listStock, txtUnitPrice: txtUnitPrice, txtQuantity: txtQuantity, listCustomer: listCustomer, txtReceiptNo: txtReceiptNo};
if (listItemName == '' || listStock == ''|| txtUnitPrice == ''|| txtQuantity == ''|| listCustomer == ''|| txtReceiptNo == ''|| TheDate == '') {
salesitemsAddFail();
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "/pms/includes/functions/sales_temp_functions.php",
data: dataString,
cache: false,
success: function(html) {
//reload the sales datagrid once add the item details to temporary table (sales_temp)
$('#list').trigger("reloadGrid",[{page:1}]);
window.location.reload();
}
});
}
}
$('#btnProceed').click(function(event) {
event.preventDefault(); // stops form submission
$('#txtSubTotal').val('');
});
ADD button/HTML
<td width="46"><button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
sales_functions.php
<?php
//Start the Session
if(!isset($_SESSION))
{
session_start();
}
include ("/../../pages/sales.php");
include("/../../dbutil.php");
if(isset($_POST['listCustomer'])){ $customer = $_POST['listCustomer'];}
if(isset($_POST['staff'])){ $user = $_POST['staff']; }
if(isset($_POST['btnProceed'])){
$result=mysqli_query($connection,
"INSERT INTO sales(cus_id,item_id,stock_id,receipt_no,qty,unit_price,amount,user_id,purchase_id)
SELECT C.cus_id, I.item_id, S.stock_id, $receipt_no, ST.qty, ST.unit_price, ST.amount, U.id, P.purchase_id
FROM customers C, items I, stock S, sales_temp ST, users U, purchase_items P
WHERE ST.staff='$user'
AND C.customer_name='$customer'
AND I.item_name=ST.item_name
AND S.stock_code=ST.stock_code
AND ST.purchase_id=P.purchase_id");
//Update available qty from purchase_items relevant only to the logged in user(sales_temp table may have records from multiple users)
$resultUpdate=mysqli_query($connection, "UPDATE purchase_items P INNER JOIN sales_temp ST ON (P.purchase_id = ST.purchase_id) SET P.avail_qty = (P.avail_qty - ST.qty) WHERE ST.staff='$user'");
//Delete records relevant only to current user. Here 'WHERE' clause use to prevent deleting other user's records.
$resultDelete=mysqli_query($connection, "DELETE FROM sales_temp WHERE staff='$user'");
if (!$result) {
printf("Errormessage: %s\n", mysqli_error($connection));
}
// use exec() because no results are returned
if ($result) {
}
else
{
echo '<script type="text/javascript">',
'salesAddFail();',
'</script>';
}}
?>
After clicking on the submit button, the form is being submitted and your custom function is not being executed.
Delete the onclick from your input element and edit your jQuery code:
$('#btnProceed').click(function(event) {
event.preventDefault(); // stops form submission
$('#txtSubTotal').val('');
});
You can try it in your browser: https://jsfiddle.net/hy7jwg8m/1/
It is working perfect for me. And after clicking on submit it might be working for you but with the same time page will be redirected to new action
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);
My dad and I are working on a project where we'd like to create a script that calls in data when a number is submitted into a form. For example, when you type in your ID number then press ENTER or SUBMIT, the form will print/display information. This is a project for school, so when a student submits their ID number it will read their first period class, for example.
I have the following script code to set up the form:
<form id="firstPeriod" action="firstPeriod.html">
<p>Find your first period.</p>
<p><label>Student no.: <input type="text" name="studentNo"></label></p>
<p><input type="submit" value="Find it"></p>
<p id="result"></p>
</form>
<script type="text/javascript">
$(function() {
$('#firstPeriod').submit(function() {
$.ajax({ // Send the request behind the scenes
url: $(this).attr('action'), // Send it here
data: $(this).serialize(), // With this student no.
success: function(data) {
$('#result').html(data); // Display the resulting HTML
},
error: function(jqxhr, status, error) {
console.log(error);
$('#result').html('No results found. Please check your number and reenter'); // Notify an error
}
});
return false; // Prevent the normal form submission
});
});
My question is, what would be the best way to organize the data? An array, HTML, etc.? There are quite a lot of ID numbers and are currently set up in an HTML table, but that doesn't seem to work in calling the information. And I'd like for the data to be specific. So when a specific ID number is typed in, it reads a specific answer. Right now my problem is when I type in a number it reads several classes.
If there are any suggestions/advice/other posts that could help me, I'd be grateful. I have solid HTML, CSS experience but I'm still learning JS and jQuery so this is a little new for me. Thanks!
Edit, Updated
Note, added value attribute to input type="text" element
<input type="text" name="studentNo" value="" />
substituted .submit() for .on("click") at input type="submit" element
Two possible approaches could be 1) using HTML to store data, .load() to retrieve fragment identifier within html file; or 2) storing data using JSON, retrieving file using php
html at firstPeriod.html
<div id="0">data 0</div><div id="1">data 1</div>
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$("#result").load(form.attr("action") +" #"+ id)
})
})
plnkr http://plnkr.co/edit/4onHf9jlJTyDei1zo9IC?p=preview
JSON
0.json
{
"0":"<div id='0'>data 0</div>"
}
1.json
{
"1":"<div id='1'>data 1</div>"
}
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$.post("data.php", {id:id}, function(result) {
$("#result").html(result[id])
}, "json")
})
})
php
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
$file = $id . ".json";
if (file_exists($file)) {
$jsondata = file_get_contents($file);
$id_data = json_decode($jsondata, true);
echo json_encode($id_data);
};
}
I have a form and it has radio buttons that a user must click to increement a value in the database but I click the radio button and nothing happens in the database heres my form code:
<form id="myform" name="myform" method="post">
<div class="radio show-options">
<li><label id="l_security"><input type="radio" id="r_security" name="weekend" value="security" />Security</label> (<label id="c_security">0</label>)</li>
</div>
<div class="radio show-options">
<li><label id="l_manager"><input type="radio" id="r_manager" name="weekend" value="manager" />Manager</label> (<label id="c_manager">0</label>)</li>
</div>
<div class="radio show-options">
<li><label id="l_cleaner"><input type="radio" id="r_cleaner" name="weekend" value="cleaner" />Cleaner</label> (<label id="c_cleaner">0</label>)</li>
</div>
</form>
here the script for the form
<script type="text/javascript">
var lastClicked = '';
function getTotals() {
// function to get click counts as JSON from helper page
// expects get_count.php to be in same directory level
$.ajax({
type: "GET",
url: "get_count.php",
dataType: "json",
error: function(xhr, status, msg) {
alert("Failed to get click counts: " + msg);
}
})
.done(function(data) {
// loop through JSON variables, assign to count labels
$.each(data, function(key, value) {
var tmp = "#c_" + key;
$(tmp).text(value);
});
});
}
function processClick(obj) {
// function to increment click count via ajax
// expects increment_count.php to be in same directory level
if(lastClicked != obj.val()) { // don't count clicks on currently active radio button
lastClicked = obj.val(); // set currently clicked radio button to this one
var qs = "weekend=" + obj.val(); // set query string value
$.ajax({
type: "GET",
url: "increment_count.php",
data: qs,
error: function(xhr, status, msg) {
alert("Failed to process click count: " + msg);
}
})
.done(function() {
getTotals(); // update totals on successful processing
});
}
}
$(document).ready(function() {
getTotals(); // get click totals on initial page load
$(document).ready(function() {
// add click incrementing event handler to all radio buttons on page
$('input:radio').click(function() {
processClick($(this));
});
});
});
</script>
here is get_count.php
<?php
require('db_connect.php');
// get new count totals, pass as JSON
$rs = mysql_query("SELECT * FROM employee") or die('Cannot get updated click counts');
if(mysql_num_rows($rs) > 0) {
$out = "{ ";
while($row = mysql_fetch_array($rs)) {
$out .= "\"$row[name]\" : $row[leave], ";
}
$out = substr($out, 0, strlen($out) - 2);
$out .= " }";
header("Content-type: application/json");
echo $out;
}
and here is increment_count.php
<?php
require('db_connect.php');
// if this is a postback ...
if(isset($_GET['weekend'])) {
// create array of acceptable values
$ok = array('security', 'manager', 'cleaner');
// if we have an acceptable value for position_name ...
if(in_array($_GET['weekend'], $ok)) {
// update the counter for that position
$q = mysql_query("UPDATE employee SET leave = leave + 3 WHERE name = '".$_GET['weekend'] . "'") or die ("Error updating count for " . $_GET['weekend']);
}
}
the leave value in the employee table is not increased
I want to add a record dynamically.
When I insert action = "add.php" for my form, the addition is accomplished by displaying a message after refreshing.
I want to add this addition without refreshing dynamically.
Also, for the ID of my games, I want that when I delete a record, for the ID to be decremented or removed. So that, when I add a game again, it uses the next ID available, not keeps on incrementing, like it is happeneing with me now.
If I take off add.php from action, nothing happens and the game isn't added.
My question is, where is this script broken? Or if add.php is not functioning right?
Here is my index.php and add.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
</head>
<body>
<?php
include("dbconfig.php");
$sql = "SELECT * FROM games";
$result = mysql_query($sql);
while ($record = mysql_fetch_array($result)){
echo "<p class=\"p" .$record['ID']. "\"></br> Game ID: " .$record['ID']. "</br> Game Name: " .$record['Name'].
"<br /> Game Type: ".$record['Type']. "<br /> Rating: ".$record['Rating']."<br /> Year Released: ".$record['Release Year']."<br /> <br />" ?>
<img src="trash.png" alt="delete"/> </p>
<?php
}
?>
<form name="add" id ="add" action="" method="post">
<input class ="gameID" type="hidden" id="ID" name="ID" value = " ' .$record['ID'] . ' " />
<b>Game Name: </b> <input type="text" id="name" name="name" size=70>
<b>Game Type:</b> <input type="text" id="type" name="type" size=40>
<b>Rating: </b> <input type="number" id="score" name="score" min="1.0" max="10.0" step ="0.1"/>
<b>Year Released: </b> <input type="number" min="1900" max="2011" id="Yreleased" name="Yreleased" value="1985" size=4>
<p><input type="submit" name="Submit" id = "Submit" value="Add Game" class = "add games"></p>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("#add").submit(function(){
var name = this['name'].value;
var type = this['type'].value;
var rating = this['score'].value;
var release = this['Yreleased'].value;
var dataString = 'name='+ name + '&type=' + type + '&rating=' + rating + '&release=' + release;
if (name == '' || type == '' || rating == '' || release == ''){
alert("please enter some valid data for your game entry");
}else
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function(){
window.location.reload(true);
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
}
)});
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("a.deletebutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var parent = $(this).parent();
if(confirm("Sure you want to delete this game? !..There is no Undo")){
$.ajax({
type: "get",
url: "delete.php?" + info,
context: document.body,
success: function(){
$('.p'+del_id).html('deleted');
$('.success').fadeIn(200).show();
}
});
}
return false;
});
});
</script>
</body>
</html>
add.php
<?php
require('dbconfig.php'); //we cannot continue without this file, thats why using require instead of include
if(isset($_POST['name']))
{
$name=addslashes($_POST['name']);
$type=addslashes(($_POST['type']));
$rating=addslashes($_POST['rating']);
$release=addslashes($_POST['release']);
$sql = 'INSERT INTO `games` (`Name`,`Type`,`Rating`,`Release Year`) VALUES ("'.$name.'", "'.$type.'", "'.$rating.'", "'.$release.'")';
mysql_query( $sql);
if(!mysql_errno())
echo " your game has been added to the list of games. ";
}
?>
What your code is currently trying to do is the right principle: you are trying to trap the submit event on the form, make your Ajax request instead, and then cancel the default submit.
The reason it doesn't work is this line:
$("add games").Submit(function(){
".submit()" should have a lowercase "s", and the selector you are using, "add games", is not going to return any elements because it looks for elements with the tag name "games" that are descendents of elements with tag name "add".
What you want to do is fix the case of the "s", and select your element by id, which you do with "#yourid". Your form name has the id "add", so do this:
$("#add").submit(function(){
Also both your document.ready and your submit handler functions have an extra pair of {} curly braces around their bodies so you should delete those:
$("#add").submit(function(){
{ // <- delete this {
/*function body code*/
} // <- delete this }
});
Also you are including the jquery.js script twice - once is enough. And you don't need two document.ready handlers, you can combine them into a single one (though you can have more than one and that shouldn't cause a problem).
(There may be some other issues, but try this first and get back to us.)
UPDATE: After the other fixes, I suspect the problem is now in your PHP, in the line:
if(isset($_POST['Submit']))
I don't know PHP, but I assume this is checking for a request parameter called 'Submit' that you are not setting in your JS (it was the name of your submit button and would've been set for a "standard", non-Ajax submit, but it won't be included in your Ajax request). Try changing that line to use a request parameter that you are setting, like:
if(isset($_POST['name']))
Then, even if you don't seem to get a response in the browser, check your database to see if records are being added.
Make a few changes:
$("add games").submit(function(){ }); -> $(".add games").Submit(function(){});
or
$("#add").submit(function(){}); or $("#add").click(function(){ //run your ajax script here});
as for the id issue, MySQl will keep incrementing the id and if you delete one, it won't decrement it. May I know why you want the ids in order?
Editing again: (Use json.js)
here is another workaround:
var postdata = new Object();
postdata.name = value;
postdata.type = value;
postdata.rating = value;
//and so on
$.ajax({
url: 'your url',
type: "POST",
contentType: "application/json; charset=utf-8", //add this
data: JSON.stringify(postdata), //another change
dataType: "json",
success: function(data, st) {
if (st == "success") {
alert('Data Added');
}
},
error: function() {
alert("Failed!");
}
});
Aside from the problems everyone else helped with, your form is still submitting because of this line:
if (id =='' || name == '' || type == '' || rating == '' || release == ''){
You did not define id in the code above it. This is causing the function to throw an exception before return false is called. You need to either remove id =='' || from your if-statement or define it in your function.
As a side note, I see that you are pulling data from the form using the following:
var name = $("#name").val();
var type = $("#type").val();
Inside the submit handler, this is the form object, meaning you can access form fields by name. I would recommend using the following properties:
var name = this['name'].value,
type = this['type'].value;
This way, you don't need IDs on your form fields and you could if necessary insert the same form multiple times in the document.
Also, you should be validating your form input. A user could enter "); DROP TABLE games;// or <script src='http://evil.com/bad.js'></script> in any of your fields and really ruin your life.