Getting HTML value in PHP using AJAX and POST method - php

I should start off by saying that I am very new to server side programming. I am trying to get a value on its change using AJAX.
My AJAX code (ajaxCode.php)
$(document).ready(function() {
$('select[name="selectBox"]').change(function(){
var value = $(this).val();
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {valueChange: value },
dataType: 'html'
});
alert(value );
});
});
My HTML code with the select box (calculator.php)
<select name ="selectBox">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<?php
$status = $_POST['changeStatus'];
echo $status;
?>
This doesn't seem to work. The status will alert but won't be echoed. What am I doing wrong? Thanks in advance?

You probably want to send value of selected box through ajax and then change the status which you get from ajax.
Server site: calculator.php
Client side:
<script>
$(document).ready(function() {
$('select[name="selectBox"]').change(function(){
var value = $(this).val();
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {valueChange: value },
dataType: 'html'
}).done(function(response){
$('.response-holder').html(response);
});
});
});
</script>
<select name ="selectBox">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<div class="response-holder"></div>

This works ok:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on("change", ".selectBox", function(){
var v = $(this).val();
$.post( "ajax.php", { changeStatus: v , time: "123" }, function( data ) {
alert("From file: " +data);
});
});
});
</script>
</head>
<body>
<select name ="selectBox" class="selectBox">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
</body>
</html>
and ajax.php
<?php
$status = $_POST['changeStatus'];
echo $status;
?>

The code that receives the ajax call should be in its own file, and echo only what you need to retrieve, not the whole content you started with. For example, just echo the status.
Let's say this is your HTML
<select name ="selectBox">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<script>
$(document).ready(function() {
$('select[name="selectBox"]').change(function(){
var value = $(this).val();
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {valueChange: value },
dataType: 'html'
});
alert(value );
});
});
<script>
Then this could be your calculator.php
<?php
$status = $_POST['changeStatus'];
echo $status;
?>
But then, again, you're making an ajax call and not doing anything with its response. To receive that calculator.php is answering, you could do
<select name ="selectBox">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
<div id="response"></div>
<script>
$(document).ready(function() {
$('select[name="selectBox"]').change(function(){
var value = $(this).val();
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {valueChange: value },
dataType: 'html'
}).then(function(response) {
jQuery('#response').html('Ajax answered: '+response);
});
alert(value );
});
});
<script>

Try this in your calculator.php script.
<?php
$status = $_POST['valueChange'];
echo $status;
?>
Does this give you your desired result?

Related

can't send jquery value to php code

I tried to send a variable value from Jquery to php code,but it doesn't work although it appears successfully in console:
Ajax:
$('#commission').change(function(){
var coinval=$('select[name=cointype]').val();
$.ajax({
url: 'core_functions/parse_coins.php', //This is the current doc
type: "POST",
data: ({coinname: coinval}),
success: function(data){
console.log(data);
var recent_btc_price=<?php show_btc_price(); ?>; //10122.9
var com=$('#commission').val();
var com_amount_only=com * recent_btc_price /100;
var convert_comm_amount=Number(com_amount_only);
var totalpricewithcomm=recent_btc_price + convert_comm_amount;
var round_totalprice=totalpricewithcomm.toFixed(2);
$('#display').text("$"+round_totalprice);
}
});
})
PHP:
if(isset($_POST['coinname'])){
$coinname=$_POST['coinname'];
echo $_POST['coinname'];
}
HTML:
<select name="cointype" id="deal_options" class="form-control">
<option value="bitcoin" >Bitcoin (BTC)</option>
<option value="ethereum"selected >Ethereum (ETH)</option>
</select>
<select class="form-control" id="commission">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
why the data can't be handled by php?
i edited code to make it work by making the following changes:
//send data to php file
var coinval=$('select[name=cointype]').val();
function senddata(catchdata){
$.ajax({
url: 'core_functions/parse_coins.php', //This is the current doc
type: "POST",
data: ({coinname: coinval}),
success: function(data){
catchdata(data);
}
});
}
to recieve data:
//recieve data
senddata(function(output){
var recent_btc_price=Number(output); //10122.9
var com=$('#commission').val();
var com_amount_only=com * recent_btc_price /100;
var convert_comm_amount=Number(com_amount_only);
var totalpricewithcomm=recent_btc_price + convert_comm_amount;
//alert(recent_btc_price);
var round_totalprice=totalpricewithcomm.toFixed(2);
$('#display').html(coinval+"~$"+round_totalprice);
});
php code in Jquery must be enclosed by double quotes
var recent_btc_price="";
You have to declare show_btc_price() function first then implement code.

How to define the ajax return value

In my project, I use jqpagination. And I want to define the records of each page, so I use select tag in my web page.
The problem is when I change select tag, the value returned from lstajax.php is not the same. sometimes it is xie1, but sometimes it is xie2.
I have tested, the returned value is random. For example, when i chosed 30 first, the value is xie1. When i chosed 30 next time, the value maybe xie1 or maybe xie2.
My js code:
<link rel="stylesheet" href="jsui/jqpagination.css" />
<script src="jsui/jquery-3.2.1.min.js"></script>
<script src="jsui/jquery.jqpagination.js"></script>
<script>
$(document).ready(function()
{
var rtnv = "<?php session_start();echo $_SESSION['rtNum']?>";
var pgrNum=$('#pgnId').val();
var mpn=Math.ceil(rtnv/pgrNum);
$('.pagination').jqPagination({
max_page:mpn,
page_string:'Page {current_page} of {max_page}',
paged:function(page){
$.ajax({
dataType:'html',
type:"POST",
url:"lstajax.php",
data:{pageNum:page,pgrNum:pgrNum},
success:function(data)
{
$('#div2').html(data);
}
});
}
});
$('#pgnId').change(function(){
var pages="1";
$('.pagination').jqPagination('option','current_page',pages);
var rtnvs = "<?php session_start();echo $_SESSION['rtNum']?>";
var pgrNums=$('#pgnId').val();
var mpns=Math.ceil(rtnvs/pgrNums);
$('.pagination').jqPagination('option','max_page',mpns);
$.ajax({
dataType:'html',
type:"POST",
url:"lstajax.php",
data:{pageNums:pages,pgrNums:pgrNums},
success:function(data)
{
$('#div2').html(data);
}
});
});
});
</script>
My lstajax.php code:
<?php
if(isset($_POST['pageNum']))
{
echo "xie1";
}
if(isset($_POST['pageNums']))
{
echo "xie2";
}
?>
My html code:
<div class="pagination" style="clear:both;display:block;margin-left:40%">
«
‹
<input type="text" readonly="readonly" data-max-page="80"/>
›
»
<label>eachpage:</label>
<select name="pgNum" id="pgnId">
<option value="10">10</option>
<option value="15">15</option>
<option value="20" selected="selected">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
var options={'trigger':false}
in the method:
base.cassMthod=function(method,key,value)
in the file:
jquery.jqPagination.js

Showing results on html using form en Ajax (OnChange)

This question is SOLVED - solution is on the bottom of the question.
Let's say I have this form:
<form id="form1" action="" method="POST">
<select name="cars">
<option value="">Choose a car</option>
<option value="Ferrari">Ferrari</option>
<option value="Lamborghini">Lamborghini</option>
</select>
<select name="colors">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
Php:
$cars = $_POST['cars'];
$colors = $_POST['colors'];
echo "Car: ".$cars." - Color: ".$colors."";
Ajax:
<script type='text/javascript'>
$('select[name="colors"]').on('change', function(){
$.ajax({
type: "POST",
url: "phpfile.php",
data: $("#form1").serialize(),
success: function(data){
$('#target1').html(data);
}
});
return false;
})
</script>
I want to show on html the results:
<div id="target1"></div>
I want to show the results when I choose the color (The 2nd dropdown):
onchange="this.form.submit()"
IT IS DONE:)
I used this code and it I am getting what I want:
<script type='text/javascript'>
$("#colorID").on("change", function() {
var $form = $("#form1");
var method = $form.attr("method") ? $form.attr("method").toUpperCase() : "GET";
$.ajax({
url: 'phpfile.php',
data: $form.serialize(),
type: method,
success: function(data){
$('#target1').html(data);
}
});
});
</script>
Technically you dont need ajax to get what your asking for but heres jQuery ajax example:
Change your HTML to:
<select name="colors" onchange="this.form.submit()">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
$( "#form1" ).submit(function( event ) {
event.preventDeafault();
alert('form submitted');
$.ajax({
type: "POST",
url: "<YOUR PHP FILE PATH>",
data: $("#form1").serialize(),
success: function(data){
alert('ajax success');
$('#target1').html(data);
}else{
alert('ajax error');
}
});
return false;
})
In your PHP:
print_r($_POST);
$car = $_POST['car'];
$color = $_POST['color'];
echo "<p>Car: ".$car." - Color: ".$color."</p>";
This is untested - I've just typed it out on my phone during my lunch break!
To debug the php add this line ( to unsure the post worked):
print_r($_POST);
Use your browser developer tools to debug your AJAX and JS
I've add alerts to help you debug - you can remove these when its working

Get the select value without refreshing the form

With this code I can see each option value printed but the page is refreshed every time I select an option. The server get the post data correctly, so I just need to do it without refreshing.
Thanks. Regards.
<form action="" method="post">
<select name="day" onchange="this.form.submit();">
<option>Please select a date</option>
<option value="Mon">Monday</option>
<option value="Tue">Tuesday</option>
<option value="Wed">Wednesday</option>
<option value="Thu">Thursday</option>
<option value="Fri">Friday</option>
</select>
</form>
<script type="text/javascript">
$('#day').change(function()
{
$.ajax({
type: 'post',
url: "day.php",
data: $("form.day").serialize(),
});
return false;
});
</script>
<?php
include 'day.php'; ?>
day.php
<?php
$day = $_POST['day'];
echo $day;
?>
I think you need this:
e.preventDefault();
//add your id="day"
<select name="day" id="day" onchange="this.form.submit();">
$('#day').change(function(e)
{
e.preventDefault();
$.ajax({
type: 'post',
url: "day.php",
data: $("form.day").serialize(),
});
return false;
});
Update the onchange to call a Javascript function that copies the data to a hidden field in another form, and use Ajax to submit that one instead.
Optionally, you could also submit the data through Ajax directly, without the additional form, but for things that might be done with high frequency, I find it useful to minimize the bandwidth as much as possible.
I could see every option value printed by the <p id=..> without refreshing the page. But the post data is not passed to day.php..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<html>
<head>
<script>
function postSelection(selectObject) {
var day = window.dateForm.day.value = selectObject.options[selectObject.selectedIndex].value;
var dataString = "day=" + day;
$.ajax ({
type:"post",
url: "day.php",
data:dataString,
success: function (response) {
$("#list").html(response);
}
});
return false;
}
</script>
</head>
<body>
<form name="displayForm">
<select name="day" onchange="return postSelection(this)">
<option>Please select a date</option>
<option value="Mon">Monday</option>
<option value="Tue">Tuesday</option>
<option value="Wed">Wednesday</option>
<option value="Thu">Thursday</option>
<option value="Fri">Friday</option>
</select>
</form>
<form action="" method="post" name="dateForm">
<input type="hidden" name="day">
</form>
<?php include 'day.php'; ?>
</body>
</html>

Retrieve the districts from database using PostgreSQL

I want to retrieve districts and state from the database, and also to populate second dropdown list based on first dropdown list. In my code below the values are inserted directly:
<!DOCTYPE html>
<head>
<script type="text/javascript" src="C:\Program Files\BitNami WAPPStack\apache2\htdocs \Prj\Online\jquery-1.9.1.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
var options = $('#test2 option');
$('#test1').on('change', function(e) {
$('#test2').append(options);
if ($(this).val() != 'Select') {
$('#test2 option[value!=' + $(this).val() + ']').remove();
} else {
$('#test2').val('Select');
}
});
});
</script>
<form name="form1" method="post" action="fid1.html">
<select name="test1" id="test1">
<option value="Select">Select</option>
<option value="a">TamilNadu</option>
<option value="b">Kerala</option>
<option value="c">Andhra</option>
</select>
<select id="test2" name="test2">
<option value="Select">Select</option>
<option value="a">Chennai</option>
<option value="a">Trichy</option>
<option value="a">Madurai</option>
<option value="b">Trivandram</option>
<option value="b">Cochin</option>
<option value="b">Azhapuzha</option>
<option value="c">Hyderabad</option>
</select>
</form>
</head>
</html>
for that purpose you should use Ajax call on your first drop box .
Ajax is a server side tools to fetch data from database.
Create a ajax function, for example get_country()
$(function() {
$('#test1').change( function() {
var val = $(this).val();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
now do your database query on findstate.php and use state div to show particuler state list.

Categories