If checkbox is checked in php - php

I have use the following code
order.php
<script type="text/javascript">
function processForm() {
$.ajax( {
type: 'POST',
url: 'ajax.php',
data: { checked_box : $('input:checkbox:checked').val()},
success: function(data) {
$('#results').html(data);
}
} );
}
</script>
<input type="checkbox" name="checked_box" value="1" onclick="processForm()">
And ajax.php
<?php
include "config.php";
$checkbox = intval($_POST['checked_box']);
echo $checkbox;
if($checkbox == 1){
$Query="SELECT * FROM `order` ORDER BY sl_no DESC";
}else{
$Query="SELECT * FROM `order` ORDER BY sl_no ASC";
}
$result=mysql_query($Query);
echo $Query;
while($row = mysql_fetch_object($result)) {
?>
It works good but when I unchecked then error showing
Notice: Undefined index: checked_box in C:\xampp\htdocs\website\admin\ajax.php on line 24
How to avoid this error???

It is not an error, but a notice. You will get that kind of notices if you try to access non initialized variables. Just initialize it with the appropiate start value.
The tricky part in your code is that you assume you'll get the value of the checkbox because it is included in the form. But it happens that the checkbox are not sent UNLESS THEY HAVE BEEN CHECKED.

Instead of intval($_POST['checked_box']); use isset($_POST['checked_box']); to make sure the value exists at all.
After that you can use intval if you still need that value.

It's all because only checked checkboxes are included in POST request. So you need to check if your checked_box key exists to figure out checkbox was set or not:
if(isset($_POST['checked_box']) {
.. set
} else {
.. not set
}

I have a select dropdown box
<select name="status" id="status" onchange="changeStatus()">
<option value="step_1">step_1</option>
<option value="step_2">step_2</option>
<option value="step_3">step_3</option>
<option value="step_4">step_4</option>
</select>
And my javascript
<script>
function changeStatus() {
$('select.changeStatus').change(function(){
$.ajax({
type: 'POST',
url: 'update_status.php',
data: {changeStatus: $('select.changeStatus').val()},
dataType: 'html'
});
});
});
</script>
So I want the value selected from the select dropdown box send to the php file(update_status.php)

Related

How to implement a code igniter country and cities select that countries determines the city?

I am new to Ajax and JavaScript
I have a similar problem with my selects that depends on the other select but don't know where it is going wrong?
This is my Controller code- that passes the member_id to the model and it is supposed to return data back to the view selected.
public function getStates() {
$this->load->model('ReferenceModel');
$this->load->model('DailyModel');
$this->load->model('MembersModel');
$this->load->model('FundsModel');
$postData = array('member_id' => $this->request->getPost('member_id'));
$dataa = $this->FundsModel->getStates($postData);
echo json_encode($dataa);
}```
This is my AJAX Request Code
<script type='text/javascript'>
// baseURL variable
var baseURL= "<?php echo base_url();?>";
$(document).ready(function(){
// City change
$('#member_id').change(function(){
var member_id = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>Historic/getStates',
method: 'post',
data: {member_id: member_id},
dataType: 'json',
success: function(response){
// Remove options
$('#id').find('Select Member').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#id').append('<option value="'+dataa['id']+'">'+dataa['fund']+'</option>');
});
}
});
});
});
</script>
Model
public function getStates($postData){
$sql = 'SELECT * FROM vw_funds_summary WHERE member_id =' .$postData['member_id'] ;
$query = $this->db->query($sql);
return $query;
}```
And My HTML Codes
<select id="member_id" name="country" class="form-control">
<option>Select Member</option>
<?php
for ($i=0;$i<$fMembers->num_rows();$i++){
echo "<option value='".$fMembers->row($i)->member_id."'>".$fMembers->row($i)->member_name."</option>";}
?>
</select>
<select class="form-control" id="id">
<option>Select Fund</option>
</select>
What is really wrong with my Code?
I have a view of both the funds and the members, that are giving the results as shown in the attached picture.
Or is there another way to do it without having to use AJAX?

Submit Form and return values using HTML / JQuery / PHP

need your help for this ... My homepage have 3 divs, #Header, #Content, #Footer. All the other pages are being opened inside the #Content div. In one of those pages I have a form with two select lists and one submit button. Just want to click the button and then return another page into the #Content div, showing the values that I select before. Like this:
The origin is: 1
The destiny is: 1
But this code returns the following ...
Notice: Undefined variable: origin in ...
Notice: Undefined variable: destiny in ...
Note: This is working if I don't open the page inside the #Content div
my Html:
<form id="myform" name="myform" action="values.php" method="POST">
<select id="origin" name="origin">
<option value="0" selected>-- Select Origin --</option>
<option value="1">Portugal</option></select>
<select id="destiny" name="destiny">
<option value="0" selected>-- Select Destiny --</option>
<option value="1">Lisboa</option></select>
<input id="btSubmit" name="btSubmit" type="submit" value="search!">
</form>
my Function:
$(document).ready(function(){
$('#btSubmit').click(function(e) {
e.preventDefault();
var url = $('#myform').attr('action');
var method = $('#myform').attr('method');
$.ajax({
type: method,
url: url,
data: $('#myform').serialize(),
success: $('#content').load(url)
});
});
});
my values.php page:
<?php
if(isset($_POST['origin']) || isset($_POST['destiny']))
{
$origin = $_POST['origin'];
$destiny = $_POST['destiny'];
}
echo 'The origin is:' . $origin . '<br>';
echo 'The destiny is:' . $destiny;
?>
You should not call load again - you have already called it essentially with $.ajax and received the results. So you need just display them in the content:
success: function (data) {
$('#content').html(data);
}
You should use success callback function correctly. Accept response in callback method and set it in your div
success: function (data) {
$('#content').html(data);
}
Additionally, You should perform your operation with form submit event.
$('form#myform').on('submit', function (e) {
instead of
$('#btSubmit').click(function(e) {
As Andrei mentioned you have to use
success: function (data) {
$('#content').html(data);
}
because calling success: $('#content').load(url) triggers a new GET request. When GET request reaches php code $_POST is not set and your variables are not initialized so you get the message from php:
Notice: Undefined variable: origin in

Send and recieve parameter with ajax using jquery

I'm tring to send and receive parameters with AJAX without any sucess
First I choose AREA and than the CITIES in this area.
Can you please tell me what do I do wrong?
Client side:
<script>
$(document).ready(function(){
$("#first").click(
function(){
var area_id=$("#area_id").val();
$.ajax({
type: "POST",
url: "recs.php",
data: "area_id="+area_id,
cache:false,
success:
function(data){
$("#second").html(data.message);
}
});
return false;
});
});
</script>
<form method="post" action="tosomewhere.php">
<select id="first" name="area_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="second" name="section"> </select>
</form>
Server Side:
$areaID = $_POST['area_id'];
$second_option = "";
$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = $areaID ORDER BY id ASC");
while($index = mysql_fetch_array($query2))
{
$id = $index['id'];
$name = $index['name'];
$second_option .= "<option value='$id'>$name</option>";
}
echo $second_option;
exit;
Thank you in advanced
After editing:
I changed the code to something even simpler:
Client side:
<script>
$(document).ready(function(){
$("#first").click(
function(){
var area_id=$("#area_id").val();
$.ajax({
type: "GET",
url: "recs.php",
data: "area_id="+area_id,
cache:false,
success:
function(data){
$("#second").html(data);
}
});
return false;
});
});
</script>
<form method="post" action="tosomewhere.php">
<select id="first" name="area_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="second"></div>
</form>
Server side:
some text
I'm still not getting the string into
change
$("#second").html(data.message);
to
$("#second").html(data);
<script>
$(document).ready(function(){
$("#first").click(function(){
var area_id=$("#area_id").val();
$("#second").load('tosomewhere.php?area_id=' + area_id);
return false;
});
});
</script>
Changed the jquery a bit. Using GET.
Also the script has changed:
$areaID = (int) $_GET['area_id'];
$second_option = "";
$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = '$areaID' ORDER BY id ASC");
if (mysql_num_rows($query2) > 0){
while($index = mysql_fetch_array($query2)){
$second_option .= '<option value="'.$index['id'].'">'.$index['name'].'</option>';
}
echo $second_option;
} else {
echo 'No result!';
}
die();
Added (int) before $_GET as a pre-security measurement.
Add this parameter to the ajax function
dataType:'text'
You need to debug code where is actually fault whether you ajax call is actually initialize.
i: check whether value properly fetch in "area_id" js variable
alert(area_id);
ii: if it ok check whether data proper returned from server scriptinog
alert(data); or alert(data.message);
iii: for testing whether you receive data properly, just send out test script.
echo "sample text";
exit;
or try to send data in json format
die('{"message" : "sample text"}');
If all three steps working, then there should be fault in data access script.
If you are not getting output in ajax try using firebug to check what is actually happening in sending request and getting response.

Ajax calling PDO function in PHP class to update a page

I have a list of files and a drop down box, I'd like the user to be able to filter them by various categories etc.
I have a php class that has the function for creating the sql query and returning the result. I'd very much like to do this via ajax to prevent a refresh.
I'm stuck and was hoping for some help.
The problem is that I don't know what to do next. This is pretty new to me but still plenty foreign. If the ajax call can be run onKeyUp from the select then even better.
Thank you for any help:
the HTML:
<div>
<form action="" method="post" name="orderBy">
<label for="orderBy" id="orderBy">Order By:</label>
<select>
<option class="orderByOption" value="newest">Newest First</option>
<option class="orderByOption" value="oldest">Oldest First</option>
<option class="orderByOption" value="cat">Category</option>
<option class="orderByOption" value="alpha">Aphabetical</option>
<option class="orderByOption" value="fileType">Filetype</option>
</select>
<label> </label>
<input type="submit" class="orderByTrainingButton" name="submit" value="Go!"/>
</form>
</div>
The Ajax:
//form for changing the ordering of items in training all docs
$(function(){
$(".orderByTrainingButton").click(function(){
//validate and process
//get vlaue
var option = $(".orderByOption").val();
var params = {option: option};
$.ajax({
type: "POST",
url: "../trainingOrderByAjax.php",
data: params,
dataType: 'json',
success: function(data){
if(data.success == true){
//aaaannnd. stuck/
}else{
// shouldn't ge there...I hope.
}
},
error: function( error ) {
console.log(error);
}
});
});
});
The php the ajax will call:
<?php
include_once('core/init.php');
if($_POST){
$orderBy = $_POST['orderByOption'];
if($training->getAlFilesOrderBy($orderBy)){
$data['success'] = true;
}else{
$data['success'] = false;
}
echo json_encode($data);
}
To start with ordering by desc or asc would be great. I can then build on that.
Something like this.
PHP:
if($results = $training->getAlFilesOrderBy($orderBy)){
$data['success'] = true;
$data['results'] = $results;
}else{
$data['success'] = false;
}
echo json_encode($data);
}
JS:
if(data.success){
var results = data.results;
for (var i = 0; i < results.length; i++) {
// do something with results[i]
}
}else{
// shouldn't ge there...I hope.
}
Change your AJAX error handler to:
error: function(xhr, status, errorMsg) {
console.log("AJAX error: " + errorMsg);
}

Get Values Associated with First Dropdown Chosen

<select style="width:300px;" id="FirstDD" name="userListingCategory" onchange="FillSelectTwo(this.options[this.selectedIndex].value)">
<option disabled="disabled">Category...</option>
<?php while($row = $sth2->fetch(PDO::FETCH_ASSOC))
{echo "<option value=". $row['catID'] . ">" .$row['catName']."</option>";}
unset($sth2);
$selectedOptionInCategory = $row['catID'];
?>
</select>
<select style="width:340px;" id="SecDD" name="userListingSCategory">
<option disabled="disabled">Sub-Category...</option>
<?php while($row = $sth3->fetch(PDO::FETCH_ASSOC))
{echo "<option value=". $row['scatID'] . ">" .$row['scatName']."</option>";}
unset($sth3);
?>
When a 'category' is selected like:
I want the subcategories associated with that first category chosen to show up.
I'm running the following SQL:
SELECT scatID, scatName
FROM Category C, SubCategory SC
WHERE C.catID = SC.catID
AND C.catID = '$selectedOptionInCategory'
JS:
function FillSelectTwo(id) { //what is this id for?
$.ajax({
url: 'index.php',
dataType: 'text',
success: function(data) {
$('#SecDD').find('option').remove().end().append(data);
},
error:function(jxhr){
console.log(jxhr.responseText);
}
});
}
Problem I get
When I test this code out, I selected a category like Baby, then the subcategory box clears the first 'disabled' option value, but then its an empty set from there and I can't selected any of the values that the SQL would return upon selecting a category.
What it looks like:
javascript ssems to be fine but i doubt if the ajax call is going out in the first place
see in the firebug or developer tools(for chrome) to confirm that the ajax call is made to index.php
also remove the options in the success callback so if the ajax fails the select remains intact and make an error callback to trace errors
function FillSelectTwo(id) { //what is this id for?
$.ajax({
url: 'index.php',
dataType: 'text',
success: function(data) {
$('#SecDD').find('option').remove().end().append(data);
},
error:function(jxhr){
console.log(jxhr.responseText);
}
});
}
P.S. the is a ' missing at the end of your url may be that is causing the problem
It is pretty easy...
First you need to make a PHP-function that return the subcats. I often make a ajax.php file. In this I have differents functions that being called on in diffs. $_GET.
The PHP viewer for the result.
switch($_GET['ajax'])
{
case 'subcats' :
$sql = [YOUR SQL QUERY];
if(mysql_num_rows($sql)!=0)
{
echo "[";
$i = 0;
while($r = mysql_fetch_array($sql))
{
if($i!=0)
{echo ',';}
echo "['$r[scatID]','$r[ScatName]']";
}
echo ']';
}
break;
}
The jQuery for the ajax request
$.post("ajax.php?ajax=subcats",'id='+$("#FirstDD").val(), function(result){
var print = '';
if(result)
{
for(i = 0;i<result.length; i++)
{
var current = result[i];
print += '<option value="'+ current[0] +'">'+ current[1] +'</option>';
}
$('#SecDD').html(print);
$('#SecDD').removeAttr('disabled');
}
});
It might be some errors (ondemand writings is not my strongest side ^_^), but try to inteplate this to your script. And comment if you meet any errors...
**
EDIT
**
But in your case, when I now understand it. In the subcats options element, add the attr. rel, in wich you write the parent id.
Afterwords, you add this jQuery code:
$('#FirstDD').change(function(){
var thisId = $(this).attr('id');
$('#SecDD option').addAttr('disabled','disabled');
$('#SecDD option[rel="'+thisId+'"]').removeAttr('disabled');
});

Categories