Getting the value of textbox - php

I have a select option, to get the value from this, I used jquery (please see below code). After I display the selected value in the textbox, I'm now having problem on how to get the value of textbox to process a such code. Even simply echo of the value is not working. What's the problem with the code? Please help. Thanks.
Select option:
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
Jquery:
$('#shiptype').change(function () {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
}
});
Text Field:
<input type='text' id='strkey' name='keyname' />
Display the value:
$key = $_POST['keyname'];
echo $key;

Please try this code :
HTML file contains this below code. File name test.html.
Form to submit your data.
<form id="frm_post">
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
<input type="text" name="name" id="strkey">
<input id="btn_post" type="button" name="submit" value="Submit">
</form>
This is a div for your output.
<div>
<p id="output"></p>
</div>
This is jquery for ajax call function.
<script>
$(document).ready(function(){
$('#shiptype').change(function() {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
}
});
$("#btn_post").click(function(){
var parm = $("#frm_post").serializeArray();
$.ajax({
type: 'POST',
url: 'your.php',
data: parm,
success: function (data,status,xhr) {
console.info(data);
$( "#output" ).html(data);
},
error: function (error) {
console.info("Error post : "+error);
$( "#output" ).html(error);
}
});
});
});
</script>
And for PHP File to get the post value like this below. File name your.php.
<?php
// $key = $_POST['keyname'];
// echo $key;
print_r($_POST);
?>
Your post result will be show up in output id. Hope this help you out. :D

Related

Jquery Ajax html (Select multiple)

I m searching something of easy. I must pass value from a form html to a file PHP by jquery. I try this code with zero result. If someone can say me where i m mistaking. Thx
for JQUERY
$('#Save').click(function(){
var realvalues = new Array();//storing the selected values inside an array
$('#Privilege[] :selected').each(function(i, selected) {
realvalues[i] = $(selected).val();
});
$.ajax({
type: "POST",
url: "test5.php",
data: {"Privilege[]": realvalues},
success:function(data){
$("#subscrres").html(data)
}
});
});
For HTML
<form method="post">
<select id="Privilege[]" multiple>
<option value="yahoo">yahoo</option>
<option value="chrome">chrome</option>
<option value="mozilla">mozilla</option>
</select>
<input type="button" id="Save" Value="SEND"/>
For PHP. Content file test5.php
if(isset($_POST['Privilege'])){
$myvar =$_POST['Privilege'];
foreach($_POST['Privilege'] as $one)
echo $one."<br/>";
}
I don't receive nothing on PHP. Someone can help me ?
If you are trying to access multi select element using id the you don't need to set id like Privilege[], you can set any unique identity like privilege-selector but if you are giving name for any multi select element then name must be like Privilege[]
Here is the html :
<form id="form" method="post">
<select id="privilege-selector" multiple>
<option value="yahoo">yahoo</option>
<option value="chrome">chrome</option>
<option value="mozilla">mozilla</option>
</select>
<input type="button" id="Save" Value="SEND"/>
</form>
Please check this below ajax request to post selected data to the server
$("#Save").on("click",function(){
var selection = [];
$.each($("#privilege-selector option:selected"),function(index,element){
selection.push($(element).val());
})
$.ajax({
url : "test5.php",
type : "POST",
data : {Privilege:selection},
success : function(_response){
var res = JSON.parse(_response);
if(res.code == "1"){
console.log(res.data);
} else {
alert(res.message);
}
}
})
});
and here is your server file that will handle the incoming request data
$serverResponse = [];
if(isset($_POST['Privilege']) && !empty($_POST['Privilege'])){
$formattedData = [];
foreach($_POST['Privilege'] as $key => $value){
$formattedData[] = array(
"id" => $key+1,
"name" => $value
);
}
$serverResponse = ["code"=>"1","message"=>"formatted data","data"=>$formattedData];
} else {
$serverResponse = ["code"=>"0","message"=>"Please select at least on value"];
}
echo json_encode($serverResponse);

Multiple else if in jQuery

I am doing dependent select box using jquery, ajax and php from same table of the database. Testpage
$(document).ready(function(){
$('.action').change(function(){
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if(action == "name") {
result = 'category';
alert ('test1');
} else if (action == "category") {
result = 'material';
alert ('test2');
} else if (action == "material") {
result = 'source_light';
alert ('test3');
} else if (action == "source_light") {
result = 'color_temperature';
alert ('test4');
} else {
// result = 'color_temperature';
}
$.ajax({
url:"fetch_filter2.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
I don't know why but it only works: test1 and test2. Test3 and 4 are not sent to php.
HTML file
Maybe something is wrong with select box? But these are just a select box with id's.
<select name="name" id="name" class="form-control action">
<option value="">Select name</option>
<?php echo $name; ?>
</select>
<br />
<select name="category" id="category" class="form-control action">
<option value="">Select category</option>
</select>
<br />
<select name="material" id="material" class="form-control">
<option value="">Select material</option>
</select>
<br />
<select name="source_light" id="source_light" class="form-control">
<option value="">Select source_light</option>
</select>
<br />
<select name="color_temperature" id="color_temperature" class="form-control">
<option value="">Select color_temperature</option>
</select>
What about something like this
$(document).ready(function(){
$('.action').change(function()
{
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
switch(action) {
case "name":
result = 'category';
alert ('test1');
break;
case "category":
result = 'material';
alert ('test2');
break;
case "material":
result = 'source_light';
alert ('test3');
break;
case "source_light":
result = 'color_temperature';
alert ('test4');
break;
default:
// result = 'color_temperature';
}
$.ajax({
url:"fetch_filter2.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
Verify your drop down list under "action" class. As per your condition it won't trigger if your selected drop down item doesn't have value if($(this).val() != '').
Also make sure your expected drop down items have the value material for your test3 and source_light for your test4
Another suggestion: To load and trigger dynamic change event for drop down you can use below jQuery API:
$(document).on("change", ".action", function(){
//Your code here
});
If this doesn't solve your problem then please share your HTML or drop down data.
Updated answer: I can see there is no class "action" in your select/drop down items for material, source_light and color_temperature. That is why change actions of these drop down items are not catching in your $('.action').change(function() ... code block.

jQuery - Serialize Form Post Values

How do I want to post a form using jquery serialize function? I tried to post the form value but on the php part, the value is not shown. Below are my codes:
html
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
jQuery
$(document).on("click", "#submit", function(e){
e.preventDefault();
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
data = $('form').serialize();
$.post('result.php',
{
data : data
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
});
PHP
if(isset($_REQUEST["sort"])){
$sort = $_REQUEST['sort'];
$id_staff = $_REQUEST['id_staff'];
echo "Your Id : $id_staff <p/>";
echo "You choose : $sort";
}
If I console.log(data), I get: id_staff=12345&sort=1
Your server is receiving a string that looks something like this (which it should if you're using jQuery serialize()):
"param1=someVal&param2=someOtherVal"
...something like this is probably all you need:
$params = array();
parse_str($_GET, $params);
$params should then be an array that contains all the form element as indexes
If you are using .serialize, you can get rid of this:
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
You data will be available as follows with .serialize:
your-url.com/sort=yoursortvalue&id_staff=youridstaff
It should be:
$(document).ready(function(e) {
$("#myform").submit(function() {
var datastring = $( this ).serialize();
$.post('result.php',
{
data : datastring
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
})
})
On PHP side you simple need to access it using the $_GET['sort'].
Edit:
To view the data, you should define a div with id result so that the result returned is displayed within this div.
Example:
<div id="result"></div>
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
I am able to do it this way:
jQuery
<script type="text/javascript">
$(document).ready(function() {
var form = $("#myform");
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'result.php',
data: form.serialize(),
success: function(response) {
console.log(response);
$("#result").html(response);
},
error: function() {
alert('Error Submitting');
}
})
})
})
</script>
PHP
if(isset($_POST["id_staff"])){
$sort = $_POST['sort'];
$id_staff = $_POST['id_staff'];
echo "<p>Your Id : $id_staff</p>";
echo "You choose : $sort";
}
Do give a comment if it need improvement or better solution.

how to get session values to textbox when checkbox is clicked in jquery

I'm having two pages with similar textboxes when user inserts data into first page and goes to next page, if he need to give same data am adding a checkbox, when user clicks it same data which is in session from before page has to be get into the second page variables through ajax. can someone help me please. thanks
Response for the Comment
I made sample code which will give you idea about how to can do this.
jQuery Code for checkbox change event
$(function(){
$('input:checkbox').change(function(){
if($(this).is(':checked'))
{
$.ajax({
url : 'script.php',
success : function(session)
{
$('input:text').val(session);
}
});
}
});
});
HTML
<input type="text" />
<input type="checkbox" />
script.php
<?php
session_start();
echo $_SESSION['name_of_the_session_variable'];
exit;
?>
EDIT
$("#checked").click(function()
{
if ($(this).is(':checked'))
{
$('#provisional_total_public_funding').val(<?php echo empty($this->session->store['actual_info']['actual_total_public_funding']) ? '' : $this->session->store['actual_info']['actual_total_public_funding']; ?>);
}
});
Ajax Request Response
<select name="fin_year" id="fin_year">
<option value="" >Please select an year</option>
<option value="<?= $actFinYr; ?>"><?= $actFinYr; ?></option>
</select>
<script type="text/javascript">
$(function(){
$('#fin_year').change(function()
{
var options = $(this);
if(options.val() != '')
{
$.ajax(
{
url : 'CODEIGNITER_HTTP_URL/'+options.val(),
beforeSend : function()
{
//show loading
},
success : function(response)
{
//play with the response from server.
}
});
}
});
});
</script>
I'd use jQuery like this:
HTML 1st page:
input1 <input type="text" id="input1" name="input1"/>
input2 <input type="text" id="input2" name="input2"/>
jQuery 1st page:
$input1 = $("#input1");
$input2 = $("#input2");
$input1.keydown(function(){
$.post("yourPHP.php", {input1: $input1.val()});
});
$input2.keydown(function(){
$.post("yourPHP.php", {input1: $input1.val()});
});
PHP 1st page:
if(session_id() == '') {
session_start();
}
if(isset($_POST['input1'])){
$_SESSION['input1'] = $_POST['input1'];
}
if(isset($_POST['input2'])){
$_SESSION['input2'] = $_POST['input2'];
}
HTML 2nd page:
input1 <input type="text" id="input1" name="input1"/>
input2 <input type="text" id="input2" name="input2"/>
<br/>
radio1 <input type="radio" id="radio1" name="radio"/>
radio2 <input type="radio" id="radio2" name="radio"/>
jQuery second page:
$input1 = $("#input1");
$input2 = $("#input2");
$radio1 = $("#radio1");
$radio2 = $("#radio2");
$radio.click(function(){
$.post("yourPHP.php", {request: "input1"}, function(data){
$input1.val(data);
});
});
$input2.keydown(function(){
$.post("yourPHP.php", {request: "input2"}, function(data){
$input2.val(data);
});
});
PHP 2nd page:
if(session_id() == '') {
session_start();
}
if(isset($_POST['request'])){
switch($POST['request']){
case 'input1':
echo $_SESSION['input1'];
break;
case 'input2':
echo $_SESSION['input2'];
break;
}
}
I hope it works.

Error posting form values using jQuery in PHP

I have made a simple page which uses jquerydatepicker, two dropdown comboboxes for selecting time values. I tried to post the values but the page gets redirected to itself with selected values shown in url and I get no values on the receiver page.
Here's the script:
<script type="text/javascript">
$(document).ready(function(){
var jQueryDatePicker1Opts = {
dateFormat: 'mm/dd/yy',
changeMonth: false,
changeYear: false,
showButtonPanel: true,
showAnim: 'fadeIn'
};
$("#jQueryDatePicker1").datepicker(jQueryDatePicker1Opts);
$("#jQueryDatePicker1").datepicker("setDate", "new Date()");
$('#submit').click(function() {
var startTime = parseInt($('#Combobox1 option:selected').text());
var endTime = parseInt($('#Combobox2 option:selected').text());
if(startTime>=endTime){
alert("End Time should not be less than Start Time !");
return false;
}
});
$("#Campaign_form").submit(function(){
$.post({type:'POST', url:'campaigndata.php' ,
data:$('#Campaign_form').serialize(), success: function(response) {
$('#Campaign_form').find('.form_result').html(response);
}});
var isValid = $.validate.form(this);
return isValid;
});
});
</script>
Here is the form script:
<form name="Campaign_form" id="Campaign_form" >
<input type="text" id="jQueryDatePicker1" name="jQueryDatePicker1" value="06/09/2012">
<select name="StartTime" size="1" id="Combobox1" >
<option value="1">01:00</option>
...
<option value="24">23:00</option>
</select>
<select name="EndTime" size="1" id="Combobox2" >
<option value="1">01:00</option>
...
<option value="24">00:00</option>
</select>
<select name="SelectApp" size="1" id="Combobox3" >
<?php
while($row = mysql_fetch_array($result)){
echo "<option value =".$row['AppName'].">".$row['AppName']."</option>";
}
?>
</select>
<input type="submit" id="submit" name="submit" value="submit" >
</form>
Here is the campaigndata.php script:
<?php
$campaignDate = $_POST['jQueryDatePicker1'];
$camp_Start_Time = mysql_real_escape_string($_POST['StartTime']);
$camp_End_Time = mysql_real_escape_string($_POST['EndTime']);
$campaignID = $appid.$campaignDate.$camp_Start_Time ;
?>
This campaigndata.php shows null values on echoing above php variables.
You need to connect to your database before you can use mysql_real_escape_string() and change the form method to post.
You have to return false if you don't refresh page by submitting form
$("#Campaign_form").submit(function () {
var isValid = $.validate.form(this);
if (isValid)
$.post({type:'POST', url:'campaigndata.php',
data:$('#Campaign_form').serialize(), success:function (response) {
$('#Campaign_form').find('.form_result').html(response);
}});
return false;
});
ur answers helped me a lot !!! i figured out the problem was in capaigndata.php
i was using mysql_real_escape_string() before $_POST[''] ;
which was creating problems .
I removed those and used normal $_POST[] and it worked magically !!! :)

Categories