My HTML+JS :
<head>
<script type="text/javascript">
function passList() {
var p=[];
$('input.first').each( function() {
if($(this).attr('checked')) {
p.push($(this).attr('rel'));
}
} );
$.ajax( {
url:'process.php',
type:'POST',
data: {list:p},
success: function(res) {
$("#result").html(res);
}
});
}
function passType() {
var q=[];
$('input.second').each( function() {
if($(this).attr('checked')) {
q.push($(this).attr('rel'));
}
} );
$.ajax( {
url:'process.php',
type:'POST',
data: {type:q},
success: function(res) {
$("#result").html(res);
}
});
}
</script>
</head>
<body>
<input type="checkbox" class="first" rel="list1" onclick="passList()">list1<br />
<input type="checkbox" class="first" rel="list2" onclick="passList()">list2<br />
<input type="checkbox" class="first" rel="list3" onclick="passList()">list3<br />
<input type="checkbox" class="first" rel="list4" onclick="passList()">list4<br />
<br><br><br>
<input type="checkbox" class="second" rel="type1" onclick="passType()">type1<br />
<input type="checkbox" class="second" rel="type2" onclick="passType()">type2<br />
<input type="checkbox" class="second" rel="type3" onclick="passType()">type3<br />
<br><br><br>
<div id="result"> </div>
</body>
I am able to get the value in the div "result" thru the following script :
if(isset($_POST['list']) && !isset($_POST['type'])) {
foreach ($_POST['list'] as $list) {
echo "this is $list<br />";
}
}
else if(!isset($_POST['list']) && isset($_POST['type'])) {
foreach ($_POST['type'] as $type) {
echo "type is : $type<br />";
}
}
else if(isset($_POST['list']) && isset($_POST['type'])) {
foreach ($_POST['list'] as $list) {
echo "Showing ads for $list<br />";
foreach ($_POST['type'] as $type) {
echo "type is : $type<br />";
}
}
}
But i get the value of either the list or the type.
I want to be able to get the value of both at the same time. I dont want to use a .
Please help.
Thank you.
Related
I want to display records based on the value of the combobox (dropdown list) using ajax. Display list of examinees based on the examdate. Help. I am a newbie in PHP and AJAX.
I want to display records based on the value of the combobox (dropdown list) using ajax. Display list of examinees based on the examdate. Help. I am a newbie in PHP and AJAX.
I want to display records based on the value of the combobox (dropdown list) using ajax. Display list of examinees based on the examdate. Help. I am a newbie in PHP and AJAX.
<?php
include 'configuration.php';
$queryselect = mysql_query("SELECT examdateno, examdate from tbl_examdate ORDER BY examdate DESC");
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="onclick edit jquery php, grid in php, onclick change text box in jquery, onclick edit table row, insert update delete using jquery ajax, simple php data grid" />
<meta name="description" content="This article is about simple grid system using PHP, jQuery. Insert a new record to the table using by normal Ajax PHP. It will show the editable textbox when user clicks on the label." />
<link rel="stylesheet" type="text/css" href="css/grid.css" />
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/component.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
// Function for load the grid
function LoadGrid(dte) {
var gridder = $('#as_gridder');
var UrlToPass = 'action=load';
var value = $('#examdate').val();
gridder.html('loading..');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass,
success: function (responseText) {
gridder.html(responseText);
}
});
}
// Seperate Function for datepiker() to save the value
function ForDatePiker(ThisElement) {
ThisElement.prev('span').html(ThisElement.val()).prop('title', ThisElement.val());
var UrlToPass = 'action=update&value=' + ThisElement.val() + '&crypto=' + ThisElement.prop('name');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass
});
}
LoadGrid(); // Load the grid on page loads
// Execute datepiker() for date fields
$("body").delegate("input[type=text].datepicker", "focusin", function () {
var ThisElement = $(this);
$(this).datepicker({
dateFormat: 'yy/mm/dd',
onSelect: function () {
setTimeout(ForDatePiker(ThisElement), 500);
}
});
});
// Show the text box on click
$('body').delegate('.editable', 'click', function () {
var ThisElement = $(this);
ThisElement.find('span').hide();
ThisElement.find('.gridder_input').show().focus();
});
// Pass and save the textbox values on blur function
$('body').delegate('.gridder_input', 'blur', function () {
var ThisElement = $(this);
ThisElement.hide();
ThisElement.prev('span').show().html($(this).val()).prop('title', $(this).val());
var UrlToPass = 'action=update&value=' + ThisElement.val() + '&crypto=' + ThisElement.prop('name');
if (ThisElement.hasClass('datepicker')) {
return false;
}
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass
});
});
// Same as the above blur() when user hits the 'Enter' key
$('body').delegate('.gridder_input', 'keypress', function (e) {
if (e.keyCode == '13') {
var ThisElement = $(this);
ThisElement.hide();
ThisElement.prev('span').show().html($(this).val()).prop('title', $(this).val());
var UrlToPass = 'action=update&value=' + ThisElement.val() + '&crypto=' + ThisElement.prop('name');
if (ThisElement.hasClass('datepicker')) {
return false;
}
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass
});
}
});
// Function for delete the record
$('body').delegate('.gridder_delete', 'click', function () {
var conf = confirm('Are you sure want to delete this record?');
if (!conf) {
return false;
}
var ThisElement = $(this);
var UrlToPass = 'action=delete&value=' + ThisElement.attr('href');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass,
success: function () {
LoadGrid();
}
});
return false;
});
// Add new record
// Add new record when the table is empty
$('body').delegate('.gridder_insert', 'click', function () {
$('#norecords').hide();
$('#addnew').slideDown();
return false;
});
// Add new record when the table in non-empty
$('body').delegate('.gridder_addnew', 'click', function () {
$('html, body').animate({scrollTop: $('.as_gridder').offset().top}, 250); // Scroll to top gridder table
$('#addnew').slideDown();
return false;
});
// Cancel the insertion
$('body').delegate('.gridder_cancel', 'click', function () {
LoadGrid()
return false;
});
// For datepiker
$("body").delegate(".gridder_add.datepiker", "focusin", function () {
var ThisElement = $(this);
$(this).datepicker({
dateFormat: 'yy/mm/dd'
});
});
// Pass the values to ajax page to add the values
$('body').delegate('#gridder_addrecord', 'click', function () {
// Do insert vaidation here
if ($('#fname').val() == '') {
$('#fname').focus();
alert('Enter the First Name');
return false;
}
if ($('#lname').val() == '') {
$('#lname').focus();
alert('Enter the Last Name');
return false;
}
if ($('#age').val() == '') {
$('#age').focus();
alert('Enter the Age');
return false;
}
if ($('#profession').val() == '') {
$('#profession').focus();
alert('Select the Profession');
return false;
}
if ($('#date').val() == '') {
$('#date').focus();
alert('Select the Date');
return false;
}
// Pass the form data to the ajax page
var data = $('#gridder_addform').serialize();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: data,
success: function () {
LoadGrid();
}
});
return false;
});
});
</script>
</head>
<body>
<header>
<img src="images/qes_logob.png" alt="logo">
<button class="hamburger">☰</button>
<button class="cross">˟</button>
</header>
<div class="menu">
<ul>
<a href="encodeinterview.php">
<li>Encode Grades</li>
</a>
<a href="viewinterview.php">
<li>View Grades</li>
</a>
<a href="../index.php">
<li>Logout</li>
</a>
</ul>
</div>
<script>
$(function () {
$(".cross").hide();
$(".menu").hide();
$(".hamburger").click(function () {
$(".menu").slideToggle("slow", function () {
$(".hamburger").hide();
$(".cross").show();
});
});
$(".cross").click(function () {
$(".menu").slideToggle("slow", function () {
$(".cross").hide();
$(".hamburger").show();
});
});
});
</script>
<form>
<h1>Exam Dates</>
<select name="examdate" id="examDate" onchange="LoadGrid(this.value)">
<option>Select Exam Date</option>
<?php
while ($row = mysql_fetch_array($queryselect)) {
echo "<option value={$row['examdateno']}>{$row['examdate']}</option>\n";
}
?>
</select>
</form>
<div class="as_wrapper">
<div class="as_grid_container">
<div class="as_gridder" id="as_gridder"></div> <!-- GRID LOADER -->
</div>
</div>
</body>
</html>
AJAX
<?php
include 'configuration.php';
include 'functions/functions.php';
$action = $_REQUEST['action'];
$q = intval($_POST['q']);
switch($action) {
case "load":
$query = mysql_query("select s.sno, s.fname, s.lname, s.examdate, s.interviewgrade, s.gwa from student s inner join tbl_examdate e on s.examdate=e.examdate where e.examdateno=$q");
$count = mysql_num_rows($query);
if($count > 0) {
while($fetch = mysql_fetch_array($query)) {
$record[] = $fetch;
}
}
$department = array('Software Architect', 'Inventor', 'Programmer', 'Entrepreneur');
?>
<table class="as_gridder_table">
<tr class="grid_header">
<td><div class="grid_heading">Sno</div></td>
<td><div class="grid_heading">First Name</div></td>
<td><div class="grid_heading">Last Name</div></td>
<td><div class="grid_heading">Age</div></td>
<td><div class="grid_heading">Profession</div></td>
<td><div class="grid_heading">Date</div></td>
<td><div class="grid_heading">Actions</div></td>
</tr>
<tr id="addnew">
<td> </td>
<td colspan="6">
<form id="gridder_addform" method="post">
<input type="hidden" name="action" value="addnew" />
<table width="100%">
<tr>
<td><input type="text" name="fname" id="fname" class="gridder_add" /></td>
<td><input type="text" name="lname" id="lname" class="gridder_add" /></td>
<td><input type="text" name="age" id="age" class="gridder_add" /></td>
<td><select name="profession" id="profession" class="gridder_add select">
<option value="">SELECT</option>
<?php foreach($department as $departments) { ?>
<option value="<?php echo $departments; ?>"><?php echo $departments; ?></option>
<?php } ?>
</select></td>
<td><input type="text" name="date" id="date" class="gridder_add datepiker" /></td>
<td>
<input type="submit" id="gridder_addrecord" value="" class="gridder_addrecord_button" title="Add" />
<img src="images/delete.png" alt="Cancel" title="Cancel" /></td>
</tr>
</table>
</form>
</tr>
<?php
if($count <= 0) {
?>
<tr id="norecords">
<td colspan="7" align="center">No records found <img src="images/insert.png" alt="Add New" title="Add New" /></td>
</tr>
<?php } else {
$i = 0;
foreach($record as $records) {
$i = $i + 1;
?>
<tr class="<?php if($i%2 == 0) { echo 'even'; } else { echo 'odd'; } ?>">
<td><div class="grid_content sno"><span><?php echo $i; ?></span></div></td>
<td><div class="grid_content editable"><span><?php echo $records['fname']; ?></span><input type="text" class="gridder_input" name="<?php echo encrypt("fname|".$records['id']); ?>" value="<?php echo $records['fname']; ?>" /></div></td>
<td><div class="grid_content editable"><span><?php echo $records['lname']; ?></span><input type="text" class="gridder_input" name="<?php echo encrypt("lname|".$records['id']); ?>" value="<?php echo $records['lname']; ?>" /></div></td>
<td><div class="grid_content editable"><span><?php echo $records['age']; ?></span><input type="text" class="gridder_input" name="<?php echo encrypt("age|".$records['id']); ?>" value="<?php echo $records['age']; ?>" /></div></td>
<td><div class="grid_content editable"><span><?php echo $records['profession']; ?></span>
<select class="gridder_input select" name="<?php echo encrypt("profession|".$records['id']); ?>">
<?php foreach($department as $departments) { ?>
<option value="<?php echo $departments; ?>" <?php if($departments == $records['profession']) { echo 'selected="selected"'; } ?>><?php echo $departments; ?></option>
<?php } ?>
</select>
</div></td>
<td><div class="grid_content editable"><span><?php echo date("Y/m/d", strtotime($records['posted_date'])); ?></span><input type="text" class="gridder_input datepicker" name="<?php echo encrypt("posted_date|".$records['id']); ?>" value="<?php echo date("Y/m/d", strtotime($records['posted_date'])); ?>" /></div></td>
<td>
<img src="images/insert.png" alt="Add New" title="Add New" />
<img src="images/delete.png" alt="Delete" title="Delete" /></td>
</tr>
<?php
}
}
?>
</table>
<?php
break;
case "addnew":
$fname = isset($_POST['fname']) ? mysql_real_escape_string($_POST['fname']) : '';
$lname = isset($_POST['lname']) ? mysql_real_escape_string($_POST['lname']) : '';
$age = isset($_POST['age']) ? mysql_real_escape_string($_POST['age']) : '';
$profession = isset($_POST['profession']) ? mysql_real_escape_string($_POST['profession']) : '';
$date = isset($_POST['date']) ? mysql_real_escape_string($_POST['date']) : '';
mysql_query("INSERT INTO `grid` (fname, lname, age, profession, posted_date) VALUES ('$fname', '$lname', '$age', '$profession', '$date')");
break;
case "update":
$value = $_POST['value'];
$crypto = decrypt($_POST['crypto']);
$explode = explode('|', $crypto);
$columnName = $explode[0];
$rowId = $explode[1];
if($columnName == 'posted_date') { // Check the column is 'date', if yes convert it to date format
$datevalue = $value;
$value = date('Y-m-d', strtotime($datevalue));
}
$query = mysql_query("UPDATE `grid` SET `$columnName` = '$value' WHERE id = '$rowId' ");
break;
case "delete":
$value = decrypt($_POST['value']);
$query = mysql_query("DELETE FROM `grid` WHERE id = '$value' ");
break;
}
?>
You are not passing exam date in your ajax, i e q, but you are using that in $_POST, so pass the value from ajax to your file.
function LoadGrid(dte) {
var gridder = $('#as_gridder');
var UrlToPass = 'action=load';
var value = $('#examdate').val();
gridder.html('loading..');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {action:"load",q:dte}, <----- this line.
success: function (responseText) {
gridder.html(responseText);
}
});
}
I want to show the output of polldemo1.php on poll.php page. But it is not happening. It is showing the poll.php page's form again as output.
Please correct it.Also if anyone can explain me php with ajax, it would be really nice
poll.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
</head>
<body>
<h3>SIG Polls</h3>
<form method="POST" id="myform" class="myform" >
C/C++
<input type="checkbox" name="vote[]" value="0" />
<br />
Java
<input type="checkbox" name="vote[]" value="1" />
<br />
Matlab
<input type="checkbox" name="vote[]" value="2" />
<br />
C#/.NET
<input type="checkbox" name="vote[]" value="3" />
<br />
PHOTOSHOP
<input type="checkbox" name="vote[]" value="4" />
<br />
CCNA
<input type="checkbox" name="vote[]" value="5" />
<br />
BASIC ELECTRONICS
<input type="checkbox" name="vote[]" value="6" />
<br />
<input type="submit" name="submit" value="vote" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
<script type="text/javascript">
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'polldemo1.php',
data: dataString,
success: function(data){
$('#myResponse').text(data);
}
});
return false;
}
</script>
</body>
</html>
polldemo1.php
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
</head>
<?php
echo "hello";
//error_reporting(0);
if(isset($_POST['submit']))
{
/*if (isset($_COOKIE["ieeepoll"]))
{
echo "<script>alert('You have already voted'); location.href='poll.php';</script>";
} */
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$c = $array[0];
$java = $array[1];
$matlab = $array[2];
$net = $array[3];
$ph = $array[4];
$ccna = $array[5];
$be = $array[6];
foreach($_POST["vote"] as $vote)
{
if ($vote == 0)
{
$c = $c + 1;
}
if ($vote == 1)
{
$java = $java + 1;
}
if ($vote == 2)
{
$matlab = $matlab + 1;
}
if ($vote == 3)
{
$net = $net + 1;
}
if ($vote == 4)
{
$ph = $ph + 1;
}
if ($vote == 5)
{
$ccna = $ccna + 1;
}
if ($vote == 6)
{
$be = $be + 1;
}
}
//insert votes to txt file
$insert = $c."||".$java."||".$matlab."||".$net."||".$ph."||".$ccna."||".$be;
file_put_contents($filename,$insert);
echo $be;
}
?>
Add onsubmit event in for html form attribute as following
<form method="POST" id="myform" class="myform" onsubmit="return false" >
You can manage above thing by jQuery also, just need to modify your javascript code something like this.
$("#myform").on('submit', function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'polldemo1.php',
data: $("#myform").serialize(),
success: function (data, status) {
//do whatever you want to do
},
error: function (err) {
//do wahtever you want to do
}
});
});
//OR
$("#myform").on('submit', function (event) {
event.preventDefault();
submitForm();
});
Also you don't need to keep any html attribute in you php script. Remove all html tags from that script.
try this it should help you.it will display the content of the file on poll.php on submit of form.
poll.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
</head>
<body>
<h3>SIG Polls</h3>
<form method="POST" id="myform" class="myform" >
C/C++
<input type="checkbox" name="vote[]" value="0" />
<br />
Java
<input type="checkbox" name="vote[]" value="1" />
<br />
Matlab
<input type="checkbox" name="vote[]" value="2" />
<br />
C#/.NET
<input type="checkbox" name="vote[]" value="3" />
<br />
PHOTOSHOP
<input type="checkbox" name="vote[]" value="4" />
<br />
CCNA
<input type="checkbox" name="vote[]" value="5" />
<br />
BASIC ELECTRONICS
<input type="checkbox" name="vote[]" value="6" />
<br />
<input type="submit" name="submit" value="vote" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
<script type="text/javascript">
function submitForm() {
var dataString = $("#myform").serialize();
$.ajax({
type:'POST',
url:'index.php',
data: dataString,
success: function(data){
$('#myResponse').text(data);
}
});
return false;
}
</script>
</body>
</html>
polldemo1.php
<?php
echo "hello";
//error_reporting(0);
if(isset($_POST))// do not check for submit here it won't go with post
{
/*if (isset($_COOKIE["ieeepoll"]))
{
echo "<script>alert('You have already voted'); location.href='poll.php';</script>";
} */
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
//put content in array
$array = explode("||", $content[0]);
$c = $array[0];
$java = $array[1];
$matlab = $array[2];
$net = $array[3];
$ph = $array[4];
$ccna = $array[5];
$be = $array[6];
foreach($_POST["vote"] as $vote)
{
if ($vote == 0)
{
$c = $c + 1;
}
if ($vote == 1)
{
$java = $java + 1;
}
if ($vote == 2)
{
$matlab = $matlab + 1;
}
if ($vote == 3)
{
$net = $net + 1;
}
if ($vote == 4)
{
$ph = $ph + 1;
}
if ($vote == 5)
{
$ccna = $ccna + 1;
}
if ($vote == 6)
{
$be = $be + 1;
}
}
//insert votes to txt file
$insert = $c."||".$java."||".$matlab."||".$net."||".$ph."||".$ccna."||".$be;
file_put_contents($filename,$insert);
echo $insert;
}
?>
Here is my PHP code:
<?php if (isset($mod['display']) && ($mod['display'] == "1")) { ?>
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" checked="checked" onclick="checkbox_click(this);" />
<?php } else { ?>
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" onclick="checkbox_click(this);" />
<?php } ?>
jQuery:
function checkbox_click(current) {
if($(current).is(':checked')) {
// do stuff....
} else {
// do stuff....
}
}
In the above code, when $mod['display'] is true, the checkbox is checked but it does not invoke checkbox_click() function. I tried onchange= instead of onclick= but it does not seem to have any effect. I need to keep the onclick or onchange in the field.
Try to use prop function for this,
Also you don't need to call function, you can create it by using jquery.on() function like,
$(function(){
$(document).on('click','.display_checkbox',function(){
if($(this).prop('checked')) {
// do stuff....
} else {
// do stuff....
}
});
});
And then remove onclick="checkbox_click(this);" from your html checkbox element
Updated
To initialize it on document ready
$(function(){
$('.display_checkbox').each(function(){
if($(this).prop('checked')) {
// do stuff....
} else {
// do stuff....
}
});
});
Read on() and prop()
Try this:
<?php if (isset($mod['display']) && ($mod['display'] == "1")) { ?>
<input class="display_checkbox selectedcheckbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" checked="checked" onclick="checkbox_click(this);" />
<?php } else { ?>
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" onclick="checkbox_click(this);" />
<?php } ?>
jQuery:
$(document).ready(function(){
var obj = $(".selectedcheckbox");
var found = obj.length;
if(found == 1)
{
checkbox_click(obj);
}
});
function checkbox_click(current) {
if($(current).is(':checked')) {
// do stuff....
} else {
// do stuff....
}
}
If you want function to be executed after page load, and also be axecuted every time checkbox state is changed you should do it this way:
<?php if (isset($mod['display']) && ($mod['display'] == "1")) { ?>
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" checked="checked" onclick="checkbox_click(this);" />
<?php } else { ?>
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" onclick="checkbox_click(this);" />
<?php } ?>
and in script:
function checkbox_click(current) {
if($(current).is(':checked')) {
// do stuff....
} else {
// do stuff....
}
}
$(function(){
$('.display_checkbox').each(function(){
checkbox_click($(this));
});
});
Also, I wouldn't do it that way. in this case, you should use onchange event binding.
Optimal solution i think would be:
<input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" <?php if (isset($mod['display']) && ($mod['display'] == "1")) { ?>checked="checked"<?php } ?> />
and javascript should look like this:
$(function(){
$('.display_checkbox').change(function(){
if($(this).is(':checked')) {
// do stuff....
} else {
// do stuff....
}
});
$('.display_checkbox').each(function(){
$(this).change();
});
});
I have a form with some php to validate and insert in the database on submit and the form opens in colorbox.
So far so good. What I'm trying to do is to close colorbox and refresh a div on success.
I guess I need to pass a response to ajax from php if everything OK, close the colorbox with something like setTimeout($.fn.colorbox.close,1000); and refresh the div, but I'm stuck because I'm new in ajax.
I'll appreciate any help here.
Here is my ajax:
jQuery(function(){
jQuery('.cbox-form').colorbox({maxWidth: '75%', onComplete: function(){
cbox_submit();
}});
});
function cbox_submit()
{
jQuery("#pre-process").submit(function(){
jQuery.post(
jQuery(this).attr('action'),
jQuery(this).serialize(),
function(data){
jQuery().colorbox({html: data, onComplete: function(){
cbox_submit();
}});
}
);
return false;
});
}
form php code:
<?php
error_reporting(-1);
include "conf/config.php";
if(isset($_REQUEST['rid'])){$rid=safe($_REQUEST['rid']);}
if(isset($_REQUEST['pid'])){$pid=safe($_REQUEST['pid']);}
$msg = '';
if (!$_SESSION['rest_id']) $_SESSION['rest_id']=$rid; //change to redirect
$session_id=session_id();
if(isset($_REQUEST['submit'])){
if(isset($_POST['opta'])){
$opta=safe($_POST['opta']);
$extraso = implode(',',array_values( array_filter($_POST['opta']) ));
}
if (array_search("", $_POST['opt']) !== false)
{
$msg = "Please select all accessories!";
}else{
$extrasm = implode(',',array_values( array_filter($_POST['opt']) ));
if ($_POST['opt'] && isset($_POST['opta'])) {$extras= $extrasm .",". $extraso;}
if ($_POST['opt'] && !isset($_POST['opta'])) {$extras= $extrasm;}
if (!$_POST['opt'] && isset($_POST['opta'])) {$extras= $extraso;}
$sql['session_id'] = $session_id;
$sql['rest_id'] = $_POST['rid'];
$sql['prod_id'] = $_POST['pid'];
$sql['extras'] = $extras;
$sql['added_date'] = Date("Y-m-d H:i:s");
$newId=insert_sql("cart",$sql);
}
}
?>
<form id="pre-process" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div style="background-color:#FFF; padding:20px;">
<?=$msg;?>
<?php
$name = getSqlField("SELECT name FROM products WHERE resid=".$_SESSION['rest_id']." and id=".$pid."","name");
echo "<div style='color:#fff; background-color:#F00;padding:10px;' align='center'><h2>".$name."</h2></div><div style='background-color:#FFF; padding: 20px 70px 30px 70px; '>Please select accessories.<br><br>";
$getRss = mysql_query("SELECT * FROM optional_groups_product where prodid=".$pid." order by id asc");
while ($rsrw = #mysql_fetch_array($getRss)) {
$goptionals = getSqlField("SELECT goptionals FROM optionals_groups WHERE resid=".$_SESSION['rest_id']." and id=".$rsrw['goptid']."","goptionals");
$goptionals=explode(', ',($goptionals));
echo "<select name='opt[]' id='opt[]' style='width:220px;'>";
echo "<option value='' >Select Options</option>";
foreach($goptionals as $v)
{
$vname = mysql_query("SELECT * FROM optionals where id=".$v." LIMIT 0,1");
while ($rsgb = #mysql_fetch_array($vname)) {
$aa=$rsgb['optional'];
}
echo "<option value=".$v." >".$aa."</option>";
}
echo "</select>(required)<br>";
//}
}
$getRss = mysql_query("SELECT * FROM optional_product where prodid=".$pid."");
?>
<br><br>
<table border="0" cellpadding="0" cellspacing="0" >
<tr>
<td bgcolor="#EAFFEC">
<div style="width:440px; ">
<?php
while ($rssp = #mysql_fetch_array($getRss)) {
$optional=getSqlField("SELECT optional FROM optionals WHERE id=".$rssp['optid']."","optional");
$price=getSqlField("SELECT price FROM optionals WHERE id=".$rssp['optid']."","price");
?>
<div style="width:180px;background-color:#EAFFEC; float:left;padding:10px;""><input type="checkbox" name="opta[]" id="opta[]" value="<?=$rssp['optid']?>" /> <i><?=$optional?> [<?=CURRENCY?><?=$price?> ]</i> </div>
<?php } ?>
</div>
</td>
</tr></table>
<input type="hidden" name="rid" value="<?=$rid?>" />
<input type="hidden" name="pid" value="<?=$pid?>"/>
</div><input type="hidden" name="submit" /><input id='submit' class="CSSButton" style="width:120px; float:right;" name='submit' type='submit' value=' Continue ' /><br />
<br /><br />
</div>
</form>
I don't know colobox, but if I understand well what you are trying to do,
I would say your javascript should more look like this
function cbox_submit()
{
jQuery("#pre-process").submit(function(e) {
e.preventDefault(); // prevents the form to reload the page
jQuery.post(
jQuery(this).attr('action')
, jQuery(this).serialize()
, function(data) {
if (data['ok']) { // ok variable received in json
jQuery('#my_colorbox').colorbox.close(); // close the box
}
}
);
return false;
});
}
jQuery(function() {
jQuery('#my_colorbox').colorbox({
maxWidth: '75%'
, onComplete: cbox_submit // Bind the submit event when colorbox is loaded
});
});
You should separate at least your php script that does the post part.
And this php (called with jQuery(this).attr('action')) should return a json ok variable if successfull. Example:
<?php
# ... post part ...
# if success
ob_clean();
header('Content-type: application/json');
echo json_encode(array('ok' => true));
?>
I have a table with records from a database which is dynamically filled.
<table>
<tr>
<td>name
</td>
<td>surname
</td>
...
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['Name'];?>
</td>
<td><?php echo $row_Recordset1['Surname'];?>
</td>
...
<td align="center">
<form name="form" action="novi.php">
<input name="check" type="radio" value="da">Да
<input name="check" type="radio" value="ne">Не
<input type="hidden" id="id" value="<?php echo $row_Recordset1['id_korisnici'];?>">
<input class="button1"type="button" id="klik" value="Испрати"/>
</form>
</td>
</tr>
<?php } while($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</table>
And than I'm using J Query to create an AJAX call to another page which will run the query.
<script>
$('#klik').click(function() {
var check = $("input[name='check']:checked").val();
var id = $('#id').val();
if (check == "da")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik').prop('value', (data));
document.location.reload();
});
}
else if (check == "ne")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik').prop('value', (data));
document.location.reload();
});
}
else
{
$('#klik').prop('value', 'Грешка');
setTimeout("$('#klik').prop('value', '.')",500);
setTimeout("$('#klik').prop('value', '..')",1000);
setTimeout("$('#klik').prop('value', '...')",1500);
setTimeout("$('#klik').prop('value', 'Испрати')",2000);
}
});
This is working OK if there is only one row in the table.
What I don't know how to do is, to make the script store all the generated CHECKED radio buttons in an array or something, plus all the ID's of the records from the database and send them to another page where according to their ID's a query will update the database..
<?php
if ($_POST['id'] != NULL) {
if ($_POST['check'] == "da") {
$id = mysql_real_escape_string($_POST['id']);
$update = mysql_query("update korisnici set validacija = 1 where id_korisnici= '$id'");
if ($update === true) {
echo 'OK';
}else if ($update === false){
echo 'Error!!!';
}
}
elseif ($_POST['check'] == "ne")
{
$id = mysql_real_escape_string($_POST['id']);
$update = mysql_query("update korisnici set validacija = 2 where id_korisnici= '$id'");
if ($update === true) {
echo 'OK';
}
else if ($update === false){
echo 'Error!!!';
}
}
} else {
echo 'Error!!!';
}
?>
Thanks!
P.S. I'm a noob in JQuery and a beginner in PHP...
UPDATE:
I did change some things. And now the values are shown as I want, when I click the button without a selection I'm getting the error message in the ELSE part of the JQuery code in the proper button. But no matter which button I click (if the table is populated with 3 records from the database, there are 3 buttons) only the first row from the table is updated in the database.
<form name="form" action="novi.php">
<input name="check<?php echo $row_Recordset1['id_korisnici'];?>" type="radio" value="da">Да
<input name="check<?php echo $row_Recordset1['id_korisnici'];?>" type="radio" value="ne">Не
<input type="hidden" id="id" value="<?php echo $row_Recordset1['id_korisnici'];?>">
<input class="button1"type="button" id="klik<?php echo $row_Recordset1['id_korisnici'];?>" value="Испрати"/>
</form>
The JQuery:
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').click(function() {
var check = $("input[name='check<?php echo $row_Recordset1['id_korisnici'];?>']:checked").val();
var id = $('#id').val();
if (check == "da")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', (data));
document.location.reload();
});
}
else if (check == "ne")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', (data));
document.location.reload();
});
}
else
{
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', 'Error');
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '.')",500);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '..')",1000);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '...')",1500);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', 'Send')",2000);
}
});
Make each group of radio buttons have a unique name but the same class. Then you can iterate through them using jQuery:
var radioVals = new Array();
var i = 0;
$(".radioButtonClass:checked").each(function() {
radioVals[i] = $(this).val();
});
Then just pass the array in your ajax call.