Can't print POST variable from AJAX using PHP - javascript

I am getting a list of data from a mysql database which I add to a select list. When the user chooses an option I want to get the ID from the selected item, and use it to reference the index of my results array, like this:
echo $results[$id]['fruit'];
I retrieved the data from the database using $results = $stmt->fetchAll(PDO::FETCH_UNIQUE) so each id of the select list is the primary key of the record.
So I read that I can use AJAX to get the value of the selected item and send it back as a POST variable which I can then access in PHP. However when I go to print this variable I get nothing.
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //prints nothing
}
Here is my code:
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
function listChange() {
var recID = document.getElementById("fruits").value;
$.ajax({
method: 'POST',
data: {'id' : recID},
dataType: "json",
success: function(response)
{
console.log(response);
}
});
}
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits" onchange="listChange()">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
My Fruit <input type="text" id="myfruit">
<?php
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //does not print however post is working if you look in firefox -> web developer -> developer toolbar -> network
//the id will be used to reference a variable
//$results[$id]['fruit'] which I got
//from a database like this
//$results = $stmt->fetchAll(PDO::FETCH_UNIQUE);
//this value will set the text field myfruit
}
?>
</body>
</html>

I think you may try this
$(document).ready(function(){
$("#fruits").change(function(){
var fruitValue = $(this).val(); // for the value i.e 0,1,2,3
var fruitTect = $(this).text(); // for text i.e. Apple, Pear,...
// then now you can do ur ajax
$.ajax({
// Your Code For Post goes here
});
});
});
No need to call the onchange function in your html. Jquery will take care of the rest
Also your isset($_POST['id']) maybe isset($_POST['fruits'])

Rogers answer is right. and you miss the url parameter in your ajax call.
function listChange() {
var fruitValue = $(this).val(); // for the value i.e 0,1,2,3
$.ajax({
url: '/myPhpFile.php',
method: 'POST',
data: {'id' : fruitValue},
dataType: "json",
success: function(response)
{
console.log(response);
}
});
}
if you realy want to call it in a single file you have to place the php code in top and do an exit after the condition is fullfilled..
<?php
if(isset($_POST['id']))
{
$id = $_POST['id'];
you need to encode as ajax expect a json data
$results_array = array("Id" => $id):
$json=json_encode( $results_array );
header('Content-Type: application/json'); //tell the broswer JSON is coming
echo $json; //Just plain vanillat JSON output
do your things here an exit. Be aware that each echo "something" falsify the json data expected by the ajax call
exit();
}
?>

Try use this code in HMTL.
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
function listChange(obj) {
var recID = obj.value;
var recID = $("#fruits:selected").text();
$.ajax({
method: 'POST',
data: {'id' : recID},
url:'demo.php',(put url of php file and remove in this file make diffrent php file)
dataType: "json",
success: function(response)
{
console.log(response);
}
});
}
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits" onchange="listChange(this)">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
My Fruit <input type="text" id="myfruit">
<?php
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //does not print however post is working if you look in firefox -> web developer -> developer toolbar -> network
//the id will be used to reference a variable
//$results[$id]['fruit'] which I got
//from a database like this
//$results = $stmt->fetchAll(PDO::FETCH_UNIQUE);
//this value will set the text field myfruit
}
?>
</body>
</html>

Ok I found a much simpler way of doing this. Just get Javascript to encode the value in the URL when the select is changed, then access it in PHP using GET.
Encoding the URL in Javascript:
<script>
$(document).ready(function(){
$("#fruits").change(function(){
var fruitValue = $(this).val();
window.location.href="ajax.php?id=" + fruitValue;
});
});
</script>
Echo the value in PHP:
if(isset($_GET['id']))
{
$id = $_GET['id'];
echo $id;
}

Print data via the different file.
Php return data send to another file and ajax response data print in html.
Action file
if(isset($_POST['id']))
{
$id = $_POST['id'];
echo $id; //prints nothing
}
View file
function listChange() {
var recID = document.getElementById("fruits").value;
$.ajax({
url: 'action.php',
method: 'POST',
data: {'id' : recID},
dataType: "json",
success: function(response)
{
$('#your_id').html(response);
}
});
}
OR
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
function listChange() {
var recID = document.getElementById("fruits").value;
$("#your_id").html(recID);
}
</script>
</head>
<body>
Fruits
<select id="fruits" name="fruits" onchange="listChange()">
<option value="0">Apple</option>
<option value="1">Pear</option>
<option value="2">Watermelon</option>
<option value="3">Orange</option>
</select>
<br/><br/>
My Fruit <input type="text" id="myfruit">
<div id="your_id"></div>
</body>
</html>

<script>
function listChange() {
var recID = document.getElementById("fruits").value;
$.ajax({
url:'ajax.php'
method: 'POST',
data: {'id' : recID},
success: function(response)
{
console.log(response);
}
});
}
</script>
<?php
print_r($_POST);
?>

Related

jquery ajax post to self not working

i am taking a value from the dropdown using jquery on change , i am using ajax to post to self, but i am not able to echo the posted variable.
<form>
<label>Select Doctor:</label>
<select class="docdrop">
<option value="">Choose</option>
<option value = "123">doca</option>
<option value = "456" >docb</option>
</select>
</form>
<script>
$(document).ready(function(){
$("select.docdrop").change(function(){
var d_Id = $(this).val();
if(d_Id!="")
{
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'];?>",
data: {d_id1 : d_Id}, //using 'd_id1' did not make a change
success: function(){
alert(d_Id]);
}
});
}
});
});
</script>
//php code in same page
<?php
if(isset($_POST['d_id1']))
$d_Id = $_POST['d_id1'];
?>
<p><?php echo $d_Id; ?></p>
i get the alert on success but , i am unable to echo the posted variable. i dont want to use serialize() or post the entire form. just d_Id whic i obtain in jquery
If you want you can do this without using jQuery in this way :
<?php
$d_id1 ="";
if(isset($_POST['d_id1'])){
$d_Id = $_POST['d_id1'];
echo $d_Id;
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
</head>
<body>
<form>
<label>Select Doctor:</label>
<select class="docdrop" >
<option value="">Choose</option>
<option value = "123">doca</option>
<option value = "456" >docb</option>
</select>
</form>
<script>
$(document).ready(function(){
$("select.docdrop").change(function(){
var d_Id = $(this).val();
if(d_Id!="")
{
$.ajax({
type: "POST",
url: "<?php echo $_SERVER['PHP_SELF'];?>",
data: {d_id1 : d_Id},
success: function(data){
d_id1 = data;
document.getElementById('name').innerHTML = d_id1;
console.log(data);
}
});
}
});
});
</script>
<p id ="name"><?php echo $d_id1;?></p>
</body>
</html>
php code execute one time on page load, so that time your variables $d_Id and $d_Id1 are not created, so it is not display any value.
also ajax execute without page refresh and all code in side success executed without any error.
success: function(data){
alert(data);
}
You will alert the data send from backend i.e. echoed by your php part, which in your case will be the result of <p><?php echo $d_Id; ?></p>, if you just need your $d_id selected without the paragraph tags change your code to <?php echo $d_Id; ?>. Of course you may prefer to use JSON as output of your backend and then parse it in the success callback with $.parseJSON(data) per instance or use data type 'json' in your AJAX reques.

Not found when using ajax in dynamic dropdown in php

In my php code, I have two dropdowns which is the other one depends on the first one.
Here is the first dropdown:
<select class="form-control style" id="sel" >
<option style="color: black;" >Select...</option>
<?php foreach ($dtype as $row ) { ?>
<option style"color:black;" value="<?php echo $row['donations_type_id'];?>"> <?php echo $row['donations_type_name'];?></option>
<?php }?>
</select>
<tr>
<td>Available Donation:</td>
<td style="color: black; ">
<select name='avail' id='avail' class="form-control style" >
<option style="color:black;" value="">Select...</option>
</select>
</td>
</tr>
The second dropdown shows the data that corresponds whatever the user selects from the first dropdown.
Here's the script:
<script type="text/javascript">
$(document).ready(function(){
$("#sel").change(function(){
$.ajax({
data: {id: $(this).val()},
type: "POST",
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ $(this).val(),
success:function(data){
$("#avail").html(data);
}
});
});
});
</script>
In my controller:
public function showAvailable()
{
echo $id = $this->input->post('id', true);
$data['package'] = $this->Beneficiary_model->getDtype($id);
$output = null;
foreach ($data['package'] as $row ) {
$output.="<option value='".$row->package_id."'>".$row->package_name."</option>";
}
echo $output;
}
And in my model:
public function getDtype($id){
$this->db->select('package_id','package_name');
$this->db->from('package_table');
$this->db->where('package_type', $id);
$query = $this->db->get();
return $query->result();
}
When I tried to run the code and debug it through F12, it shows there that POST http://localhost:8999/samp/sampModule/showAvailable/2 404 (Not Found)
Why is it?
Can anyone help me with this error?
$("#sel").change(function(){
$.ajax({
data: {id: $(this).val()},
...
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ $(this).val(),
Take $(this) out of ajax object. It points now to ajax object itself. Try:
$("#sel").change(function(){
var _id = $(this).val();
$.ajax({
data: {id: _id},
...
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ _id,
**UPDATED**
Also, if the data is received from the server correctly but dropdown is still not rendered, the issue might be with the dataType property. There may be some problems with the response mime type, that cause the problem with the Intelligent Guess and data is treated as a json or xml string, so you can try to set it explicit:
$("#sel").change(function(){
var _id = $(this).val();
$.ajax({
data: {id: _id},
type: "POST",
dataType: 'html',
url:"<?= base_url() ?>BeneficiaryModule/showAvailable/"+ _id,
success:function(data){
$("#avail").html(data);
}
});
});

basic Dynamic Select list PHP & AJAX Jquery

I was trying to get a dynamic dependent select list using AJAX, but unable to get the second list. Here is my code. gethint.php is working fine. I don't know where I am doing wrong.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"</script>
<script>
$(document).ready(function()
{
$('#brand').change(function()
{
var cid=$('#brand').val();
if(cid !=0)
{
$.ajax({
type:'post',
url: 'gethint.php',
data: {id:cid},
cache:false,
success: function(returndata)
{
$('#model').html(returndata);
}
});
}
})
})
</script>
</head>
<body>
<header>
<h1>Car Comparision </h1>
</header>
<form method="post" action="">
Brand 1:
<select id="brand" class="brand">
<?php
include "connect.php";
$query=$con->query("SELECT * FROM car");
while($brand=$query->fetch_assoc())
{
$brand_sel='<option value="'.$brand['id'].'"'.">".$brand['brand'].'</option>'."\n";
echo $brand_sel;
}
?>
</select>
Model 1:
<select id="model" class="model">
<option value="0">Please select a city</option>
<option></option>
</select>
<input type="submit" value="submit">
</form>
</body>
</html>
code for my gethint.php file
<?php
require ("connect.php");
$Query='SELECT * FROM model WHERE id='.$_POST['id'];
$sql=$con->query($Query) or die(mysql_error());
//print_r($Query);
while($row=$sql->fetch_array(MYSQLI_ASSOC)) {
?>
<option value="<?php echo $row["id"];?>"><?php echo $row['model_name'];?></option>
<?php
}
?>
Pls try this code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$('#brand').on('change', function() {
var cid=$('#brand').val();
if(cid !=0)
{
$.ajax({
type:'post',
url: 'gethint.php',
data: {id:cid},
cache:false,
success: function(returndata)
{
$('#model').html(returndata);
}
});
}
})
})
</script>
I would do it of a different a way:
<?php
require ("connect.php");
$Query='SELECT * FROM model WHERE id='.$_POST['id'];
$sql=$con->query($Query) or die(mysql_error());
//print_r($Query);
$elements = [];
while($row=$sql->fetch_array(MYSQLI_ASSOC)) {
$item = ["id" => $row['id'], "model_name" => $row['model_name']]
array_push($elements , $item)
}
echo $elements;
?>
I would send a associative array which contains all the items of your select. I would also modify your script to:
<script>
$(document).ready(function()
{
$('#brand').change(function()
{
var cid=$('#brand').val();
if(cid !=0)
{
$.ajax({
type:'post',
url: 'gethint.php',
data: {id:cid},
cache:false,
success: function(returndata)
{
returndata.each(data,function(){
$('#model').append("<option value="+data.id+">"+data.model_name+"</option>")
})
}
});
}
})
})
</script>
I worried about really you are passing the right value to the ajax.
See the data render for first select is:
$brand_sel='<option value="'.$brand['id'].'"'.">".$brand['brand'].'</option>'."\n";
It should be like this:
$brand_sel='<option value="'.$brand['id'].'">'.$brand['brand'].'</option>\n';
As per my above comment please let us know if any error showing related to jQuery or PHP.
Also, check the passing data to ajax is in correct format.

Ajax with PHP same page not working

I have a dependent dropdown menu for category>subcategory without refreshing page with the help of Ajax. But currently my JavaScript code sends the Ajax request to another page and it works fine, i want to send the request to the same page. Currently using the JavaScript as below .. please anyone help me to get the request to the same page.
<script type="text/javascript">
$(document).ready(function(){
$(".category").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-subcat.php",
data: dataString,
cache: false,
success: function(html){
$(".subcat").html(html);
}
});
});
</script>
If I empty the Ajax url, still doesn't work for one page.
HTML as below
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
$sql=mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)){
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory:</label>
<select name="subcat" class="subcat">
</select>
ajax-subcat.php contains the below
if(isset($_POST['id'])){
$id=$_POST['id'];
$sql=mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row=mysqli_fetch_array($sql)){
$id=$row['sucat'];
$data=$row['sucat_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
I want to achieve this in 1 page, without sending request to other page. Please help.
Please remember to properly indent your code and make the necessary spaces for readability. Also, I advise you to separate your code, and put all the PHP part in classes provided for that purpose.
Try this :
Html file
<select id="category">
<?php
$sql = mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)) {
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory :</label>
<select id="subcat"></select>
<!-- Suppose you call the jquery here -->
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var id = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax-subcat.php',
data: json,
cache: false
}).done(function (data) {
$('#subcat').html(data);
}).fail(function (data) {
alert('You have a critic error');
});
});
});
</script>
You should call the php script with json, and have the callback with json_encode. This approach is cleaner. Also I set you the new ajax syntax. THe syntax you used with "success" is now deprecated.
Php file
<?php
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
$sql = mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row = mysqli_fetch_array($sql)) {
$id = $row['sucat'];
$data = $row['sucat_name'];
$return[] = '<option value="'.$id.'">'.$data.'</option>';
}
echo json_encode($return);
}
?>
Code not tested, but I think it work

.load page with form variables

I want to load a page with variables from a form and it seems it doesn't get my select value. I'm new to JavaScript and I need this instead doing a serialize to get values and then use .load().
Here is my code:
<?php
include('dbconfig.php');
$id=$_GET['id'];
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function filtreaza_tip () {
var tip = document.getElementById("tip").value;
var id_local= document.getElementById("id_local").value;
$( "#tipuri_rezervare" ).load("select_tip_rezervare.php?id="+id_local+"&tip="+tip);
}
</script>
</head>
<body>
<form id="tip" method="post">
<input type="hidden" name="id_local" id="id_local" value="<?php echo $id;?>">
<select name="tip" id="tip" onchange="filtreaza_tip();">
<option value="0">Selectati Tipul</option>
<?php
$stmt = $dbh->prepare("SELECT *
FROM Tip_Rezervare
INNER JOIN Local ON Local.ID_Local=:id_local
INNER JOIN Leg_Tip_Local ON Tip_Rezervare.ID_Tip=Leg_Tip_Local.ID_Tip and Leg_Tip_Local.ID_Local=:id_local");
$stmt->bindParam(':id_local', $id, PDO::PARAM_INT);
$stmt->execute() ;
while ($row = $stmt->fetch()) {
$local=$row['Denumire_Local'];
echo '<option value="'.$row['ID_Tip'].'">'.$row['Nume'].'</option>';
}
echo'</select>';
?>
<div id="tipuri_rezervare">
</div>
</body>
</html>
I have a working one with serialize but I don't want that. Here is the working code:
function filtreaza_tip ()
{
var datastring = $("#tip").serialize();
$.ajax({
type: "POST",
url: "tip_rezervare.php",
data: datastring,
success: function(data) {
$( "#tipuri_rezervare" ).load('select_tip_rezervare.php?',data);
}
});
}
Your form id and dropdown id are same.
Thats the reason you are getting the issue.
Change the ids it will work fine.
Load uses POST method so you can just do this:
var tip = document.getElementById("tip").value;
var id_local= document.getElementById("id_local").value;
$( "#tipuri_rezervare" ).load("select_tip_rezervare.php, {tip: tip, id: id_local});
Then you can get your values on your select_tip_rezervare.php page with $_POST['tip'] and $_POST['id'].
Use the jquery method $.val() like that :
$("#tip").val(); // Return the input / select value of the selector
Check the jQuery Api : http://api.jquery.com/val/

Categories