Post JQuery variable to PHP - 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);
}
});

Related

How do I send a Latitude & Longitude Value For AJAX to get Information From GeoNames

I need some help and advice if possible.
I'm working on a task for an online course and I'm stumped. I have the below html, trying to send a latitude value to ajax for a php request to geonames API and return the nearest ocean. I have tried a couple of different ways as shown below in the html code.
<select id="latitude">
<option value= "3.4360">3.4360</option>
<option value="lat">133.7751</option>
<option value="lat">106.3468</option>
</select>
<select id="longitude">
<option value= 55.3781>55.3781</option>
<option value="lng">25.2744</option>
<option value="lng">56.1304</option>
</select>
And this is the ajax request that should be pulling the info from the above html.
$('#btnRun').click(function() {
$.ajax({
url: "libs/php/getCountryInfo.php",
type: 'POST',
dataType: 'json',
data: {
lat: parseInt($('#latitude').val()),
lng: parseInt($('#longitude').val())
},
success: function(result) {
console.log(JSON.stringify(result));
if (result.status.name == "ok") {
$('#txtDistance').html(result['data'][0]['distance']);
$('#txtGeonameID').html(result['data'][0]['geonameid']);
$('#txtName').html(result['data'][0]['name']);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// your error code
}
});
});
I don't think the two link up at all and I had a look at the parseInt option as well but I am out of ideas now.
Thank you for any help you can give.
The <option> tags in your Html are wrong, the value attribute is set to the strings lat and lng and not the actual latitudes and longitudes.
<select id="latitude">
<option value="3.4360">3.4360</option>
<option value="133.7751">133.7751</option>
<option value="106.3468">106.3468</option>
</select>
<select id="longitude">
<option value="55.3781">55.3781</option>
<option value="25.2744">25.2744</option>
<option value="56.1304">56.1304</option>
</select>
Also, if you exclude the value attribute then the text inside the option is considered its value. The markup below is equivalent to the one above.
<select id="latitude">
<option>3.4360</option>
<option>133.7751</option>
<option>106.3468</option>
</select>
<select id="longitude">
<option>55.3781</option>
<option>25.2744</option>
<option>56.1304</option>
</select>
Latitude and longitude values aren't integers so you cannot use parseInt on them, also there is no reason to parse them as numeric values as they will be converted back to String to be sent in the ajax call
$.ajax({
url: "libs/php/getCountryInfo.php",
type: 'POST',
dataType: 'json',
data: {
lat: $('#latitude').val(),
lng: $('#longitude').val()
},
success: function(result) {
console.log(JSON.stringify(result));
if (result.status.name == "ok") {
$('#txtDistance').html(result['data'][0]['distance']);
$('#txtGeonameID').html(result['data'][0]['geonameid']);
$('#txtName').html(result['data'][0]['name']);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// your error code
}
});

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.

PHP: Passing selected list value to another variable in the same page

I have a form, having two list boxes and based on the selected field from the first list, I have to fetch data from the database to create second list box.
I am trying to acheive this with post method, but unable to understand why mey second list is not populating with data...
PHP to fetch data for second list box
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
}
HTML to for the list boxes
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="c">CC</option>
<option value="d">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid"> <br />
<option value="">Home_Floor</option>
<?php foreach ($HF_id as $row){echo '<option value="' . $row['floor'] . '">' . $row ['floor'] . '</option>';}?>
</select>
Jquery
$('#PC1').on('click', function() {
$.post('user_info1.php', 'val=' + $(this).val(), function (response) {
$.ajax({
url: 'user_info1.php', //This is the current doc
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
}
});
You seem to expect the post function to trigger a loading of the page specified by the URL parameter.
Try something along the lines of this:
HTML
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="C">CC</option>
<option value="D">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid">
</select>
loaddata.php
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
$HF_array=array();
foreach ($HF_id as $row)
{
$HF_array[]=$row['floor'];
}
}
echo json_encode($HF_array);
javascript/jquery
jQuery('#PC1').on('click', function() {
jQuery.ajax({
url: 'loaddata.php',
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
//data should come as JSON string in the form of ['item1','item2','item3'] use JSON.parse to convert to object:
jQuery.each(JSON.parse(data), function(key, datavalue) {
jQuery('#hfid').append(
jQuery('<option>', { value : datavalue })
.text(datavalue)
);//end of append
});//end of each
}//end of success function
});//end of ajax datastruct and ajax call
});//end of on-click-function

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

How to pass data through Jquery?

Here is the piece of my dropdown list:
<li><label>City:</label>
<select id="car" id="city">
<option value="New York">New York</option>
<option value="Sydney">Sydney</option>
</select>
</li>
Ajax code:
$("#SaveChanges").click(function () {
var data = {
email: $('#email').val(),
firstname: $('#firstname').val(),
lastname: $('#lastname').val(),
city: $('#city option:selected').text()
};
$.ajax({
url: "<?php echo site_url('ajax/saveChanges');?>",
type: 'POST',
async: false,
data: data,
success: function(msg) {
alert(msg);
},
error: function(e) {
alert("error");
}
});
return false;
});
I want to send all the data to ajax function. I am getting all the details there except city.
Try changing to this:
$( "#city" ).val();
Your select have to look like this:
<li><label>City:</label>
<select id="city">
<option value="New York">New York</option>
<option value="Sydney">Sydney</option>
</select>
</li>
Hope it helps you!
You just need to access the val() function for the select:
$('#city').val()
That will give you the value.
Note that the value is not the same as the display text, in that case you'll want to use the text() function.

Categories