can't send jquery value to php code - php

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.

Related

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

Getting HTML value in PHP using AJAX and POST method

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?

get html dropdown array in jquery

On my html page, I have a variable number of dropdown boxes, each with the following code:
<select name="gearquan[]">
<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>
<option value="8">8</option>
</select>
If using a regular form submit, it sends as a nested array. I'm trying to convert my forms over to using jquery and ajax. When I had a list of checkboxes I used the following code to get their values:
var gear = new Array();
$("input:checked").each(function() {
gear.push($(this).val());
});
What would I need to change in that, in order to get the values of the dropdown boxes? (Other than changing gear to gearquan)
It seems like you are trying to manually build arrays to send to your PHP through AJAX, you don't need to do all that. When using jQuery and AJAX all you need to do is use .submit() to handle your submit event and .serialize() to get all your current form's data to send thorough AJAX as such:
$('form').submit(function(e){
e.preventDefault();
var postdata = $(this).serialize();
$.ajax({
url: 'file.php',
type: 'post',
data: postdata,
success: function(response){
console.log(response);
}
});
});

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

Post JQuery variable to PHP

So I have this select field:
<select name="year" id = "year" class="dropdown-select">
<option value="2005">All Years</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
<option value="2008">2008</option>
<option value="2007">2007</option>
<option value="2006">2006</option>
</select>
And I have this jquery to get the selected value any time a new value is selected:
$("#year").change(function() {
input_year = parseInt($(this).val());
});
My question is how would I go about posting the 'input_year' variable to PHP every time the value changes?
The end goal is to do something with $_POST['year'] in PHP and return the result to JavaScript e.g echo "var res = " . $_POST['year'] . ";";
A very simple implementation
$.ajax({
type:'POST',
url:'your_url.php',
data:'input_year='+input_year,
success: function(msg) {
console.log(msg);
}
});
data string may need a ? before it, I can't remember off the top of my head
Use AJAX, specifically the jQuery .post() function:
$("#year").change(function() {
input_year = parseInt($(this).val());
$.post('/path/to/file', year: input_year, function(data, textStatus, xhr) {
/*optional stuff to do after success */
});
});
$("#year").change(function() {
var input_year = parseInt($(this).val());
$.post('server.php',{year:input_year}, function(result,status){});
});
Using ajax. With jquery, it would be like this:
$.ajax({
type: 'POST',
dataType: 'text',
url: "(your php filename)",
data: $.param({'year': input_year}),
success:function(data){
//do whatever you need to do with the received result
}
error: function (request, status, error) {
alert(request.responseText);
}
});

Categories