I want to fetch value through jquery Ajax in PHP. but when I run below this code value is fetch properly but all value are joined together when fetching and together value print all field, but I want to print the separate value in the separate field. my code is below, please solve this problem
index.php
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<select name="Pro" onChange="my_validate_func()" id="pro_serv">
<option value=""></option>
<option value="" ><font size="-1">Add New Product</font></option>
<option value="Development"><font size="-1">Development</font></option>
<option value="Maintance"><font size="-1">Maintance</font></option>
</select>
<br />
<input type="text" name="desc" id="desc" value="" />
<br />
<input type="text" name="unitprice" id="unitprice" value="" />
<br /><input type="text" name="discount" />
<script type="text/javascript" src="bootstrap/jquery1.8.3jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var pro_serv = $('#pro_serv').val();
if ($('#pro_serv').val() != "" ) {
$.ajax({
type: "POST",
url: 'check.php',
data: { pro_serv: pro_serv},
success: function(response) {
$('#desc').val(response);
$('#unitprice').val(response);
$('#tax').val(response);
}
});
}
}
</script>
</body>
</html>
check.php
<?php
include('database/db.php');
$type=$_POST['pro_serv'];
$sql="Select * from product_service_details where type='$type'";
$result=mysql_query($sql);
if($dtset=mysql_fetch_array($result))
{
$desc=$dtset['desc'];
$unitprice=$dtset['unitprice'];
$tax=$dtset['tax'];
echo $desc;
echo $unitprice;
echo $tax;
}
?>
You need to use json_encode in php and in jquery you need to parse the response like below:
PHP:
<?php
include('database/db.php');
$type=$_POST['pro_serv'];
$sql="Select * from product_service_details where type='$type'";
$result=mysql_query($sql);
if($dtset=mysql_fetch_array($result))
{
echo json_encode($dtset);
}
JQuery:
$.ajax({
type: "POST",
url: 'check.php',
data: { pro_serv: pro_serv},
success: function(response) {
var res = $.parseJSON(response);
$('#desc').val(res.desc);
$('#unitprice').val(res.unitprice );
$('#tax').val(res.tax );
}
});
You can use a separates for separate values then use JS split function.
echo $desc ."-" . $unitprice ."-" .$tax;
In Js
var arr = response.split('-');
$('#desc').val(arr[0]);
$('#unitprice').val(arr[1]);
$('#tax').val(arr[2]);
in check.php
*echo $tax;* should be echo json_encode('tax'=>$tax);
and in index.php
$('#tax').val(response); can be $('#tax').val(response.tax);
Related
Here is my code of html, ajax and php. The value returned by selected is to be passed in php
I want to use these four selected value (bank, state, district and city) in text form (bank_name, state_name, district_name, city_name) in my php file to show the data based on these value. If I use $bank=$_POST['bank[1]']; it gives the bank_id and so on, not the bank_name which was selected
<?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Dynamic Dependent Select Box using jQuery and PHP</title>
<script type="text/javascript" src="../js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.8.17.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".state").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_district.php",
data: dataString,
cache: false,
success: function(html)
{
$(".district").html(html);
}
});
});
$(".state").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});
});
});
</script>
<style>
label
{
font-weight:bold;
padding:10px;
}
div
{
margin-top:100px;
}
select
{
width:200px;
height:35px;
}
</style>
</head>
<form name="frm_ifsc" method="post" action="show_ifsc.php">
<body>
<center>
<div>
<label>Bank:</label>
<select name="bank" class="bank">
<option selected="selected">--Select Bank--</option>
<?php
$stmt = $DB_con->prepare("SELECT * FROM tbl_banks");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['bank_id']; ?>"><?php echo $row['bank_name']; ?></option>
<?php
}
?>
</select>
<br>
<br>
<label>State:</label>
<select name="state" class="state">
<option selected="selected">--Select State--</option>
<?php
$stmt = $DB_con->prepare("SELECT * FROM tbl_state");
$stmt->execute();
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['state_id']; ?>"><?php echo $row['state_name']; ?></option>
<?php
}
?>
</select>
<br>
<br>
<label>District:</label> <select name="district" class="district">
<option selected="selected">--Select District--</option>
</select>
<br>
<br>
<label>City:</label> <select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
<br>
</div>
<br />
<br>
<input type="submit" name="submit" value="Search" class="btnRegister">
</center>
</form>
</body>
</html>
You can fix this a number of ways. I think the two easiest are:
Modify JavaScript to get option text:
var id = $( this ).html();
var dataString = "id=" + id;
Modify select HTML:
<option value="<?php echo $row['bank_name']; ?>"><?php echo $row['bank_name']; ?></option>
Good luck!
How can I get the results of the result.php into the welcome div using ajax or any other method to prevent loading a new page?
<div id="welcome">
<form action="result.php" method="post">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="">Anyplace</option>
.
.
.
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="">Anything</option>
.
.
.
</select>
<input type="submit" class="button" value="Ok Go!"/>
<input id="current" name="current" type="hidden"/>
</form>
</div>
If you are doing this through AJAX, then there is no need for the <form> codes. The <form> codes are only useful if you are posting to a different page and expecting the view to change/refresh anyways.
Also, using <form> codes in this example will cause the page to refresh (and values inserted by jQuery to be lost) for the additional bit with the "Set value for hidden field CURRENT" button. Not that it likely matters in your real world app, but just FYI.
Ajax goes in your javascript code, and looks like this:
$('#mySelect').change(function() {
var sel = $(this).val();
//alert('You picked: ' + sel);
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'theOption=' + sel,
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END dropdown change event
Note that the data ECHO 'd from the PHP file comes into your HTML document in the success function of the AJAX call, and must be dealt with there. So that's where you insert the received data into the DOM.
For example, suppose your HTML document has a DIV with the id="myDiv". To insert the data from PHP into the HTML document, replace the line: alert('Server-side response: ' + whatigot); with this:
$('#myDiv').html(whatIgot);
Presto! Your DIV now contains the data echoed from the PHP file.
Here is a working solution for your own example, using AJAX:
HTML MARKUP:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').on('click', function(e){
e.preventDefault(); //prevent default action
var ct = $('#city').val();
var dt = $('#date').val()
var ty = $('#type').val();
var curr = $('#current').val();
$.ajax({
url: 'result.php',
type: 'POST',
data: 'ct=' +ct+ '&dat=' +dt+ '&t=' +ty+ '&curr=' +curr,
success: function(response){
$('#welcome').html(response);
}
});
});
$('#mycurr').click(function(){
var resp = prompt("Please type something:","Your name");
$('#current').val(resp);
});
}); //END $(document).ready()
</script>
</head>
<body>
<div id="welcome">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="sumwhere">Anyplace</option>
<option value="anutherwhere">Another place</option>
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="sumthing">Anything</option>
<option value="anutherthing">Another thing</option>
</select>
<input type="submit" id="mybutt" class="button" value="Ok Go!"/>
<input type="submit" id="mycurr" class="button" value="Set value for hidden field CURRENT"/>
<input id="current" name="current" type="hidden"/>
</div>
</body>
</html>
PHP Processor file: result.php
$ct = $_POST['ct'];
$date = $_POST['dat'];
$typ = $_POST['t'];
$cu = $_POST['curr'];
if ($date == '') {
$date = 'Some other date';
}
$r = '<h1>Results sent from PHP</h1>';
$r .= 'Selected city is: [' .$ct. ']<br />';
$r .= 'Selected date is: [' .$date. ']<br />';
$r .= 'Selected type is: [' .$typ. ']<br />';
$r .= 'Hidden field #CURRENT is: [' .$cu. ']<br />';
$r .= '<h2>And that\'s all she wrote....</h2>';
echo $r;
You can do something like this using jQuery Ajax
Use following code inside your head tag or footer
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type='text/javascript>
$('document').ready(function(){ //after page load
$('.button').on('click', function(e){
e.preventDefault(); //prevent default action
$.ajax({
'url': 'result.php',
'type: 'POST',
'success': function(response){
$('#welcome').html(response);
}
});
});
});
</script>
valit's the action="result.php" who makes your page reload
You shloud try to give an id to your form, and using a simple ajax call :
$("#formId").submit(function() {
$.ajax({
url: 'result.php',
success: function(response) {
$("#welcome").setValue(response); // update the DIV
}
});
return false; // prevent form submitting
});
Cheers
I’m using below a simple Jquery code to call a PHP page and get the button information back in a div:
<head>
<script>
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
myPHPfile.php
<?php
if( $_REQUEST["selectedButtonValue"] )
{
$buttonPHP = $_REQUEST['selectedButtonValue'];
echo "Value button is ". $buttonPHP;
}
?>
How can I get the PHP information inside JavaScript, as follows:
alert(<?php echo('buttonPHP'); ?>);
Note: The following code shows the alert box message, but I can’t use it since I need the $buttonPHP value:
$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue}, function(data){ alert(data); });
I’ve tried $_SESSION in myPHPfile.php, and also all jQuery AJAX functions: load(), get(), post() and the ajax() method, none of them is giving the PHP value inside JavaScript.
I looked all over but I couldn’t find an answer.
You would be better with an $.ajax request. Don't echo the 'Value of button is' part, just echo the actual value. For example:
$.ajax({
url: "myPHPfile.php",
context: document.body
}).done(function(data) {
var buttonValue = data;
// Whatever you want to do with the data goes here.
});
See the jQuery docs http://api.jquery.com/jQuery.ajax/
Alternatively, if you are generating the page with PHP, just echo the PHP variable into the JavaScript
<script>
...
var buttonValue = "<?php echo $buttonPHP; ?>";
...
</script>
Encode it in JSON instead of trying to echo the data :
<?php
if( $_GET["selectedButtonValue"] )
{
$buttonPHP = $_GET['selectedButtonValue'];
header('Content-Type: application/json');
echo json_encode($buttonPHP);
}
?>
Then use jquery get json to grab the data
$.get('myPHPfile.php?selectedButtonValue='+buttonvalue, function(data){
console.log(data);
});
Try:
alert('<?php echo $buttonPHP; ?>');
As a temporary solution, you could quickly merge both into a dirty code like this:
index.php:
<?php
$buttonPHP = "10"; //Set up your default button variable
if( $_REQUEST["selectedButtonValue"] == 10 )
{
echo "Selected button value: 10"; //You can also print $_REQUEST["selectedButtonValue"] here directly, but what's the point if you can select it from DOM through jQuery?
exit;
} else if ($_REQUEST["selectedButtonValue"] == 20) {
echo "Selected button value: 20";
exit;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = <?php echo $buttonPHP ?>; //Duplicate default value from PHP to JS
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
</html>
index.php rendered in browser:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = 10; //Duplicate default value from PHP to JS
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv">Click the button to load results</div>
</body>
</html>
EDIT: Stored session
<?php
session_start();
if (isset($_REQUEST['selectedButtonValue'])) {
$_SESSION['selectedButtonValue'] = $_REQUEST['selectedButtonValue'];
echo $_REQUEST['selectedButtonValue'];
exit;
} else if (!isset($_SESSION['selectedButtonValue'])) {
$_SESSION['selectedButtonValue'] = 10;
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var buttonValue = <?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?>;
$(document).ready(function(){
$('#myButtons input:radio').change(function() {
var buttonValue = $("#myButtons input:radio:checked").val();
$("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
});
});
</script>
</head>
<body>
<div id="myButtons">
<input type="radio" name="category" value="10" />ButtonA
<input type="radio" name="category" value="20" />ButtonB
</div>
<div id="myDiv"><?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?></div>
</body>
</html>
Also make sure you filter the $_REQUEST variable, because as of now, it will print anything. See http://en.wikipedia.org/wiki/Cross-site_scripting for details.
i want to implement a dynamic drop down which will select , batch of students from first drop down and then the corresponding subjects as the options for second drop down ..
this is the code for my Page :
<head>
<link rel="stylesheet" type="text/css" media="all" href="jsDatePick_ltr.min.css" />
<script type="text/javascript" src="jsDatePick.min.1.3.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
window.onload = function(){
new JsDatePick({
useMode:2,
target:"inputField",
dateFormat:"%d-%M-%Y"
});
};
</script>
</head>
<?php
$dept =$_COOKIE[dept];
include_once("../Include/connectdb.php");
include_once("../Include/data_menu.php");
include_once '../Include/pagemaker.php';
?>
<script type="text/javascript">
$(document).ready(function()
{
$(".batch").change(function()
{
var id=$(this).val();
var dataString = 'year_join='+ id;
$.ajax
({
type: "POST",
url: "ajax_subject.php",
data: dataString,
cache: false,
success: function(html)
{
$(".subject").html(html);
}
});
});
});
</script>
</head>
<body>
<br><br><br><br><br>
<fieldset class="cbox"><legend>Batch</legend>
<form name="frm" action=<?php print "edit_attendencePHP_NEW.php"; ?> method="GET"
id="content">
<br><br>
<div style="margin:80px">
<label>Batch :</label> <select name="batch">
<option selected="selected">--Select Batch--</option>
<?php
$result = mysql_query("select distinct year_joining from student_profile
order by year_joining ")or die(mysql_error());
while($year = mysql_fetch_assoc($result)){
if($year[year_joining]!="" && $year[year_joining]>"2008"){
print "<OPTION value='$year[year_joining]'>$dept $year[year_joining]</OPTION>";
} }
?>
</select>
<label>Subject :</label> <select name="subject" class="subject">
<option selected="selected">--Choose Subject--</option>
</select>
Date :<input type="text" size="12" id="inputField" name="date"/>
<input class="bluebutton" type="submit" value="Go">
</form><br>
<label class="comment">select a batch frm the list and press "Go"</label>
</fieldset>
the second ajax page works fine ... as i tested that with ($_GET)
this is wat with $_GET[year_join] ( view source code ) shows ...
ajax_subject.php
<option value="ENGG.MATHS-I">ENGG.MATHS-I</option><option value="COMPUTER PROGRAMMING
LAB">COMPUTER PROGRAMMING LAB</option><option value="WORKSHOPS">WORKSHOPS</option>
<option value="ENGG.PHYSICS">ENGG.PHYSICS</option><option
value="ENGG.CHEMISTRY">ENGG.CHEMISTRY</option><option ...........
Everything else seems fine ..
Right now it looks like no change event, which leads to the AJAX request, is being fired because your batch select element does not have a class of batch, only a name of batch. That is what you intended with $(".batch").change(function(){} right? Once you change, I would put an alert or console log in your callback function just to make sure it is even firing.
I want to load data from a MySQL database to a PHP page using jQuery and JSON. When the user choose the name from the select box, it loads the person's data into the text field.
This is my HTML code (select)
<select name='name' id='name'>
<option value='1'>John</option>
<option value='2'>Marco</option>
<option value='3'>Charles</option>
</select>
The text field that I want to populate with the person data:
<input type='text' name='firstname' value='' id='firstname'/>
<input type='text' name='phonenum' value='' id='phonenum'/>
getpersonData.php
<?php
include('dbconfig.php');
$id = $_POST['id'];
$query = "select * from person where ID='$id'";
$result = mysql_query($query);
$data = mysql_fetch_array($result);
echo json_encode($data);
?>
The Ajax call:
$.ajax({
type: "POST",
async : false,
url: 'http://test.com/getpersonData.php',
dataType: 'json',
data : {
id : $("#id").val(),
},
success : function(data) {
//What to insert here?
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + " : " + textStatus + " : " + errorThrown);
}
});
What code should I use for the success function?
First, you should set your Content-type header right before you echo your json_encode in getpersonData.php:
header("Content-type: application/json");
echo json_encode($data);
In your success function you would do something like:
$("#firstname").val(data.firstname); //firstname is the key of the user's firstname from your mysql query
I'm guessing your DB column names here, but maybe something like this
$('#firstname').val(data.firstname);
$('#phonenum').val(data.phonenum);
getpersonData.php
<?php
include('dbconfig.php');
$id = $_POST['id'];
$query = "select * from person where ID='$id'";
$result = mysql_query($query);
$data = mysql_fetch_array($result);
header("Content-type: application/json");
echo json_encode($data); ?>
main file
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Load JSON data through jQuery and PHP </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
load_data($('#name').val());
$('#name').change(function(){
load_data($('#name').val());
});
});
function load_data(personid)
{
$.getJSON("getpersonData.php", {id: personid}, function(data){
$('#firstname').val(data['firstname']);
$('#phonenum').val(data['phonenum']);
});
}
</script>
</head>
<body>
<select name="name" id="name">
<option value='1'>John</option>
<option value='2'>Marco</option>
<option value='3'>Charles</option>
</select>
<input type='text' name='firstname' value='' id='firstname'/>
<input type='text' name='phonenum' value='' id='phonenum'/>
</body>
</html>