Showing results on html using form en Ajax (OnChange) - php

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

Related

Show option chosen by ajax from a select

Hello I am trying to choose an option from the select to show me the option chosen on the page by ajax but the code is not working if you can help me thanks
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0 /jquery.min.js"></script>
<script>
function fetch_select(val){
$.ajax({
type: 'post',
url: 'ajax.php',
datatype:'json',
data: {option:val},
success: function (response) {
$('#print-ajax').html(response);//This will print you result
}
});
}
</script>
<div id="select_box">
<select onchange="fetch_select(this.value);">
<option value="10">state</option>
<option value="20">20</option>
</select>
</div>
<p id="print-ajax"></p><!--Result will print here-->
ajax.php
echo $_POST['option'];
Sometimes jQuery file not working while you put it at the top of Body tag. Currently your code is perfect. But my suggest is try this.
<div id="select_box">
<select onchange="fetch_select(this.value);">
<option value="10">state</option>
<option value="20">20</option>
</select>
</div>
<p id="print-ajax"></p><!--Result will print here-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0 /jquery.min.js">
</script>
<script>
function fetch_select(val){
$.ajax({
type: 'POST',
url: 'ajax.php',
dataType:'JSON',
data: {option:val},
success: function (response) {
$('#print-ajax').html(response);//This will print you result
}
});
}
</script>
Sometimes "post" small format creates issues. So always use "POST" as a capital format.
Hope it will be work for you.

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?

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.

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