Sending Ajax Request to PHP not working - javascript

I am trying to make an ajax request to my PHP file.
The ajax request occurs when my "Country" select option menu changes. The result is suppose to be a new select option menu titled "State Province" and the options would be based off the choice made in the "Country" select option menu.
This is what I want it to look like:
The problem I'm having is when the ajax is making a request to the PHP, the PHP seems to be returning an empty array:
Does anyone know what might be wrong?
Thank you!
HTML for the select option:
<select name="Country" class="form-control input-sm" id="Country">
</select>
Ajax code with the onchange function:
$("#Country").on("change",function(){
var val = $('#Country').val();
performAJAX(val,'Country','StateProvince');
});
function performAJAX(choice,prevSelect,newSelect){
$.ajax({
type: "post",
url: "select-creation.php",
data: {choice: choice, prevSelect: prevSelect,newSelect: newSelect},
dataType: "json",
success: function(data){
var obj = $.parseJSON(data);
console.log("meow meow");
}
});
}
PHP code:
<?php session_start();
try{
$choice = $_POST['choice'];
$prevAttri = $_POST['prevSelect'];
$nxtAttri = $_POST['newSelect'];
$data = array();
$sql = 'SELECT '.$nxtAttri.' FROM agents WHERE '.$prevAttri.' = :userChoice';
include_once $_SERVER['DOCUMENT_ROOT'].'/inc/Database.class.php';
$db = new Database();
$conn = $db->getConnection();
$query = $conn->prepare($sql);
$query->bindValue(':userChoice',$choice,PDO::PARAM_STR);
if($query->execute()){
$data = $query->fetchAll(PDO::FETCH_ASSOC);
}//stmt
return json_encode($data);
}catch(PDOException $e){
echo $e->getMessage();
}
?>

Your code return json_encode($data); seems to be nothing or invalid because your code doesn't use a function.
Just use echo json_encode($data);
In the ajax side, you don't need to use $.parseJSON(data); because you already specify the dataType to json it will immediately convert the data response by PHP to an object type.

Related

How to fetch mutiple values on select option and display in input type using ajax?

I'm trying to fetch mutiple values from database using ajax php.
I've a select option(value is fetching from database), and if i select any option then i want to display the related data which is matching with the id
of the the current option.but currently i'm able to fetch only one data column from databse.
I'm writing my current code please have a look at it and let me know how can i modify it.
My select option:-
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' onChange="getCity(this.value);" id="vno" required='true' >
<option value="">Select</option>
<?php
foreach($results as $vd) { ?>
<option value='<?php echo $vd['id'];?>'><?php echo $vd['vno'];?></option>";
<?php } ?>
</select>
and the js file
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:'id='+val,
success: function(data){
$("#rate").html(data);
}
});
}
retrive_data.php
<?php
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
$query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
$results = $db_handle->runQuery($query);
?>
<?php
foreach ($results as $city) {
?>
<option value="<?php echo $city["rate"]; ?>"><?php echo $city["rate"]; ?></option>
<?php
}
}
?>
Change your js code as below
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php?id=" + val,
success: function(data){
$("#rate").html(data);
}
});
}
I’m making some assumptions about the desired result, and I’m not sure what the connection is between vehicles and city rates... but there are multiple issues here. Let’s work through them:
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' id="vno" required='true' >
<option value="">Select</option>
<?php foreach($results as $vd): ?>
<option value="<?= $vd['id']?>" ><?= $vd['vno'] ?></option>";
<?php endforeach; ?>
</select>
<!-- add a landing spot for the data coming in -->
<select id="rate"></select>
Nothing major here, just took out the onChange (typical practice is to have a listener in the JavaScript. Separation of concerns)
In your JavaScript, I don’t think you were successfully passing the id. It should be a JavaScript object. Also, send data to a function that knows how to put the data in your form:
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:{id: val},
success: function(data){
showRate(data);
}
});
}
Monitor the select for a change. (JavaScript should be inside document ready block)
$('#vno').on('change', function (){
getCity($(this).val());
});
Function to display the results of your ajax call:
showRate(data) {
// this lets you see the data that was returned
console.log(data);
var rate = $('#rate');
// clear current content
rate.html('');
// create options, assuming this is a select
$.each(data, function() {
rate.append($("<option />").val(this.rate).text(this.rate));
});
}
retrieve.php
Need to use prepared statements, and sending data as json instead of html is recommended
<?php
// sending json (data), not html (presentation)
header('Content-Type: application/json');
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
// substituting variables in a query is a big no-no
// $query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
// must use placeholders / prepared statement
$query = "SELECT * FROM tbl_vehicle WHERE id = ?'";
// check your database object for how to do prepared statements and row fetching. If it doesn’t do prepared statements, dump it!
$stmt = $db_handle->prepare ($query);
$stmt->execute($_POST["id"]);
$out = array();
while($row = $stmt->fetch() ) {
$rate = $row['rate'];
$out[] = array(
'rate'=>$rate
);
}
die(json_encode($out));
}
Caveat: all code is off the top of my head, and typed on a phone. Syntax errors are likely. This is intended to show concepts and ideas for further research

Ajax show Dynamic data of php in html drop down

I am trying to get the data from a database and populate then in a drop down in the code below.
I am unable to populate them as the data output says:
"undefined index: selectid" from php ma be the data is not passing from ajax or the php is unable to read.
HTML:
<select id="dynamicDropdown"></select>
JS:
var storedValue = localStorage.getItem("id");
$.ajax({
url : "DD.php",
data: {"storedValue":storedValue},
success : function(data){
alert(data);
console.log(data) // data should be an array that you have mentioned.
data.map(function(c){
$("#dynamicDropdown").append("<option value="+c.C_CO+">"+c.C_NAME1+"</option>");
});
}
});
};
PHP:
$mysqli=mysqli_connect('xxx','xxx','xxx','xxx');
$selectid = mysqli_real_escape_string($mysqli,trim($_POST['storedValue']));
$query112 ="SELECT * FROM dd_table WHERE id='$selectid'";
$result112 = mysqli_query($mysqli,$query112)or die(mysqli_error());
$num_row112 = mysqli_num_rows($result112);
while($row=mysqli_fetch_array($result112))
{
$response = array($row['dd_data'] );
echo json_encode($response);
}
I might be wrong but shouldn't you write it like this :
$query112 ="SELECT * FROM dd_table WHERE id='".$selectid."'"; ?
You don't need any jQuery for that:
Try this:
<select>
<?php
foreach(mysqli_fetch_array($result112) as $x){
echo "<option>". $x['dd_data']. "</option>";
}
?>
</select>

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

How do I get JSON from URL and set its value to texfield?

I have some URL mysite.com/json.php, which returns something like this : [{"invoice_number":"INV#20101"}]
on another page I have a <input type="hidden" id="myinvoice" />
I just wanted to set that invoice_number value to this hidden field withJQuery. How can I do this?
on JSON page I have converted JSON with this code :
<?php
$return_arr = array();
$fetch = mysql_query("SELECT invoice_number FROM db_stocks ORDER BY stock_id DESC LIMIT 1 ");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['invoice_number'] = $row['invoice_number'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
You can use jQuery.ajax() to get the returned array then set the value.
$.ajax({
url: "json.php",
success: function(data) {
$("#myinvoice").val(data[0].invoice_number);
}
});
You can use the following jquery:
$.get('mysite.com/json.php', function(data){
$('#myinvoice').val(data[0].invoice_number);
} 'json');
Also please don't use mysql but use pdo or mysqli instead, see why-shouldnt-i-use-mysql-functions-in-php for more information about this.

fetch rows from mysql using Ajax

I am trying to retrieve a row from mysql db using ajax, code bellow:
jQuery.ajax({
type: 'POST',
url: 'Connection.php',
dataType: 'text',
data: {'query_id' : query_id},
success: function(response){
data = response;
alert(data['username']); //print undefined!!!
},
error: function(xhr, ajaxOptions, thrownError){
alert("thrownError");
}
});
Here is my mysql php code:
<?php
$con = mysql_connect('****','****','****');
mysql_select_db("eBay",$con);
$username = $_SESSION['username'];
$query_id = $_POST['query_id'];
$myquery = "SELECT * FROM `Output` WHERE `username` =" '$username';
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
}
$data = mysql_fetch_array($query);
echo ($data);
mysql_close($server);
?>
In the response I get, I have undefined array cell. Any idea?
to return just the username from php:
$data = mysql_fetch_assoc($query)['username'];
in your javascript you should be able to do alert(data) instead of searching for the username tuple in an array.
Ideally you should return your data back in json instead of text that way it can remain structured and easier to access in javascript. You will need to change your ajax option to dataType: 'json'
and the PHP code to :
$data = json_encode(mysql_fetch_assoc($query));
You are getting array in $data variable so you should use json_encode function to get all values from resulting row like this-
$myquery = "SELECT * FROM `Output` WHERE `username` ='".$username."'";
foreach ($myquery as $test)
{
$field1_value =$test->name_of_field1_in_db;
$field2_value =$test->name_of_field2_in_db;
$field3_value =$test->name_of_field3_in_db;
}
$all_values_in_array=array('field1'=>$field1_value,'field2'=>$field2_value,'field3'=>$field3_value,);
echo json_encode(echo json_encode($arr_provider);
and get all value on ajax suucess function like this--
success: function(response){
var pro = jQuery.parseJSON(response);
var field1_val=pro.field1; //var field1 contain value of field1 in db
var field2_val=pro.field2;
var field3_val=pro.field3;
},
hope it will help you.
Best of Luck

Categories