Ajax Code work on localhost but not on server - php

I am working on 2 dependent dropdowns (Country, State). On the bases of previous selection, new drop-down options will open using ajax. My code works fine in localhost but on the server, it doesn't fetch any data(ajax not working on the server). I am using 2 files(Reg.php, getState.php) code is here, plz help.
Reg.php
<?php
require("../conn.php");
$query ="SELECT * FROM country";
$results=mysqli_query($con,$query);
?>
<html>
<head>
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "getState.php",
data:'country_id='+val,
success: function(data){
$("#state-list").html(data);
getCity();
}
});
}
</script>
</head>
<body>
<select name="country" id="country-list" onChange="getState(this.value);">
<option value="">Select Country</option>
<?php
foreach($results as $country) {
?>
<option value="<?php echo $country["id"]; ?>"><?php echo
$country["country_name"]; ?></option>
<?php
}
?>
</select>
<select name="state" id="state-list" class="form-control" style="width:100%;" onChange="getCity(this.value);">
<option value="">Select State</option>
</select>
</body>
</html>
getState.php
<?php
require("../conn.php");
if (! empty($_POST["country_id"])) {
$query = "SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results=mysqli_query($con,$query);
?>
<option value disabled selected>Select State</option>
<?php
foreach ($results as $state) {
?>
<option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?>
</option>
<?php
}
}
?>

Please try this code for getting data from ajax.
function getState(val) {
$.ajax({
method: "POST",
url: "getState.php",
data: { country_id: val }
})
.done(function( data ) {
$("#state-list").html(data);
});
}

In the above code foreach loop working well on localhost but not on the server, I replace the foreach loop with while loop and get the country & city name. Thanks to everyone

Related

Populating 2nd select box with the value of first select box

Currently I have 2 select boxes called Country and City. Now I've made it so that the city data is populated according to the value selected in country using AJAX. To do this I've used the following code:
edit.php:
<select name="country" onchange="getcities($(this).val())" required>
<option value="<?php echo set_value('country'); ?>">Select Country</option>
<?php if($countries) foreach($countries as $country): ?>
<option value="<?php echo $country['id']; ?>" <?php echo ($listing[0]['country'] == $country['id'])?'selected="selected"':''?>><?php echo $country['name']; ?></option>
<?php endforeach; ?>
</select>
<label class="control-labels ">City</label>
<div id="emiratewrap">
<select name="emirate" id="emirate">
<option value="">Select City</option>
</select>
AJAX
$(document).ready(function () {
getcities($('#country').val());
});
function getcities(obj){
console.log(obj);
var dataString = new Object();
dataString.emirate = '<?php echo $property->emirate ?>';
$.ajax({
type: "get",
dataType:"json",
url: "<?php echo site_url('listings/ajaxgetcitiesedit'); ?>/"+obj,
data: dataString,
success: function(e) { $('#emiratewrap').html(e.result);
$bb = "<?php echo $property->status; ?>";
if($bb=="Y") {$("#emiratewrap select").addClass("disabled"); }
}
});
}
Controller:
function ajaxgetcitiesedit($country=''){
$emirate = $this->input->get('emirate');
if(!$country) return false;
$cities = $this->listings_model->get_activepair_cities(array('country_id'=>$country),'*','name asc');
$html = '<select name="emirate" id="emirate" class="form-control select2 required" onchange="oemirate(this);">';
$html .= ($emirate <1)? '<option value="">Select Emirate</option>':'';
foreach($cities as $city):
$html .= '<option value="'.$city['id'].'" '.($city['id'] == $emirate ? 'selected="selected"' : '').'>'.$city['name'].'</option>';
endforeach;
$html .= '<option value="Other">Other</option> </select><input type="text" id="other_emirate" name="other_emirate" class="form-control" style="display: none;" />';
echo json_encode(array('result'=>$html));
}
Now currently I'm working on edit page where it should initially show what value the user had selected while adding the entry. As of now the functionality of the second select works fine as intended as it changes its options when the 1st select data is changed and also gives the correct value in database when update is pressed.
Now the only problem here I have is that initially when loading into the page, it doesn't show anything in the second select box even though there is a value for it in the database. I performed a console.log(obj); in getcities(obj) and initially it returned undefined and everytime I change country, it gives a value in my log.

Second Dropdown concern, Php, Ajax

This code comes from a guide I've seen in YouTube.
I'm trying to populate the second dropdown based on the choices on the first dropdown, in my test page its working, however when I tried to attach it to my main page, the second dropdown is not turning into a dropdown.
I've tried to re-code it, but still the problem persist.
This is for the AJAX
<?php
include('db.php');
if($_POST['id']){
$id=$_POST['id'];
if($id==0){
echo "<option value='0'>Select Type</option>";
}else{
$sql = mysqli_query($con,"SELECT * FROM `ConcernType` WHERE Concern_Id='$id'");
while($row = mysqli_fetch_array($sql)){
echo '<option value="'.$row['ConcernType_id'].'">'.$row['ConcernType_name'].'</option>';
}
}
}
?>
This is for the index.php
<label>Concern Category :</label><select name="concerncategory" class="concerncategory">
<option value="0">Select Category</option>
<?php
include('db.php');
$sql = mysqli_query($con,"select * from ConcernCategory");
while($row=mysqli_fetch_array($sql))
{
echo '<option value="'.$row['Concern_Id'].'">'.$row['ConcernCategory_name'].'</option>';
} ?>
</select><br/><br/>
<label>Concern Type :</label><select name="concerntype" class="concerntype">
<option value="0">Select Type</option>
</select>
<br /><br />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".concerncategory").change(function()
{
var Concern_Id=$(this).val();
var post_id = 'id='+ Concern_Id;
$.ajax ({
type: "POST", url: "ajax.php", data: post_id, cache: false,
success: function(Type) {
$(".concerntype").html(Type);
} }); }); });
</script>
Here are some screenshots.
https://ibb.co/2NTTdG8
https://ibb.co/fFXBzFS

Select row table using ajax and php

I have a drop menu that includes some category every category has their own subcategory i want to show them buy selecting category name
but it's not working, did i miss something or am i doing it completely wrong?
<script type="text/javascript">
$(function() {
$("#error").hide();
$("#category").change(function(){
$("#error").hide();
var category = $("#category").val();
if (category == "") {
$("#error").show();
return false;
}
var data = $("#form").serialize();
$.ajax({
type:"POST",
url:"index.php",
data:data,
success: function(){
}
});
return false;
});
});
</script>
<form id="form" name="form">
<label for="category" id="error">Empty</label>
<select name="category" id="category">
<option></option>
<option value="News">News</option>
<option value="Items">Items</option>
<option value="Updates">Updates</option>
</select>
</form>
<?php
include("connect.php");
if(!empty($_POST['category'])){
$sql=$con->prepare("SELECT * FROM categorys WHERE category=:category ");
$sql->bindparam(":category",$_POST['category']);
$sql->execute();
while($r=$sql->fetch()){
echo $r['subcategory'];
}
}
?>
SomePage.php
<form id="form" name="form">
<div id='category'>
<label for="category" id="error">Empty</label>
<select name="category" id="category">
<option></option>
<option value="News">News</option>
<option value="Items">Items</option>
<option value="Updates">Updates</option>
</select>
</div>
<div id='subcategory'>
</div>
</form>
<script>
$('#category').change(function(){
var CatName= $('#category').val();
$.ajax({url:"AjaxSelectCategory.php?CatName="+CatName,cache:false,success:function(result){
$('#subcategory').html(result);
}});
});
</script>
Create New Page AjaxSelectCategory.php
[NOTE: If you want to change this page name. Change in <script></script> tag too. Both are related.]
<?php
include("connect.php");
if(!empty($_GET['CatName']))
{
$sql=$con->prepare("SELECT * FROM categorys WHERE category=:category ");
$sql->bindparam(":category",$_GET['CatName']);
$sql->execute();
?>
<select name='subcategory'>
<?php
while($r=$sql->fetch())
{?>
<option value="<?php echo $r['subcategory'];?>"><?php echo $r['subcategory'];?></option>
</select>
<?php }
}?>
Try like this,
$.ajax({
type:"POST",
url:"get_subcategory.php",
data:data,
success: function(data){
alert(data)// this will have the second dropdown. add to desired place in your view.
}
});
In get_subcategory.php
$sql = "Select * from table_name where catregory = ".$_POST'category'];
// execute the query.
$sub = "<select name='sub-category'>";
foreach(result from database as $row) {
$sub .= "<option value='$row->id'>$row->name</option>";
}
$sub .= "</select>";
echo $sub;

hold values of dropdown using ajax

there are two drop downs naming country and state.....so how to hold the values whwn error occurs in the form.i have used ajax to list the state value
<select name="country" onchange="getstate(this.value,'')">
<option value="">Select</option>
<?php $option="";
$query="select * from tbl_country";
$res=mysql_query($query);
while ($country=mysql_fetch_array($res)) {?>
<option value="<?php echo $country['id']; ?>"><?php echo $country['country']; ?></option>
<?php }?>
</select>
<select id="state" >
</select>
/////ajax code///////
<script type="text/javascript">
function getstate(id) {
$.ajax({
type : 'post',
url : 'ajax.php',
data : {
act : 'get_state',
country : id,
},
success : function(data) {
data = data.replace(/\s*\n\s*/g, '');
if (data) {
document.getElementById('state').innerHTML = data;
} else {
}
return true;
}
});
}
</script>
///////ajax.php/////
if($_REQUEST['act']=="get_state"){
$statelist=array();
$countryid=$_REQUEST['country'];
$query="select * from tbl_state where id_country=".$countryid;
$result=mysql_query($query);
$option.='<option value="">select</option>';
while ($state=mysql_fetch_array($result)) {
$option.= '<option value="'.$state["state"].'">'.$state["state"].'</option>';
}
echo $option;
}
I want to hold both the values of country and state at the time of form submit(error occurs). how to do that?

PHP Echoe selected value via JS/AJAX Post

I am using a JS/Ajax function to echo Selected values from select boxes. I am populating these select boxes with values from MySQL DB. The function works with text input fields but now that I am using it with these select boxes I am getting no response.
Can I echo the selected value from a select box with the JS? or Is there a better way? EXAMPLE
JS
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#category_form').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>
PHP/HTML
try {
$pdo = get_database_connection();
$sql = "SELECT *
FROM `categories`
WHERE `master_id` = 0";
$statement = $pdo->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'There was a problem';
}
<form action="" method="post" id="category_form'" name="category_form'">
<select name="main" id="main" size="7" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="subc1" id="subc1" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
<select name="subc2" id="subc2" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
<select name="subc3" id="subc3" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
</form>
<div id="special"></div>
It looks like you're selecting the wrong element with jQuery.
Change:
$('#category_form').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
To:
$('#main').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});

Categories