Reputation: 59
Got some problems with Ajax calls. My program makes dynamic fields based on user choice. For example, if the user selects "dvd" the Javascript creates a field to add DVD size, or if furniture is selected it creates 3 fields to add hwl parameters.
Posting from HTML forms works great but I can't get data to get from jQuery to PHP. Could you help me to post DVD parameter with Ajax?
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submitted'] ) ) {
ob_clean();
include('connect_mysql.php');
$message='error';
if( isset( $_POST['price'], $_POST['sku'], $_POST['name'], $_POST['prtype'], $_POST['dvd'], $_POST['book'], $_POST['furnh'], $_POST['furnw'], $_POST['furnl'] ) ) {
$sku = $_POST['sku'];
$name = $_POST['name'];
$price = $_POST['price'];
$prtype = $_POST['prtype'];
$dvd = $_POST['dvd'];
$book = $_POST['book'];
$furnh = $_POST['furnh'];
$furnw = $_POST['furnw'];
$furnl = $_POST['furnl'];
$sql = "insert into `people` ( `sku`, `name`, `price`, `prtype`, `dvd`, `book`, `furnh`, `furnw`, `furnl`) values (?,?,?,?,?,?,?,?,?)";
$stmt=$dbcon->prepare( $sql );
if( $stmt ){
$stmt->bind_param('sssssssss',$sku,$name,$price,$prtype,$dvd,$book,$furnh,$furnw,$furnl);
$result=$stmt->execute();
$stmt->free_result();
$message=$result ? '1 record added' : 'Something went wrong';
} else {
$message='Problem preparing sql statement';
}
}
exit( $message );
}
?>
<html>
<head>
<title>Submit your data</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<h1>Insert your data</h1>
<form method="post" action="training.php">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>New Product</legend>
<label>ID:<input type="text" name="sku"/></label>
<label>Name:<input type="text" name="name"/></label>
<label>Price:<input type="text" name="price"/></label>
<label>Product Type</label>
<select id="Product_Type" name="prtype">
<option style="display: none;" selected>Select product type</option>
<option value="Dvd">DVD</option>
<option value="Book">Book</option>
<option value="Furniture">Furniture</option>
</select>
</fieldset>
<br />
<input type="submit" class="button" name="add" value="add new product"/>
<script>
var $input_DVD = $('<input id="dvd" input type="text" name="dvd" class="input" placeholder="Size"/>');
var $input_Book = $('<input id="book" input type="text" name="book" class="input" placeholder="Weight"/>');
var $input_FurnitureHeight = $('<input id="furnh" input type="text" class="input" name="furnh" placeholder="Height"/>');
var $input_FurnitureWidth = $('<input id="furnw" input type="text" class="input" name="furnw" placeholder="Width"/>');
var $input_FurnitureLength = $('<input id="furnl" input type="text" class="input" name="furnl" placeholder="Length"/>');
$(document).ready(function() {
/*
The issue was the generation of a new form with the specific values that
you are trying to use for adding a new record. The new form was never
included in the data sent so the logic tests were failing and thus no records
were ever inserted.
Some simple debugging using the console would have helped you identify this
though there still remains the issue of how you deal with form submissions
when the selected item in the `select` menu is other than DVD!!!
Using the code here you ought to be able to work that part out now - this works
for DVD as the selected item
Rather than insert a new form, it now inserts a new fieldset within the original
form.
*/
$('select#Product_Type').on('change', function() {
$('#container').remove();//<!---- just use the ID
var val = $(this).val()
$container = $('<fieldset id="container" ></fieldset>');// <!---- fieldset, not form
if (val == "Dvd")$input_DVD.appendTo($container);
if (val == "Book")$input_Book.appendTo($container);
if (val == "Furniture"){
$input_FurnitureHeight.appendTo($container);
$input_FurnitureWidth.appendTo($container);
$input_FurnitureLength.appendTo($container);
}
$container.insertAfter($(this)).val();
})
});
$(function() {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : location.href, // <!---- POST to same page
data : $(this).serialize(), // <!---- send all data from this form
dataType : 'json',
encode : true
})
.done(function(data) {
$('#result').html( data );
})
});
});
</script>
</form>
<div id='result'></div>
</body>
</html>
P.S Edited code , added code to add all options
Upvotes: 0
Views: 1148
Reputation: 33823
As it is quite different to the original answer and because the question has mutated a little I felt it might be clearer to add as another answer. Because the original question just revolved around the dvd
being added a rethink was required to accomodate other columns and data for the insert statement. The following has not been tested but replaces the original ajax handling php code.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submitted'] ) ) {
ob_clean();
/* my test db conn */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$dbcon = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
#include('connect_mysql.php');
$message='error';
if( isset( $_POST['price'], $_POST['sku'], $_POST['name'], $_POST['prtype'] ) ) {
/* Do some filtering of the POSTed variables */
$args=array(
'sku' => FILTER_SANITIZE_STRING,
'name' => FILTER_SANITIZE_STRING,
'price' => array(
'filter' => FILTER_SANITIZE_NUMBER_FLOAT,
'flags' => FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND
),
'prtype' => FILTER_SANITIZE_STRING,
'dvd' => FILTER_SANITIZE_STRING,
'book' => FILTER_SANITIZE_STRING,
'furnh' => FILTER_SANITIZE_STRING,
'furnw' => FILTER_SANITIZE_STRING,
'furnl' => FILTER_SANITIZE_STRING
);
$_POST=filter_input_array( INPUT_POST, $args );
/* extract the POST data into variables */
extract( $_POST );
/* a one-for-all query, insert empty strings where suitable */
$sql = "insert into `people` ( `sku`, `name`, `price`, `prtype`, `dvd`, `book`, `furnh`, `furnw`, `furnl` ) values (?,?,?,?,?,?,?,?,?)";
$stmt= $dbcon->prepare( $sql );
if( $stmt ){
$stmt->bind_param('ssdssssss', $sku, $name, $price, $prtype, $dvd, $book, $furnh, $furnw, $furnl );
if( !empty( $_POST['dvd'] ) ){
/* dvd only: set empty values for other parameters/vars */
$book = $furnh = $funw = $furnl = '';
} elseif( !empty( $_POST['book'] ) ){
/* books: set empty values for other parameters/vars */
$dvd = $furnh = $funw = $furnl = '';
} elseif( isset( $_POST['furnw'],$_POST['furnl'],$_POST['furnh'] ) ){
/* furniture: set empty values for other parameters/vars */
$book = $dvd = '';
}
$result=$stmt->execute();
$stmt->free_result();
$message=$result ? '1 record added' : 'Something went wrong';
} else {
$message='Problem preparing sql statement';
}
exit( $message );
}
}
?>
<html>
<head>
<title>Submit your data</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<h1>Insert your data</h1>
<form method="post" action="training.php">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>New Product</legend>
<label>ID:<input type="text" name="sku"/></label>
<label>Name:<input type="text" name="name"/></label>
<label>Price:<input type="text" name="price"/></label>
<label>Product Type</label>
<select id="Product_Type" name="prtype">
<option style="display: none;" selected>Select product type</option>
<option value="Dvd">DVD</option>
<option value="Book">Book</option>
<option value="Furniture">Furniture</option>
</select>
</fieldset>
<br />
<input type="submit" class="button" name="add" value="add new product"/>
<script>
var $input_DVD = $('<input id="dvd" input type="text" name="dvd" class="input" placeholder="Size"/>');
var $input_Book = $('<input id="book" input type="text" name="book" class="input" placeholder="Weight"/>');
var $input_FurnitureHeight = $('<input id="furnh" input type="text" class="input" name="furnh" placeholder="Height"/>');
var $input_FurnitureWidth = $('<input id="furnw" input type="text" class="input" name="furnw" placeholder="Width"/>');
var $input_FurnitureLength = $('<input id="furnl" input type="text" class="input" name="furnl" placeholder="Length"/>');
$(document).ready(function() {
/*
The issue was the generation of a new form with the specific values that
you are trying to use for adding a new record. The new form was never
included in the data sent so the logic tests were failing and thus no records
were ever inserted.
Some simple debugging using the console would have helped you identify this
though there still remains the issue of how you deal with form submissions
when the selected item in the `select` menu is other than DVD!!!
Using the code here you ought to be able to work that part out now - this works
for DVD as the selected item
Rather than insert a new form, it now inserts a new fieldset within the original
form.
*/
$('select#Product_Type').on('change', function() {
$('#container').remove();//<!---- just use the ID
var val = $(this).val()
$container = $('<fieldset id="container" ></fieldset>');// <!---- fieldset, not form
if (val == "Dvd")$input_DVD.appendTo($container);
if (val == "Book") $input_Book.appendTo($container);
if (val == "Furniture"){
$input_FurnitureHeight.appendTo($container);
$input_FurnitureWidth.appendTo($container);
$input_FurnitureLength.appendTo($container);
}
$container.insertAfter($(this)).val();
})
})
$(function() {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : location.href, // <!---- POST to same page
data : $(this).serialize(), // <!---- send all data from this form
dataType : 'json',
encode : true
})
.done(function(data) {
$('#result').html( data );
})
});
});
</script>
</form>
<div id='result'></div>
</body>
</html>
The db schema
mysql> describe people;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| sku | varchar(50) | YES | | NULL | |
| name | varchar(50) | YES | | NULL | |
| price | varchar(50) | YES | | NULL | |
| prtype | varchar(50) | YES | | NULL | |
| dvd | varchar(50) | YES | | NULL | |
| book | varchar(50) | YES | | NULL | |
| furnw | varchar(50) | YES | | NULL | |
| furnl | varchar(50) | YES | | NULL | |
| furnh | varchar(50) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
mysql> select * from people;
Empty set (0.00 sec)
mysql> select * from people;
+--------+--------------+-------+-----------+------+------+-------+-------+-------+
| sku | name | price | prtype | dvd | book | furnw | furnl | furnh |
+--------+--------------+-------+-----------+------+------+-------+-------+-------+
| 78459 | Geronimo | 0 | Dvd | 55 | | NULL | | |
| 123456 | pocahontas | 7845 | Book | | 5632 | NULL | | |
| 78 | chief wiggum | 0 | Furniture | | | 20 | 30 | 10 |
+--------+--------------+-------+-----------+------+------+-------+-------+-------+
Upvotes: 2
Reputation: 876
In You ajax call you are specifying dataTyp:'json'.Then you Should return json data from php. And Instead of exit you should use return.
return json_encode(@utf8_encode($message));
//or
return json_encode($message);
Upvotes: 1
Reputation: 33823
I have only briefly looked through the bulk of the html so may have missed errors in there but to POST, via AJAX, to the same file needs a little careful attention to the portion of code that handles the request. Without care your request would return the entire document - not usually the desired state of affairs so isolate that portion of code and surround with ob_clean()
to erase any html/other content before that point finish with exit
The callback function of the ajax request should process the response - in your case you wished to add to an element with id result
.
The sql previously was vulnerable to sql injection - so I show how to use a prepared statement below. None of the below has been tested so excuse syntax errors...
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submitted'] ) ) {
ob_clean();
include('connect_mysql.php');
$message='error';
if( isset( $_POST['price'], $_POST['sku'], $_POST['name'], $_POST['prtype'], $_POST['dvd'] ) ) {
$sku = $_POST['sku'];
$name = $_POST['name'];
$price = $_POST['price'];
$prtype = $_POST['prtype'];
$dvd = $_POST['dvd'];
$sql = "insert into `people` ( `sku`, `name`, `price`, `prtype`, `dvd`) values (?,?,?,?,?)";
$stmt=$dbcon->prepare( $sql );
if( $stmt ){
$stmt->bind_param('sssss',$sku,$name,$price,$prtype,$dvd );
$result=$stmt->execute();
$stmt->free_result();
$message=$result ? '1 record added' : 'Something went wrong';
} else {
$message='Problem preparing sql statement';
}
}
exit( $message );
}
?>
<html>
<head>
<title>Submit your data</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<h1>Insert your data</h1>
<form method="post" action="training.php">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>New Product</legend>
<label>ID:<input type="text" name="sku"/></label>
<label>Name:<input type="text" name="name"/></label>
<label>Price:<input type="text" name="price"/></label>
<label>Product Type</label>
<select id="Product_Type" name="prtype">
<option style="display: none;" selected>Select product type</option>
<option value="Dvd">DVD</option>
<option value="Book">Book</option>
<option value="Furniture">Furniture</option>
</select>
</fieldset>
<br />
<input type="submit" class="button" name="add" value="add new product"/>
<script>
var $input_DVD = $('<input id="dvd" input type="text" name="dvd" class="input" placeholder="Size"/>');
var $input_Book = $('<input id="book" input type="text" name="book" class="input" placeholder="Weight"/>');
var $input_FurnitureHeight = $('<input id="furnh" input type="text" class="input" name="furnh" placeholder="Height"/>');
var $input_FurnitureWidth = $('<input id="furnw" input type="text" class="input" name="furnw" placeholder="Width"/>');
var $input_FurnitureLength = $('<input id="furnl" input type="text" class="input" name="furnl" placeholder="Length"/>');
$(document).ready(function() {
/*
The issue was the generation of a new form with the specific values that
you are trying to use for adding a new record. The new form was never
included in the data sent so the logic tests were failing and thus no records
were ever inserted.
Some simple debugging using the console would have helped you identify this
though there still remains the issue of how you deal with form submissions
when the selected item in the `select` menu is other than DVD!!!
Using the code here you ought to be able to work that part out now - this works
for DVD as the selected item
Rather than insert a new form, it now inserts a new fieldset within the original
form.
*/
$('select#Product_Type').on('change', function() {
$('#container').remove();//<!---- just use the ID
var val = $(this).val()
$container = $('<fieldset id="container" ></fieldset>');// <!---- fieldset, not form
if (val == "Dvd")$input_DVD.appendTo($container);
if (val == "Book") $input_Book.appendTo($container);
if (val == "Furniture"){
$input_FurnitureHeight.appendTo($container);
$input_FurnitureWidth.appendTo($container);
$input_FurnitureLength.appendTo($container);
}
$container.insertAfter($(this)).val();
})
})
$(function() {
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : location.href, // <!---- POST to same page
data : $(this).serialize(), // <!---- send all data from this form
dataType : 'json',
encode : true
})
.done(function(data) {
$('#result').html( data );
})
});
});
</script>
</form>
<div id='result'></div>
</body>
</html>
Upvotes: 1
Reputation: 573
try this
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'training.php', // post to same file
data : $(this).serialize(),
dataType : 'json',
encode : true
})
.done(function(data) {
$('#result').html(data);
})
});
Upvotes: 3