trouble in handling json response - javascript

I have two select box and want to populate 2nd select box based on onchange of first select box. so my code for first select box
<select id="category-box" name="category" onchange="showCrops()" >
<option value ="0">Select category</option>
<?php
$query = $con->query("Select*from categories");
while($row = $query->fetch_object())
{
echo "<option value = '".$row->category_id."'>".$row->category."</option>";
}
?>
</select>
onchange function for ajax call
function showCrops() {
var name = $('#category-box').val();
$.ajax({
type: "POST",
url: "getCropName.php",
data: {category:name},
dataType: 'json',
success: function(data, textStatus, jqXHR)
{
var opts = $.parseJSON(data);
$.each(opts, function(i,d) {
$('#crop-box').append('<option value="' + d.crop_id + '">' + d.crop_name + '</option>');
});
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log(textStatus);
}
});
}
php code to get response
header('Content-type: text/html; charset=utf-8');
include("connect.php");
$category = $_POST['category'];
$sql1 = $con->query("SELECT category_id from categories where category ='".$category."' ");
$row1= $sql1->fetch_array();
$sql2 = $con->query("SELECT * from crop_category where category_id ='".$row1['category_id']."' ");
while($row2 = $sql2->fetch_assoc()){
echo json_encode($row2);
}
json response is
{"crop_id":"1","category_id":"1","crop_name":"rice"} {"crop_id":"2","category_id":"1","crop_name":"wheat"}
but i'm getting 'parsererror' on main php page. Whats the problem in my code ? i have less knowledge in javascript so maybe need correction to populate by 2nd select box.

Just change the php code, so the right JSON string is generated ..
$arr = array();
while($row2 = $sql2->fetch_assoc()){
$arr[] = $row2;
}
echo json_encode($arr);

Related

Ajax request shows status of 200 in console but executing the error function

In my index.php file I have the following script that sends an ajax request:
$('#select-name').on('change', function () {
var selectedName = $(this).find('option:selected').val();
$.ajax({
type: "POST",
url: "assets/php/selectCar.php",
data: {
selectedName: JSON.stringify(selectedName)
},
dataType: "json",
contentType: "application/json",
success: function (data) {
$.each(data, function (i, value) {
$('.car-model').append('<option value = "'+value+'">'+value+'</option>');
});
},
error: function () {
alert("error");
}
});
});
The element with id select-name in the index.php file looks like:
<select name="car-name" id="select-name" class="form-control">
<option value="select_make">Choose make</option>
<?php
$stmt = "SELECT DISTINCT name FROM car_name";
if ($result = mysqli_query($conn, $stmt)) {
while($row = mysqli_fetch_array($result)){
echo '<option value = "'.$row['name'].'">'.$row['name'].'</option>';
}
}
?>
</select>
And the php statement in the above code works fine and renders the elements. The selectCar.php in which the request is sent to looks like:
<?php
require 'db.php';
$selectedName = $_POST['selectedName'];
$stmt = "SELECT DISTINCT model FROM model WHERE id IN ( SELECT model_id FROM cars WHERE name_id IN ( SELECT id FROM car_name WHERE name = '".$selectedName."'))";
$models = array();
$result = mysqli_query($conn, $stmt);
while($row = mysqli_fetch_array($result)){
$models[] = $row['model'];
}
echo json_encode($models) ;
?>
I have tested the sql statement substituting the value of $selectedName with the value I get when I alert selectedName in the script.
I have no idea why this isn't working. Any help would be appreciated. Thank you in advance.
Edit:- I have logged the error in the console and I see :
responseText: "<br />\n<b>Notice</b>: Undefined index: selectedName in <b>/opt/lampp/htdocs/wabi-cars/assets/php/selectCar.php</b> on line <b>3</b><br />\n[]"
and line 3 of selectCar.php is $selectedName = $_POST['selectedName'];

Ajax Success Returning Commented Html Tag

I am trying to set up a select box that would show up the cities depending on the prior selection of the state.
Basically, I am using ajax to run my php.file to populate my <option>. In the php file I successfully passed the pre-selected state to query the database. However, now, to populate the <option> I am using ajax success to call the php file, however, whenever I try to pass the variable containing the php code it shows up commented with !-- and --.
// hmtl
<select id="select-city" required >
<option disabled selected>Selecione sua Cidade</option>
</select>
// js code
function fillSelectCity () {
var getState = document.getElementById('selectState');
var stateID = getState.options[getState.selectedIndex].value;
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (){
var phpfile = "'fillcity.php'"
var tag = "<?php include_once " + phpfile + " ?>";
$('#select-city').html(tag);
/// here the output is "<!-- ?php include_once 'fillcity.php' ? -->"
}
})
}
//php file
<?php
$conn = mysqli_connect("host", "user", "pass", "db");
if(isset($_POST['stateID']))
{
$stateID = $_POST['stateID'];
}
$query = "SELECT * FROM states WHERE stateID = '$stateID'";
$result_one = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result_one); //my table has a specific ID for each state, so I am fetching the acronoym of the state according to the id;
$stateUf = $row['uf']; // passing the acronym to the $stateUf
mysqli_free_result($result_one);
$queryCity = "SELECT * FROM city WHERE Uf = '$stateUf'"; //query all cities with the acronym
if ($result = mysqli_query($conn, $queryCity)){
while ($row = mysqli_fetch_assoc($result)){
$id = $row['cityID'];
$name = $row['cityName'];
$name = utf8_encode($name);
echo <<< EOT
"<option value="$id">$name</option>"
EOT;
}
mysqli_free_result($result);}
else {echo "<option>Error</option>";}
?>
I expect to populate my select options by looping through the table city in the php file. The tag <?php include_once 'fillcity.php' ?> was used to populate the state select. Probably, there may be a more direct way to populate accordingly, but as I am new to programming, I am trying to figure things out on my own. But please, feel free to recommend other methods as I am not sure if what I am planning to do will gonna work. Thanks!
You can try this one. You can modify it later for improvement.
read.php
<?php
//include header
header('Content-Type: application/json');
$conn= mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$type = $_GET["type"];
if($type == "GetState"){
//SAMPLE QUERY
$sql = "SELECT StateID,StateName from State";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
if($type == "GetCity"){
$StateID= $_POST["StateID"];
//SAMPLE QUERY
//LET'S ASSUME THAT YOU HAVE FOREIGN KEY
$sql = "SELECT CityID,CityName from City where StateID = '".$StateID."'";
$data = array();
$results = $db -> query($sql);
while($row = mysqli_fetch_assoc($results)){
$data[] = $row;
}
echo json_encode($data);
}
?>
index.html
<select id="state"></select>
<select id="city"></select>
<!--PLEASE INCLUDE JQUERY RIGHT HERE E.G. <script src='jquery.min.js'></script>-->
<!--DOWNLOAD JQUERY HERE https://jquery.com/-->
<script>
LoadState();
function LoadState(){
$.ajax({
url:"read.php?type=GetState",
type:"GET",
success:function(data){
var options = "<option selected disabled value="">Select
State</option>";
for(var i in data){
options += "<option value='"+data[i].StateID+"'>" + data[i].StateName+ "</option>";
}
$("#state").html(options);
}
});
}
function LoadCity(StateID){
$.ajax({
url:"read.php?type=GetCity",
type:"POST",
data:{
StateID: StateID
},
success:function(data){
var options = "<option selected disabled value="">Select City</option>";
for(var i in data){
options += "<option value='"+data[i].CityID+"'>" + data[i].CityName+ "</option>";
}
$("#city").html(options);
}
});
}
$("#city").change(function(){
LoadCity(this.value);
});
You don't need to include 'fillcity.php. The AJAX call runs that script, and the response is the output. It will be in the parameter of the success function.
function fillSelectCity () {
var getState = $("#selectState").val();
$.ajax ({
type: "POST",
url: "fillcity.php",
data: { stateID : stateID },
success: function (tag){
$('#select-city').html(tag);
}
});
}

How to add a <select> <option> with jquery dynamically?

Changed value of <select> on success response from API with:
jQuery('#vat').val(response);
With this returned value can be placed into a textbox, but need to change the selected value of a combobox.
How to realize this?
Here is jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getVat() { // Do an Ajax request to retrieve the product price
console.log("getVat before ajax", jQuery('#product_name').val());
jQuery.ajax({
url: './get/vat/get1.php',
method: 'POST',
data: {'id' : jQuery('#product_name').val()},
success: function(response){
console.log("getPrice after ajax", jQuery('#product_name').val());
jQuery('#vat').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The script works when #vat is a textbox but not when #vat is a combobox.
Update:
Here is the script been using for the combobox:
<?php
$dbname = 'db';
$dbuser = 'root';
$dbpass = 'pass';
$db = new mysqli('localhost', $dbuser, $dbpass, $dbname);
if (!$db) {
exit('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
?>
<select style="width:100%" id="vat" name="vat">
<option value = "0">No VAT</option>
<?php
$queryusers = "SELECT id, internal_id, name FROM vat";
$db = mysqli_query($db, $queryusers);
while ( $d=mysqli_fetch_assoc($db)) {
echo "<option value='".$d['id']."'>".$d['internal_id']." | ".$d['name']."</option>";
}
?>
</select>
Update 2:
The selected value is changed to '1'. But the script still shows <option value = "0">No VAT</option>. Does someone know how I can update the data that is shown.
Update 3:
I just get a extra option when I run the following script. The value that is represented as the selected value is still the same:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getVat() { // Do an Ajax request to retrieve the product price
console.log("getVat before ajax", jQuery('#product_name').val());
jQuery.ajax({
url: './get/vat/get1.php',
method: 'POST',
data: {'id' : jQuery('#product_name').val()},
success: function(response){
// and put the price in text field
var newOption = "<option value=" + response + ">" + response + "</option>";
$("#vat").append(newOption);
$("#vat").val(response);
getPrice();
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
You are right <select> value will be changed with $("#vat").val(1). However this will not create a new <option>. If there would be an <option value="1"> then this option would have been shown. Since it doesn't exist thus HTML have nothing to show and showing default <option> of <select>.
You need to create a <option> and append it to <select>.
Here's jQuery on success:
var newOption = `<option value=` + response + `>` + response + `</option>`;
$("#vat").append(newOption);
$("#vat").val(response);

Javascript Ajax are not getting data in the dropdown Select tag in php (PDO)

i am having a problem with one of my scripts , i wanted to show data on dropdown select tag but their is a problem with my javascript it's not working even the alert() is not responding maybe it's because of the functions i wrote. by the way php data is good and getting it's output from the pages in array format
home.php
<div class="form-group">
<span class="label label-default">Country</span>
<select class="form-control" id="country1">
<div class="form-group">
<span class="label label-default" >Province</span>
<select class="form-control"id="province1">
</select>
</div>
Now the Javascript Code which is creating problem
<script type="text/javascript">
function country() {
$('#country1').empty();
$('#country1').append("<option> Loading --- </option>");
$('#province1').append("<option value='0'>--Select Province-- </option>");
$.ajax({
type:"POST",
url:"country_dropdown.php",
contentType:"application/json; charset=utf-8",
datatype:"json",
success: fuction(data) {
$('#country1').empty();
$('#country1').append("<option value='0'>-- Select Country---</option>");
$.each(data,function(i,item){
$('#country1').append('<option value="'+data[i].CountryID + '">'+ data[i].CountryName +'</option>');
});
},
complete : function() {
}
});
}
$(document).ready(function(){
country();
});
function province(id) {
$('#province1').empty();
$('#province1').append("<option> Loading --- </option>");
$.ajax ({
type:"POST",
url:"province_dropdown.php?id"+id,
contentType:"application/json"
charset:"utf-8",
dataType:"json",
success: function(data){
$('#province1').empty();
$('#province1').append("<option value='0'> --Select Province-- </option>");
$.each(data,function(i.item)
$('#province1').append('<option value="'+data[i].ProvinceID+'">'+data[i].ProvinceName+'</option>');
});
complete: function() {
}
});
}
</script>
My database Connection seems to be fine as both the files are getting the results
country_dropdown.php
<?php
include('config.php');
include('class.user.php');
try {
$obj = new USER();
$stmt = $obj->getCountry();
echo "{";
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){
echo '"'.$result['CountryID'].'":"'.$result['CountryName'].'",';
}
echo '"0":"Select Country"}';
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
header('Content-type: application/json');
?>
province_dropdown.php
<?php
include('config.php');
include('class.user.php');
try {
$obj = new USER();
$stmt = $obj->getProvince();
echo "{";
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){
echo '"'.$result['ProvinceID'].'":"'.$result['ProvinceName'].'",';
}
echo '"0":"Select Province"}';
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
header('Content-type: application/json');
?>
class.user.php file which has the functions to query the data ,they are also working fine but i think it should also be consider as any possible problem can came from the start
class.user.php
public function getCountry() {
$stmt =$this->conn->prepare("SELECT * FROM country");
$stmt->execute();
return $stmt;
}
public function getProvince(){
$stmt =$this->conn->prepare("SELECT * FROM province WHERE Country_CountryID='".$_GET["id"]."'");
$stmt->execute();
return $stmt;
}
The problem is in here as both these select tags can't get values as country value index correspond to the province , so province is dependent upon the country
First, where is your event handler for when you change the country?
Second, you have bunch of typo-like errors in your code.
Here's some fixes:
$(document).ready(function() {
// cache the elements that you will be re-using
var $country = $('#country1'), $province = $('#province1');
// renamed
function getCountries() {
$country.html("<option> Loading --- </option>");
$province.html("<option value='0'>--Select Province-- </option>");
$.ajax({
type: "POST",
url: "country_dropdown.php",
// typo: datatype:"json"
dataType: "json",
// error: success: fuction (data) {
success: function (data) {
$country.html("<option value='0'>-- Select Country---</option>"); // simplified
$.each(data, function (i, item) {
$country.append('<option value="' + item.CountryID + '">' + item.CountryName + '</option>');
});
// attach event listener to the country dropdown, so that when the country changes, we load the related provinces
$country.on('change', getProvinces);
// trigger event listener ^ to get related country's provinces
$country.trigger('change');
}
});
}
// renamed
function getProvinces() {
$province.html("<option> Loading --- </option>"); // simplified
$.ajax ({
type: "POST",
url: "province_dropdown.php?id" + $(this).val(),
dataType: "json",
success: function (data) {
$province.html("<option value='0'> --Select Province-- </option>"); // simplified
// error: $.each(data, function(i.item)
$.each(data, function (i, item) {
// error: ('#province1').append(...)
$province.append('<option value="' + item.ProvinceID + '">' + item.ProvinceName + '</option>');
});
}
});
}
// load the countries
getCountries();
});
Another thing, the whole point of using prepare() is to avoid SQL injection. The way that you are using it is wrong in the second function.
class.user.php
public function getCountry() {
$stmt = $this->conn->query("SELECT * FROM country"); // no need to use prepare() as you are not using any untrusted data
return $stmt;
}
// renamed
public function getProvinceByCountry($id) {
$stmt = $this->conn->prepare("SELECT * FROM province WHERE Country_CountryID = ?"); // notice the '?' ?
$stmt->execute(array($id));
return $stmt;
}
You shouldn't need to build your JSON object. Use json_encode().
country_dropdown.php
<?php
include('config.php');
include('class.user.php');
try {
$obj = new USER();
$stmt = $obj->getCountry();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null; //unnecessary
header('Content-type: application/json');
echo json_encode($results);
?>
province_dropdown.php
<?php
include('config.php');
include('class.user.php');
try {
$obj = new USER();
$stmt = $obj->getProvinceByCountry($_GET["id"]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null; //unnecessary
header('Content-type: application/json');
echo json_encode($results);
?>
The getProvince() function in your class.user.php code contains a syntax error here: ='".$_GET["id"]."'" - It should be ="'".$_GET["id"]."'". Also, when writing a database and column name I think it should be a period and not an underscore, but I'm not 100% sure about that.
there are some errors in the script, i can't test the ajax respons by with the chrome console I found something wrong. i've tried to replace your script, it doesn't give the error in the console, I hope it is helpfull.
function country() {
$('#country1').empty();
$('#country1').append("<option> Loading --- </option>");
$('#province1').append("<option value='0'>--Select Province-- </option>");
$.ajax({
type: "POST",
url: "country_dropdown.php",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(data) {
$('#country1').empty();
$('#country1').append("<option value='0'>-- Select Country---</option>");
$.each(data, function(i, item) {
$('#country1').append('<option value="' + data[i].CountryID + '">' + data[i].CountryName + '</option>');
});
},
complete: function() {
}
});
};
$(document).ready(function() {
country();
});
function province(id) {
$('#province1').empty();
$('#province1').append("<option> Loading --- </option>");
$.ajax({
type: "POST",
url: "province_dropdown.php?id=" + id,
contentType: "application/json"
charset: "utf-8",
dataType: "json",
success: function(data) {
$('#province1').empty();
$('#province1').append("<option value='0'> --Select Province-- </option>");
$.each(data, function(i,item) {
$('#province1').append('<option value="' + data[i].ProvinceID + '">' + data[i].ProvinceName + '</option>');
}),
complete: function() {
}
}
} );
};

Trying to populate a drop down list with jquery and ajax

Here's my code :-
<script>
$(document).ready(function(){ //#This script uses jquery and ajax it is used to set the values in
$("#day").change(function(){ //# the time field whenever a day is selected.
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
dataType : 'json',
success:function(data){
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.res + '</option>';
});
$('#timing').html(option);
}
});
});
});
</script>
And here's the php script.
<?
$con=mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query="SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
$i = 0; //Initialize the variable which passes over the array key values
$row = mysqli_fetch_assoc($result); //Fetches an associative array of the row
$index = array_keys($row); // Fetches an array of keys for the row.
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
$res = $index[$i];
echo json_encode($res);
}
$i++;
}
?>
I want options with time values inserted inside a select on my html page which looks something like this :-
<select id="timing" name="timing"></select>
My java script code is posting values to the php script alright but the code is still not working. There aren't any errors in my javascript as I see it. Kindly help me out
var postUrl = "time.php";
$.ajax({
type: "POST",
url: postUrl,
data: {day: day,doctor: doctor},
dataType: "json",
success: function (data) {
$.each(data, function (key, value) {
$('#timing').append('<option value="' + key + '">' + value + '</option>');
});
}
});
hope it's help to you
success:function(data){
var select= '<select>';
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.res + '</option>';
});
select = select+option'</select>';
$('#timing').html(select);
}
HTML :
<div id="timing"> </div>
var day=$("#day option:selected").val();
var doctor=$("#doctor option:selected").val();
data:"{day:'"+day+"', doctor: '" + doctor + "'}" ,

Categories