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/
Related
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.
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.
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
I have got 2 files, one named index.php and one named api.php. I am trying to retrieve some data from my DB and I've done this simple example before trying to put the code into my project. In the api.php file I ve got the following:
$connessione=mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
$scelta_db=mysql_select_db(DB_NAME) or die(mysql_error());
$idM=67;
$result = mysql_query("SELECT * FROM map_comment WHERE idMap ='$idM'");
$array = array();
while ( $row = mysql_fetch_row($result) )
{
$array[] = $row;
}
echo json_encode($array);
While in the index.php:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
<h3>Output: </h3>
<div id="output">Attacco qua sotto</div>
<button onclick ='show_comments'>Carica commenti </button>
<script id="source" language="javascript" type="text/javascript">
function show_comments()
{
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var idU = row[1];
var text_map = row[3];
$('#output').append("<b> idU: </b>"+idU+"<b>text </b>"+text_map)
.append("<hr />");
}
}
});
};
</script>
</body>
</html>
The problem is that it does not seems to "append" nothing and I dunno what I am doing wrong. I KNOW I should use mysqli, I'll fix that. Plus: HOW can I "send" a $idM to the api.php from the index.php (for example an $id already defined in the index.php)?
Your function is not called when you click the button, in an onclick attribute you're not setting a function but rather writing code to execute. See example below
<button onclick ='show_comments()'>...
To send the id, you can use the data parameter
data: {id: 67},
Since this is a GET request you can use the php super global $_GET to retrieve the value $_GET['id'].
I am trying to populate an initial customer select box with results from PDO MySql via PHP. Then I would like the second contact select box to update with additional information related to what was chosen in the first box. I can't get the second script to work. I think the problem is in my ajax script because the PHP scripts work fine when ran on there own.
The Primary Script
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#contact").change(function(){
var cid = $("#cid").val();
$.ajax({
type:"post",
url:"contact.php",
data:"cid="+cid,
success: function(data) {
$("#contact").html(data);
}
});
});
});
</script>
</head>
<body>
Campaign :
<select name="customer" id="customer">
<option>-Select a Customer-</option>
<?php
include ("function.php");
include("connect.php");
$id = $_SESSION['profile']['id'];
foreach($db->query("SELECT * FROM customers WHERE pid = '$id'") as $row) {
echo "<option value=" . $row['id'] . ">" . $row['name'] . "</option>";
}
?>
</select>
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
</body>
</html>
The Contact script
include("connect.php");
$cid = $_POST["cid"];
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
Maybe your second function should start on #customer change
I see you used the contact select in ajax not customer as you described. However the code you wrote, you used the contact selector with change event, But the contact select box contain only one value, How can it change ??
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
The previous select should has more than option to can change. Or I think you mean the #customer instead contact as following:-
$("#customer").change(function(){
// your code;
});
Why not just encode a JSON response with the ids and names?
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
$arr[] = array("id" => $row['id'], "name" => $row['name']);
}
echo json_encode($arr);
Then in your ajax response, you could do
$(document).ready(function () {
$("#customer").change(function () {
var cid = $("#customer").val();
$.ajax({
type: "post",
url: "contact.php",
data: {cid: cid},
success: function (data) {
var options = [];
$.each(data, function () {
options.push('<option value="' + this.id + '">' + this.name + '</option>');
});
$("#contact").html(options.join(""));
}
});
});
});