AJAX and PDO problems - javascript

OK so I have been for 2 days trying to do this but for some reason, doesn't matter in what way I do it, it doesn't work (I tried different way with json_encode and then taking care of creating the elements with javascript, I've tried to echo the in the php itself, I've tried to return it, nothing really works)
What I'm trying to do is use AJAX to ask the server for a specific script (right now test.php) and then return the <option>'s so I can populate a <select>, so I'm trying to populate a comboBox, what seems to be happening is that the AJAX response is coming out empty, I tried to output the result and it was outputting an empty value. Can anyone please help me, I'm really desperate at this point, it should have been easy, I've spent hours on stack overflow trying to find the problem, I've debugged the code to the best of my ability, I've read everything relevant in the jquery documentation. well anyways my setting my suffering aside, here's the code:
comboStaging.php :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form id="testForm">
<select name="states" id="states">
<?php
$odb = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "SELECT id, name FROM `database`.pt_state";
$data = $odb->prepare($query);
$data->execute();
while ($row = $data->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
//print_r($row);
}
?>
</select>
<select name="cities" id="cities">
</select>
</form>
<script type="text/javascript">
$(document).ready(function () {
console.warn("test");
function loadFirst() {
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data: "id=1",
dataType: "html",
success: function (data) {
console.warn("test2")
console.warn(data);
}
});
}
console.warn("test3");
loadFirst();
});
$("#states").change(function () {
var ID = document.getElementById("states").valueOf().value;
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data: "id=" + ID,
success: function (r) {
document.getElementById("cities").innerHTML = r;
}
});
});
</script>
</body>
</html>
Test.php:
<?php
header('Content-Type: text/html');
require_once $_SERVER['DOCUMENT_ROOT'] . "/resources/scripts/php/conn/dal.php";
$stmt = $DB_con->prepare('SELECT id, name FROM `database`.pt_city WHERE state_id=:state');
$stmt->bindParam(':state', $_GET['ID']);
$stmt->execute();
if($stmt->rowCount() > 0 ) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$test = $test . '<option value="' . $row['id'] . '"id="optionTest">' . $row['name'] . '</option>';
}
}
return $test;
?>
Dev console:

Related

Jquery is not spotting that a form select has changed

I have a db table of all postcodes in the UK and want to create functionality to filter down into local locations to decrease load times of the page. The issue I am having is that I am a bit out of practice with JQuery and there seems to be an issue where selecting the country is not being picked up by the JQuery.
Here is the HTML/PHP for the select:
<label for="country_select">
Select Country
</label>
<select id="country_select" name="country_select" class="form-control search-select">
<option value=""> </option>
<?PHP
if ($result = mysqli_query($link, "SELECT DISTINCT(`country`) as countrylist FROM `postcodes`")) {
while($member = mysqli_fetch_assoc($result)) {
$country=$member['countrylist'];
?>
<option value="<?PHP echo $country; ?>"><?PHP echo $country; ?></option>
<?PHP
}
}
?>
</select>
Here is the PHP to check for the post and create a mysql statment to then create another drop down for cities. I am wondering if the issue lies here, i added an echo to see if it appears when the option has been changed, but nothing is appearing.
<?PHP
if (isset($_POST['CountryID'])) {
$country_query = $_POST['CountryID'];
$statement = " AND `country` = '".$country_query."' ";
echo $statement;
}
?>
And here is the jquery:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
if(data.success == true){
alert('success');
}
}
});
});
});
I am unsure where I am going wrong as it has been a while since I have coded. I have looked around at others' issues with no luck. Any help would be greatly appreciated.
The issue was the jquery. The code should be the following:
$(document).ready(function(){
$("#country_select").change(function () {
var country_name = $("#country_select").val();
jQuery.ajax({
type: "POST",
data: {CountryID: country_name},
success: function(data){
alert(data);
}
});
});
});`

How do I pass MySQL rows to a specific div in html using PHP?

Good day to everyone. So I am trying to get the value of a select option and getting a set of rows in MySql depending on the column name in the database. So here is the HTML code:
<html>
<body>
<select name = "FilterDoc" onchange = "filterby(this);">
<option disabled>Filter By</option>
<option value="document_type">Document Type</option>
<option value="date">Date</option>
<option value="hei">HEI</option>
<option value="other">Other Govt.</option>
<option value="person">Person</option>
</select>
<div class="panel-body" id="container">
</div>
Here is code for Ajax:
<script type="text/javascript">
function filterby(sel){
$.ajax({ //create an ajax request to display.php
type: "POST",
data: {FilterDoc: $(sel).val()},
url: "filterdocu.php",
dataType: "html", //expect html to be returned
success: function(response)
{
$("#responsecontainer").html(response);
}
console.log(reply);
});} </script>
Now the value of the select option will pass to the PHP file. I dont know if "if statement" is the right one for this since I haven't had that much background about getting values on html and such and I'm trying to find a better way to get the rows from MySql and display them into the container.
Here's the PHP code:
<?php echo"<div class='panel panel-primary' id='container'>";
if($_POST["FilterDoc"]=="document_type")
{
echo "<script type='text/javascript'>$('container').html('""');</script>";
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY document_type ASC");
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="date")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY date_received DESC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="hei")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY hei ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="Other")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY other_govt ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}
else if($_POST["FilterDoc"]=="Person")
{
$result=mysqli_query($conn,"SELECT * FROM records ORDER BY contact_person ASC");
echo "<script type='text/javascript'>$('container').html('""');</script>";
while($data = json_encode(mysql_fetch_assoc($result))
{
echo json_encode($data);
}
}echo"</div>"; ?>
I'm also not entirely sure if using javascript to clear the container is the proper way before putting contents into the div container.
I would really appreciate your help. Thank you!
At first i would simplify the code like :
<?php
echo "<div class='panel panel-primary' id='container'>";
// Set Variable
$filter = $_POST["FilterDoc"]; // This needs proper escaping
$result = mysqli_query($conn,"SELECT * FROM records ORDER BY $filter ASC");
while($data = json_encode(mysql_fetch_assoc($result)) {
echo json_encode($data);
}
echo "</div>";
Thats the PHP part, now i would rewrite the javascript.
function filterby(sel) {
$.ajax({ //create an ajax request to display.php
type: "POST",
data: {
FilterDoc: $(sel).val()
},
url: "filterdocu.php",
dataType: "html", //expect html to be returned
success: function(response) {
$("#container").empty().html(response);
}
});
}
But maybe your whole filtering process may be inefficient. You could fetch all the data with one SQL call and do the filtering with JS / data-attributes.

how to retrieve ajax data in "multiple" drop box?

I have 2 multiple select drop box.. form one I want to inflate the other multiple select drop box.. can anyone help me with this?
When I get result from the jQuery or ajax i want that result to display in 2nd number multiple select drop box...
this is my ajax..
function demo1() {
var emp_id = document.getElementById("employeeName").value;
alert(emp_id);
var datastring = "emp_id=" + emp_id;
//alert (emp_id);
$.ajax({
type: "POST",
url: "search_emp.php",
data: datastring,
dataType: "text",
//async: false,
success: function (data) {
//$("#clname").append(data);
$('#clname').html(data);
//document.getElementById("clname").innerHTML=data;
}
});
}
This are 2 multiple drop box..
<label>Select Employee </label>
<select multiple="multiple" class="w300" name="employeeName[]" id="employeeName" >
<?php $result = $conn->query("SELECT id,first_name,last_name,employee_id FROM employees");
while ($row = $result->fetch_assoc()){ ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['id']; ?><?php echo $row['first_name']; ?>
<?php echo $row['last_name'] ?></option>
<?php } ?>
<!--<?php echo $option;?>-->
<!--<?php echo $option2;?>-->
</select>
</br>
<label>Select Client</label>
<select multiple="multiple" class="w300" name="clname[]" id="clname">
<!--<?php echo $c;?>-->
</select>
.html() will set the innerHTML content of a DOM element, you can't do that on a <select>. There are two ways to solve it:
1) Quick & dirty: replace HTML
Make your search_emp.php also return the HTML code for the <select>, like this:
echo '<select multiple="multiple" class="w300" name="clname[]" id="clname">';
while($row = mysqli_fetch_assoc($ress)) {
echo '<option value="'.$row['gn_id'].'">'.$row['gamename'].'</option>';
}
echo '</select>';
Then you can use jQuery.replaceWith() to replace the whole DOM element:
$('#clname').replaceWith(data);
2) Much nicer: Build DOM from JSON
Instead of returning HTML code, your search_emp.php should return JSON, something like
[
{
"gn_id": "123",
"gamename": "superduper client"
},
{
"gn_id": "234",
"gamename": "another client"
}
]
You can easily do this by passing the client array to PHP's json_encode() and add a JSON content type header (Note that you will have to change the dataType attribute of $.ajax to "json" or you could use the shortcut function $.json():
// identify the content as JSON
header('Content-Type: application/json');
// put your MySQL query here.
// if errors occur, send a HTTP 500 header and return a useful error message as JSON
// collect results in an array
$rows = array();
while($row = mysqli_fetch_assoc($ress)) {
$rows[] = $row;
}
// return the results as a JSON list
echo json_encode($rows);
Before you make the AJAX call, you would want to remove all existing options from the select. In the success function of the AJAX call, you can loop through the results and append them to the select:
// reset the select options
$('#clname').empty();
// make the ajax call
$.ajax({
type: "POST",
url: "search_emp.php",
data: datastring,
dataType: "json",
success: function (data) {
// build the options from the JSON data
for (let client of data) {
$('#clname').append('<option value="' + client.gn_id + '">' + client.gamename + '</option>');
}
},
// optional, but good to have: error handling
error: function (data) {
alert("An error occurred:\n" + data.error)
}
});
jsfiddle
Note: let client of data only works in modern browsers (ES2015 compatible). If you want to support older browsers, do an old-fashioned for (len=data.length, i=0; i<len; ++i) loop. Or use jQuery.each() (although this might be slower)

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

dynamically updating select boxes with php mysql jquery ajax

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(""));
}
});
});
});

Categories