how to send multiple checkbox data to PHP via jQuery - javascript

<form id="foo">
<input type="text" name="voucher" placeholder="voucher ID" class="bill_fillter"/>
<input type="text" name="voucher" placeholder="voucher ID" class="bill_fillter"/>
<input type="text" name="voucher" placeholder="voucher ID" class="bill_fillter"/>
</form>
This is my Jquery Code
<script>
$("#foo").submit(function(event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "ajax_receipt_sms.php",
type: "post",
data: values,
success: function(){
alert("success");
$("#result").html('Submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('There is error while submit');
}
});
});
</script>
ajax_receipt_sms.php
<?php
$viuchid = $_POST['voucher'];
$sql1="SELECT * from usertable;
$result1 = mysql_query ($sql1);
$row1 = mysql_fetch_array($result1)
$CHEQUE_NO = $row1['CHEQUE_NO'];
$cheqdate = $row1['CHEQUE_DATE'];
$mobile = $row1['mobile'];
$bank_name = $row1['name'];
$amt = $row1['Amount'];
// split "dd-mm-yyyy" into an array of three elements
$ddate = explode("-", $cheqdate);
// retrieve the values
$month = $ddate[1]; // mm
$day = $ddate[2]; // dd
$year = $ddate[0]; // yyyy
?>
<?php
$notify="Your message is successfully sent to:"."91".$mobile;
$message = "Dear Member, received with thanks Rs.".$amt. " by chq/cash dated " .$day.'-'.$month.'-'.$year. " drawn on " .$bank_name. "bank, from ".$_SESSION['socityname'].".";
$username = "xxx";
$password = "xxxxxx";
$sendername = "shoaib";
$url = "http://bulksms.mysmsmantra.com/WebSMS/SMSAPI.jsp?username=".$username."&password=".$password."&sendername=".$sendername."&mobileno=91".$mobile."&message=".urlencode($message);
// for sms send request
$ch=curl_init();
if($url)
curl_setopt($ch,CURLOPT_URL,$url);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
?>
how to send multiple checkbox data to PHP via jQuery and send sms to multiple user, when i add multiple number to input box , it should send Sms to all data to the number.

I also think need to use array like voucher[] in input element of type check box.

Related

How to pass the radio button value to other program and insert value into database using php and jquery

I have a form with multiple radio buttons. What i want to store the radio button values in database like 1 for "Yes" and 0 for "No". I am using couple of script a.php, b.php for the same, a.php will get the radio button values and pass to b.php as parameter. Then b.php insert into the database. The problem here is database field for button value always updating with 0. I tried to implement with javascript and some other php logic. But no luck. Also I have created other small script to test the radio value is printing properly which is working fine. The problem is I am not aware how to get proper value in "recommend" in b.php
I really appreciate your help.
a.php is like below:
<div id="result">
<label for="sel1">Would You recomend</label>
<div class="pull-left">
<input name='recommend' type='radio' value=1>Yes
<input name='recommend' type='radio' value=0>No
<button class="btn btn-primary btn-sm" id="submit" type="submit" value="submit">submit</button>
b.php
<?php
require_once './config.php';
$pid = intval($_POST["pid"]);
$uid = intval($_POST["uid"]);
$score = intval($_POST["score"]);
$recommend = intval($_POST["recommend"]);
$aResponse['error'] = FALSE;
$aResponse['message'] = '';
$aResponse['updated_rating'] = '';
$return_message = "";
$success = FALSE;
$sql = "INSERT INTO `tbl_product_rating` (`product_id`, `user_id`, `ratings_score`, `recommend_score`) VALUES "
. "( :pid, :uid, :score, :recommend)";
$stmt = $DB->prepare($sql);
try {
$stmt->bindValue(":pid", $pid);
$stmt->bindValue(":uid", $uid);
$stmt->bindValue(":score", $score);
$stmt->bindValue(":recommend", $recommend);
//$stmt->execute(':pid' => $pid, ':uid' => $uid, ':score' => $score, ':recommend' => $recommend));
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
$aResponse['message'] = "Your rating has been added successfully";
} else {
$aResponse['error'] = TRUE;
$aResponse['message'] = "There was a problem updating your rating. Try again later";
}
} catch (Exception $ex) {
$aResponse['error'] = TRUE;
$aResponse['message'] = $ex->getMessage();
}
if ($aResponse['error'] === FALSE) {
// now fetch the latest ratings for the product.
$sql = "SELECT count(*) as count, AVG(ratings_score) as score FROM `tbl_products_ratings` WHERE 1 AND product_id = :pid";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":pid", $pid);
$stmt->execute();
$products = $stmt->fetchAll();
if ($products[0]["count"] > 0) {
// update ratings
$aResponse['updated_rating'] = "Average rating <strong>" . round($products[0]["score"], 2) . "</strong> based on <strong>" . $products[0]["count"] . "</strong> users";
} else {
$aResponse['updated_rating'] = '<strong>Ratings: </strong>No ratings for this product';
}
} catch (Exception $ex) {
#echo $ex->getMessage();
}
}
echo json_encode($aResponse);
?>
Jquery which I am using in a.php to send radio button value to b.php:
<script>
$document.ready(function(){
$('input[type="radio"]').click(function(){
var recommend = $(this).val();
$.ajax({
url:"b.php",
method:"POST",
data:{recommend:recommend},
// data:{recommend:$('#recommend').val($("[type='radio'] :checked").val())},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
jquery to fetch pid,uid,score..
<script>
$(document).on('click', '#submit', function() {
<?php
if (!isset($USER_ID)) {
?>
alert("You need to have a account to rate?");
return false;
<?php } else { ?>
var score = $("#score").val();
if (score.length > 0) {
$("#rating_zone").html('processing...');
$.post("update_ratings.php", {
pid: "<?php echo $_GET["pid"]; ?>",
uid: "<?php echo $USER_ID; ?>",
score: score
}, function(data) {
if (!data.error) {
// success message
$("#avg_ratings").html(data.updated_rating);
$("#rating_zone").html(data.message).show();
} else {
// failure message
$("#rating_zone").html(data.message).show();
}
}, 'json'
);
} else {
alert("select the ratings.");
}
<?php } ?>
});
</script>
I can insert the value 1 if "YES" for radio button with the mentioned jquery but it's inserting 0 for other fields like product_id..etc.I want just one entry to be inserted in db with proper value of radio button along with other fields.I have provided the full code for insert (b.php) with ajax which passing value to b.php from a.php. Kindly suggest.
I want output in mysql like below:
ratings_id product_id user_id ratings_score recommend_score
1 17637 1 4 0
2 17638 2 2 1
How it's happening now:
ratings_id product_id user_id ratings_score recommend_score
3 0 0 0 1
6 17639 2 4 0
In your ajax that fires once a user clicks on a radio-button you are not sending the other values needed for insert (pid, uid, score). I suppose they are included in the half-shown form.
Assuming you have those inputs in your form
<input name="pid" id="pid">
<input name="uid" id="uid">
<input name="score" id="score">
EDIT: since you've now shown more code I updated the code below (to match how you send pid & uid in the normal form-submit).
you can add them to the data object with something like this:
data:{
recommend:recommend,
pid: "<?php echo $_GET["pid"]; ?>",
uid: "<?php echo $USER_ID; ?>",
score: $('#score').val(),
},
Also change the double-ids of #newsletter as the others have suggested.
Change id to class attribute.
<script type="text/javascript">
$(document).ready(function() {
$("input[type=radio]").click(function () {
var recommend = $(this).val();
console.log(recommend);
$.ajax({
url:"b.php",
method:"POST",
data:{
recommend:recommend
},
success: function(data){
//your code here
},
error: function (error) {
console.log(error);
}
});
});
});
</script>
<input name="recommend" class='newsletter' type='radio' value=1>Yes
<input name="recommend" class='newsletter' type='radio' value=0>No
Sample HTML:
<input type="radio" name="color" id="rdoColor" value="green" />Green<br />
<input type="radio" name="color" id="rdoColor" value="Blue" />Blue<br />
Sample JQuery Code:
$(document).on("click", "input[id=rdoColor]", function(){
$.post(serverPath+"/colorHandler.php", {action: "saveColor", color: $(this).val()}, function(data){
var response = $.parseJSON(data);
// use this response as u need
});
});
Sample PHP (colorHandler.php):
$jsonStr = "";
define('DB_SERVER', 'DBserver:port');
define('DB_NAME', 'DBName');
define('DB_USER', 'dbUser');
define('DB_PASS', 'dbPass');
try {
$dbCon = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASS);
$dbCon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO colorTable (colorName) VALUES (?)";
$stmt= $dbCon->prepare($sql);
$stmt->execute(array($_POST["color"]));
if( $dbCon->lastInsertId() ){
$jsonStr = '{
"status":"Success",
"Message":"Color Saved"
}';
echo $jsonStr;
}else{
$jsonStr = '{
"status":"Failure",
"Message":"Color was not Saved"
}';
echo $jsonStr;
}
}catch(PDOException $e){
$jsonStr = '{
"status":"Failure",
"Message":"Database server not found!"
}';
echo $jsonStr;
}

How, Right Click a <tr>, run php to retrieve data, display result in an alert?

I've read and tried many solutions, none are working. Here is my latest. As you can see all I'm trying to do is display an alert box on screen with the data retrieved from the MySQL using PHP.
My HTML looks like this:
...
<td $brbCols class=\"editCS1\" oncontextmenu=\"getLastLogin('$row[callsign]');return false;\" id=\"callsign:$row[recordID]\" style=\'text-transform:uppercase\'> $row[callsign] </td>
...
Right clicking on the above code runs this,
The getLastLogin javascript looks like this:
function getLastLogin() {
$('tr').on('contextmenu', 'td', function(e) { //Get td under tr and invoke on contextmenu
e.preventDefault(); //Prevent defaults'
var idparm = $(this).attr('id');
var arparm = idparm.split(":");
var id = arparm[1];
id = id.replace(/\s+/g, '');
var call = $(this).html();
call = call.replace(/\s+/g, '');
$.ajax({
type: "GET",
url: "getLastLogIn.php",
data: {call : call, id : id},
success: function(response) {
alert(response);
},
error: function() {
alert('Not OKay');
}
});
});
}
The PHP:
<?php
ini_set('display_errors',1);
error_reporting (E_ALL ^ E_NOTICE);
require_once "creddtls.php";
$call = $_POST['call'];
$id = $_POST['id'];
$sql2 = "SELECT recordID, id, Fname, Lname, grid, creds,
email, latitude, longitude, tactical, callsign, logdate, netID, activity
FROM NetLog
WHERE callsign = '$call'
ORDER BY netID DESC
LIMIT 1,1 " ;
$stmt2 = $db_found->prepare($sql2);
$stmt2->execute();
$result = $stmt2->fetch();
$recordID = $result[0]; $email = $result[6];
$id = $result[1]; $latitude = $result[7];
$Fname = $result[2]; $longitude = $result[8];
$Lname = $result[3]; $creds = $result[5];
$tactical = $result[9]; $grid = $result[4];
$callsign = $result[10]; $netID = $result[12];
$logdate = $result[11]; $activity = $result[13];
$msg = "<b>Last Check-in::</b>
<br>$callsign, $Fname $Lname
<br><b>eMail::</b>$email
<br><b>Was on::</b> $logdate
<br><b>Net ID::</b> $netID, $activity
<br><br>
$recordID
";
echo "$msg";
?>
You are trying to access the data passed via ajax with the wrong superglobal.
You are looking at POST data, but your ajax call is using GET
Change $_POST to $_GET
Wrong or not the code writes to the lli DIV. So I added $("#lli").modal(); to the Javascript to open it in a modal dialog.
All is now well.

Submit and fetch data without refreshing the page

I'm new to php and mySQL. I've created a webpage, it's essentially a noticeboard. The page has a form to submit content and the content is shown below instantaneously. The content appears when the submit button is pressed, but now if I wanted to submit content immediately after the form still displays the echo that says submission was successful. Could someone point me in right direction to get the page functioning in a way that users can submit content one after the other without refreshing the page? Any help is greatly appreciated. Apologies for the messy code.
This is my input code:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO db3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
This is my form:
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" placeholder="Name..." required autocomplete="off">
<input name = "email" type = "text"
id = "email" placeholder="example#gmail.com..." autocomplete="off">
<textarea name = "proposal" type = "textarea" maxlength="1000"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
This is my retrieval code:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, proposal FROM db3 ORDER BY ID DESC ';
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo
"<article>".
" <div class='id'> ID :{$row['id']} </div> ".
" <section> <p> {$row['proposal']} </p></section> ".
" <section class='name'><h3> {$row['name']} </h3></section> ".
"</article>"
;
}
mysql_close($conn);
?>
Use this code:
<script>
submitHandler: function(form) {
$.ajax({
url: '',
type: 'POST',
data: $("#submission").serialize(),
success: function() {
alert('submitted data: '$("#submission").serialize());
return false;
}
});
}
</script>
Please change the form line with this one:
<form name="submission" id="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
You can do this using AJAX
You will use javascript to send the data to a PHP script which will process it. The same script will return the new data that was just submitted so you can display it on the page.
An example would be
HTML
<form id="comment">
<input type="text" id="userInput" name="comment" placeholder="Tell us what you feel about this" />
<input type="submit" value="Submit" />
</form>
jQuery
<script>
$("#comment").on('submit', function(e) {
// Stop the form from being submitted the standard way
e.preventDefault();
// Put the user's input into a variable
var userInput = $('#userInput').val();
// Do some validation of the data if needed
// ...
// ...
// Perform AJAX request (a.k.a send the data to the server)
$.ajax({
// There are many parameters one can use here
// Browse the documentation to get familiar with the most useful ones
url: 'proccess.php', // The PHP script that will handle the request
type: 'POST', // This can be set to GET, but in this case we'd use POST
data: { comment: userInput }, // "comment" will result in $_POST['comment'], and userInput is the value of it
// If the script returns a 200 status (meaning the request was successful)
success: function(data) {
// The data variable will be the response from the PHP script
// Depending on what you are going to do with the data returned,
// you may want to ensure it is returned as valid JSON
},
error: function() {
// The request failed - So something here
// ...
// ...
}
});
});
</script>
PHP (process.php)
<?php
$data = $_POST['comment'];
// Do all you would normally do when submitting a post
// ...
// ...
// Now, upon successfully storing the data in your database,
// you can return something to the 'data' variable in the AJAX.success function
?>
Do some research on AJAX and jQuery. It's really fun to work with

php search function dynamically show results with javascript

I have the following php script which works fine, it uses the search term and compares it with a few different fields, then prints out the each record that matches:
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("table");
$search = isset($_POST['search']) ? $_POST['search'] : '';
$sql = mysql_query("select * from asset where
name like '%$search%' or
barcode like '%$search%' or
serial like '%$search%' ");
while ($row = mysql_fetch_array($sql)){
echo '<br/> Name: '.$row['name'];
echo '<br/> Barcode: '.$row['barcode'];
echo '<br/> Serial: '.$row['serial'];
}
?>
And this is the form that links to it:
<form action="http://localhost/test/search.php" method="post">
Search: <input type="text" name="search" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
I need to some how encode the results of the search so I can use them in a javascript function, then I can display them on the same html page below the form.
For that you have to use AJAX. You can send data back to the same page using JSON.
Advice - Don't use mysql_* functions since they are deprecated. Learn mysqli_* and try using that.
<script>
$(function(ev){
ev.preventDefault();
$("form").on('submit', function(){
var form = $(this);
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function(response){
if(response.success == TRUE)
{
// Search result found from json
// You have to loop through response.data to display it in your page
// Your single loop will have something like below -
var name = response.data.name;
var barcode = response.data.barcode;
var serial = response.data.serial;
$("#name").html(name);
$("#barcode").html(barcode);
$("#serial").html(serial);
}
else
{
// search result not found
}
});
});
});
</script>
On search.php
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("table");
$search = isset($_POST['search']) ? $_POST['search'] : '';
$sql = mysql_query("select * from asset where
name like '%$search%' or
barcode like '%$search%' or
serial like '%$search%' ");
$num = mysql_rows_nums($sql);
$json = array();
if($num > 0)
{
$json['success'] = TRUE;
while ($row = mysql_fetch_array($sql)){
$json['data']['name'] = $row['name'];
$json['data']['barcode'] = $row['barcode'];
$json['data']['serial'] = $row['serial'];
}
}
else
{
$json['success'] = FALSE;
}
return json_encode($json);
?>

How to Modify PHP/Jquery/Ajax script to have more than one form field posst

I have an php/Ajax/Jquery script that inserts a form field into MySQL and updates the page without refreshing when you hit submit. I would like the script to submit four form fields, instead of just one.
I have already updated the database table add_delete_record with 3 additional fields: balance, account_number and monthly, plus the content field that was already there.
Below is probably overkill of code because I only need to modify a few lines, but I figured this would answer all the questions.
This is the php & html page:
<div class="content_wrapper">
<ul id="responds">
<?php
//include db configuration file
include_once("config.php");
//MySQL query
$Result = mysql_query("SELECT id,content FROM add_delete_record");
//get all records from add_delete_record table
while($row = mysql_fetch_array($Result))
{
echo '<li id="item_'.$row["id"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $row["content"].'</li>';
}
//close db connection
mysql_close($connecDB);
?>
</ul>
<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea>
<button id="FormSubmit">Add record</button>
</div>
</div>
This is the php it posts to:
<?php
//include db configuration file
include_once("config.php");
//check $_POST["content_txt"] is not empty
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0)
{
//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')"))
{
//Record is successfully inserted, respond to ajax request
$my_id = mysql_insert_id(); //Get ID of last inserted record from MySQL
echo '<li id="item_'.$my_id.'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $contentToSave.'</li>';
mysql_close($connecDB);
}else{
//output error
//header('HTTP/1.1 500 '.mysql_error());
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
}
elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{//do we have a delete request? $_POST["recordToDelete"]
//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
if(!mysql_query("DELETE FROM add_delete_record WHERE id=".$idToDelete))
{
//If mysql delete record was unsuccessful, output error
header('HTTP/1.1 500 Could not delete record!');
exit();
}
mysql_close($connecDB);
}else{
//Output error
header('HTTP/1.1 500 Error occurred, Could not process request!');
exit();
}
?>
This is the JQuery
$(document).ready(function() {
//##### Add record when Add Record Button is clicked #########
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val()==="") //simple validation
{
alert("Please enter some text!");
return false;
}
var myData = "content_txt="+ $("#contentText").val(); //post variables
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field after successful submission
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
});
//##### Delete record when delete Button is clicked #########
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var clickedID = this.id.split("-"); //Split string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut("slow");
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
});
This is not my script so I thought I should also give a link to credit the author of it:
http://www.sanwebe.com/2012/04/ajax-add-delete-sql-records-jquery-php
i'm no php expert, but this should get you through:
First change the form area on the main page:
<div class="form_style">
<textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea><br/>
<input type="text" id="balance" /><br/>
<input type="text" id="acctNum" /><br/>
<input type="text" id="monthly" /><br/>
<button id="FormSubmit">Add record</button>
</div>
then your myData looks like this:
var myData = {
content_txt: $("#contentText").val(),
balance: $("#balance").val(),
acctNum: $("#acctNum").val(),
monthly: $("#monthly").val()
};
and later in the ajax response:
$("#contentText").val(''); //empty text field after successful submission
$("#balance").val('');
$("#acctNum").val('');
$("#monthly").val('');
and finally the PHP:
//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$content = filter_var($_POST['content_txt'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$balance = filter_var($_POST['balance'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$account = filter_var($_POST['acctNum'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$monthly = filter_var($_POST['monthly'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$qry= "INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')";
// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')"))
{
//Record is successfully inserted, respond to ajax request
$my_id = mysql_insert_id(); //Get ID of last inserted record from MySQL
echo '<li id="item_'.$my_id.'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $content.'</li>';
mysql_close($connecDB);
}else{
//output error
//header('HTTP/1.1 500 '.mysql_error());
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
var myData = {
content_txt: $("#contentText").val(),
other_var: $("#anotherField").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field after successful submission
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
This is an easier way to send several fields (notice the myData object). In PHP you can retrieve and save your new variable like this:
//check $_POST["content_txt"] is not empty
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0 && !empty($_POST["other_var"])) // !empty() checks that the variable is set and not empty
{
//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH
$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$otherVarToSave = filter_var($_POST["other_var"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
// Insert sanitize string in record
if(mysql_query("INSERT INTO add_delete_record(content, other) VALUES('".$contentToSave."', '".$otherVarToSave."')"))
{
Something like this:
var myData = "content_txt="+ $("#contentText").val()+"&other_value"+ $("#foo").val(); //post variables
In the php file:
$other_value = $_POST['other_value'];
UPDATE:
balance, account_number and monthly
JS:
var myData = "content_txt="+ $("#contentText").val()+"&balance"+ $("#balance").val();
myData = myData + "&account_number="+$('#acnum').val()+"&monthly="+$('#month').val();
PHP:
$content = filter_var($_POST['content_txt'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$balance = filter_var($_POST['balance'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$account = filter_var($_POST['account_num'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$monthly = filter_var($_POST['monthly'],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$qry= "INSERT INTO add_delete_record(content,balance,account,monthly) VALUES('".$content."','".$balance."','".$account."','".$monthly."')";
if(mysql_query($qry)){

Categories