I have been trying everything to get this to work. When I hit the submit button nothing happens. It just sits there.
I have the html calling to a javascript that sends the data to a php file so that the webpage won't refresh. I just need a message to show up saying "success" and the database to update.
But when I hit submit, it doesn't update the database, and the success messages don't show up. I have checked this over and over. Am I calling them improperly? Please help!
function passData() {
//getting values from HTML
var title= $("#title").value;
var year= $("#year").value;
var director= $("#director").value;
var genre= $("#genre").value;
var runtime= $("#runtime").value;
if (title == '' || year == '' || director == '' || genre == '' || runtime == '') {
alert("Please fill all fields");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "insert_DVD.php",
data: {
title1: title,
year1: year,
director1: director,
genre1: genre,
runtime1: runtime},
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
<?php
//getting values from JS
$title = $_POST['title11'];
$year = $_POST['year1'];
$director = $_POST['director1'];
$genre = $_POST['genre1'];
$runtime = $_POST['runtime1'];
$title = addslashes($title);
$director = addslashes($director);
$year = addslashes($year);
$genre = addslashes($genre);
$runtime = addslashes($runtime);
//connecting to server
$connection = mysql_pconnect($host,$user,$pass);
if (!($db = mysql_select_db($database)))
echo "<p> could not connect to database </p><br>");
//open database
if(!mysql_select_db($table,$db))
echo "<p> could not open collection database </p><br>");
//insert query
if (isset($_POST['title1'])) {
$query = "INSERT INTO `collection` (`title` , `year` , `director` , `genre` , `runtime` ) VALUES ('$title', '$year', '$director', '$genre', '$runtime')";
if(!$results = mysql_query($query, $db){
print("<p> could not excute query </p>");
} else {
echo "succuess";
}
}else {
echo "Something went wrong";
}
//close connection
mysql_close($connection);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="refreshForm.js"></script>
<link rel="stylesheet" href="webpage.css">
</head>
<body class="subStyle">
<form id="form" method="post">
If there is more than one director, seperate with comma.
<table border=0>
<tr>
<th>Movie Title</th>
<th>Year Made</th>
<th>Director</th>
<th>Genre</th>
<th>Runtime(Minutes)</th>
</tr>
<tr>
<td><input type=text name="title" id="title" maxlength=100 size=30></td>
<td><input type=text name="year" id="year" maxlength=4 size=10></td>
<td><input type=text name="director" id="director" maxlength=100 size=30></td>
<td><input type=text name="genre" id="genre" maxlength=20 size=20></td>
<td><input type=text name="runtime" id="runtime" maxlength=4 size=20></td>
</tr>
<tr><td>
<input type="submit" id="submit" name="submit" onclick="passData();" value="Update Database"></td></tr>
</table>
</form>
<div id="results">
<!-- All data will display here -->
</div>
</body>
</html>
My answer is based on the assumption that your Javascript function passData() is inside the file refreshForm.js.
There's a few issues here.
The Javascript function cannot be called because it's declared in another file
Each .js file has its own scope. The easiest way to fix this is to assign the passData() function to the global scope. This is the quickest way but do note that there are much better ways like export.
Calling the Javascript function from onclick does not prevent the entire form from submitting
Your function gets called, but then Javascript continues with the form submission since that's the default behaviour of a submit button. You will need some way to tell Javascript to prevent this default action from happening.
// refreshForm.js
window.passData = function (e) { // <-- Assign passData to the global scope
e.preventDefault(); // <-- Tell Javascript to prevent the default action of form submission
//getting values from HTML
var title= $("#title").value;
var year= $("#year").value;
var director= $("#director").value;
var genre= $("#genre").value;
var runtime= $("#runtime").value;
if (title == '' || year == '' || director == '' || genre == '' || runtime == '') {
alert("Please fill all fields");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "insert_DVD.php",
data: {
title1: title,
year1: year,
director1: director,
genre1: genre,
runtime1: runtime},
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
};
Next, change your onclick handler in your HTML to onclick="return passData(event);"
Related
I have one form with two submit buttons.
<form id="manageSalesForm" name="manageSalesForm" method="post" action="<?php echo BASE_URL?>includes/functions/sales_functions.php">
PROCEED button should submit data to the database (This works)
<input type="submit" name="btnProceed" id="btnProceed" value="PROCEED" onclick="document.getElementById('txtSubTotal').value = '';"/>
PRINT & PROCEED button should submit data to the database and print the page (How to do this?)
<input type="submit" name="btnPrintReceipt" id="btnPrintReceipt" value="PRINT & PROCEED" formaction="<?php echo BASE_URL?>reports/salesreceipt2.php" formtarget="_blank"/>
salesreceipt2.php has the fpdf code and should open this in a new tab/window.
Same form has another button with button type
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); resetform();">ADD</button>
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();
//refresh/update the sub total value when adding
$("#sub_total_div").load(location.href + " #sub_total_div");
}
});
}
}
I tried several ways, but I couldn't make this work. Appreciate your help.
First of all change all of your submits to button. Like this :
<input type="button" value="Proceed" onclick="proceed(false)" />
<input type="button" value="Proceed & Print" onclick="proceed(true)" />
Now add this Javascript :
function print(recordId){
window.open( 'baseurl/salesreceipt2.php?id='+recordId , '_blank');
}
function proceed(printIt){
// your ajax operations..
$.ajax({
//your ajax configs..
success:function(response){
//your ajax success things..
if(printIt == true){
print(response.lastId); // Pass last Id of record to print function if your salesreceipt2.php always prints last record that's unnecessary.
}
}
});
}
It works easy. If printIt ( your first parameter ) is true it calls print with LastRecordId ( if your salesreceipt2.php always prints last record passing it is unnecessary as i said. ) if not you should return a JSON Response that contains inserted ID. So this inserted id will be passed to salesreceipt2.php file by ?id
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);
Please, can somebody publish a mistakes corrected and tested code for my problem?
Program does - 22.php has the form. When the user enter and click Submit button, the result should be taken from 23.php and displayed in div on 22.php
I already tried solutions below and none of them solve my problem;
1) I changed to: $("#testform").submit(function(event){
2) I included "return false;" at the end to prevent it to actually submit the form and reload the page.
3) clear my browser cache
I can see what happen the program with my computer;
1) I do not get error message after I click submit.
2) I can see the tab of the page reloads quickly and the entered text fields are cleared.
3) No error message or result shows.
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').val(data);
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
you don't need to change your php code
try submit form with submit event ...
$("#testform").submit(function(event){
use `dataType:json`; in your ajax ..
yourData =$(this).serialize();
Your php
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
$data['name']= 'welcome '.$name;
$data ['age']= 'you are '.$age;
print_r(json_encode($data));exit;
}
?>
Now In Your Success function
var message = data.name + ' ' + data.age;
$('#result').html(message );
You are sending myname and checking name(isset($_POST['name']) in php.
don't use .value() use .html() for data rendering. and console log the data and see whats request and response using firebug.
Can you try this one?
To be changed
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
and
$('#result').html(data); // here html()
the code becomes
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
alert('Submitted');
}else{
return false;
}
}
});
});
});
Try formatting your post data like this inside your ajax function.
$.ajax({
type:'POST',
data : {
myname: myname
myage: myage
}
...
}
EDIT
Try removing the ; in
return false;
}
};
to
return false;
}
}
You can change at both end ajax and php:
#PHP:
You can check for correct posted data which is myname and myage not name and age.
<?php
if ( isset($_POST['myname'])) { // was the form submitted?
echo "Welcome ". $_POST["myname"] . "<br>";
echo "You are ". $_POST["myage"] . "years old<br>";
}
?>
or #Ajax:
yourData ='name='+myname+'&age='+myage;
//--------^^^^^^----------^^^^----change these to work without changing php
Just noticed the #result is an div element. So, you can't use .val() but use .html(), .append() etc:
$('#result').html(data);
This is my first project where I used Jquery.
There are two pages 1. listofleaders.php 2. leadersprofile.php
On First Page i.e. listofleaders.php
I have a input text box, where user enters leaders name and I used jQuery code to transfer textbox values to leaderprofile.php page
<html>
<head>
<script>
function ls()
{
var leaderdetails = "leaderprofile.php?lname="+$("#gopal").val();
$.get(leaderdetails, function( data ) {
//alert(leaderdetails);
location.href = "leaderprofile.php";
});
}
</script>
</head>
<body>
<input type="text" id="gopal" name="t" placeholder="Start Typing" size="50" />
<button onclick="ls();" type="button">Go!</button><br><br>
</body>
</html>
On Second Page leadersprofile.php I have written this,
<?php
include "admin/includes/dbconfig.php";
$lname = $_GET['lname'];
echo $lname;
?>
But on second page i.e. leaderprofile.php it is showing me error
Undefined index : lname
Am I Correct to this approach ?
Where I am Wrong ?
Hope you Understand.
So I am having a guess here at what you are trying to achieve based on your problem description.
If you want to send a <input> value to another page, you better use a classic POST request (without the need of evolving jQuery):
<form method="post" action="leadersprofile.php">
<input type="text" name="lname"/>
<button type="submit">Send</button>
</form>
And in leadersprofile.php:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['lname'])) {
$lname = $_POST['lname'];
var_dump($lname); // outputs whatever the user input was
}
Now if you want to send the data to leadersprofile.php without reloading the page, you are looking for an Ajax request (XmlHttpRequest).
jQuery(function($) {
$('form').on('submit', function(e) {
e.preventDefault(); // prevents default behavior that is submitting the form
$.ajax({
method: 'post', // can be also 'get'
url: 'leadersprofile.php',
data: {lname: $('input').val() },
success: function(html) {
$('div').html(html); // place whataver was printed in leadesrprofile.php into a div
},
error: function(r) { // fire if HTTP status code != 200
console.log(r);
}
});
});
});
You seem to be using JQuery correctly. The Javascript to extract the value and the send the GET request should be working.
Your misunderstanding lies in how you check if the PHP file has received the request. This redirect
location.href = "leaderprofile.php";
Will not provide you any information about the GET request that you just made. Instead you can try:
location.href = "leaderprofile.php?lname=" + $("#gopal").val()
To verify that your PHP and Javascript is performing as expected. If you see the values that you expect then I believe you have confirmed two things:
successfully extracted the correct value from the textbox
GET request is succeeding, and the success callback is being invoked
I understand your question.Try the following codes.
listofleaders.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td></td>
<td><button id="submit">Submit</button></td>
</tr>
</table>
</form>
<script src = "jquery.js"></script>
<script src = "leader.js"></script>
</body>
</html>
When submit button is click, leader.js file will get the value of text box.
leader.js
$(document).ready(function() {
$('#submit').on('click', function(){
var name = $('#name').val();
$.ajax({
url:'leaderprofile.php',
type:'POST',
data:{'name':name},
success:function(data){
}
});
});
});
Now, this leader.js file will send the name key to liderprofile.php.
After that php file witt return the data(name) to js file..and the js file will alert name.
leaderprofile.php
<?php
$name = $_POST['name'];
echo $name;
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.