I have a list of files and a drop down box, I'd like the user to be able to filter them by various categories etc.
I have a php class that has the function for creating the sql query and returning the result. I'd very much like to do this via ajax to prevent a refresh.
I'm stuck and was hoping for some help.
The problem is that I don't know what to do next. This is pretty new to me but still plenty foreign. If the ajax call can be run onKeyUp from the select then even better.
Thank you for any help:
the HTML:
<div>
<form action="" method="post" name="orderBy">
<label for="orderBy" id="orderBy">Order By:</label>
<select>
<option class="orderByOption" value="newest">Newest First</option>
<option class="orderByOption" value="oldest">Oldest First</option>
<option class="orderByOption" value="cat">Category</option>
<option class="orderByOption" value="alpha">Aphabetical</option>
<option class="orderByOption" value="fileType">Filetype</option>
</select>
<label> </label>
<input type="submit" class="orderByTrainingButton" name="submit" value="Go!"/>
</form>
</div>
The Ajax:
//form for changing the ordering of items in training all docs
$(function(){
$(".orderByTrainingButton").click(function(){
//validate and process
//get vlaue
var option = $(".orderByOption").val();
var params = {option: option};
$.ajax({
type: "POST",
url: "../trainingOrderByAjax.php",
data: params,
dataType: 'json',
success: function(data){
if(data.success == true){
//aaaannnd. stuck/
}else{
// shouldn't ge there...I hope.
}
},
error: function( error ) {
console.log(error);
}
});
});
});
The php the ajax will call:
<?php
include_once('core/init.php');
if($_POST){
$orderBy = $_POST['orderByOption'];
if($training->getAlFilesOrderBy($orderBy)){
$data['success'] = true;
}else{
$data['success'] = false;
}
echo json_encode($data);
}
To start with ordering by desc or asc would be great. I can then build on that.
Something like this.
PHP:
if($results = $training->getAlFilesOrderBy($orderBy)){
$data['success'] = true;
$data['results'] = $results;
}else{
$data['success'] = false;
}
echo json_encode($data);
}
JS:
if(data.success){
var results = data.results;
for (var i = 0; i < results.length; i++) {
// do something with results[i]
}
}else{
// shouldn't ge there...I hope.
}
Change your AJAX error handler to:
error: function(xhr, status, errorMsg) {
console.log("AJAX error: " + errorMsg);
}
Related
I have a <select> with only one option, i want to get the rest of the options from a database using PHP and then populate said <select> with the PHP result using AJAX.
Unfortunately my code is not working, im not surprised as im new to both AJAX and jQuery but i dont get any errors to guide myself through the issue.
The PHP works as expected because its used in another part of the site and i have no issues with it so my error must be in the AJAX (no big surprise here).
Below my HTML:
<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>
Below my AJAX code:
<script type="text/javascript">
$(document).ready(function() {
$("#producto").click(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
$("#producto").append(data);
}
});
});
});
</script>
Below my PHP code:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
As always any kind of help is greatly appreacited and thanks for your time.
IMPORTANT EDIT
<select> has a duplicated id, perhaps i should i have stated this from the start as i know think thats whats causing my issue.
The fact is that in this <form> the selects are created dynamically on user request. They click on Add product and a new select with the products avaiable is created, i know the id/name of said input must have [ ] (id="producto[]") for it to be converted into an array but i dont know how to make the AJAX deal with this dynamically created reapeated selects issue. I apologise for this belated aclaration i realise now it is of the utmost importance.
You have to edit your response from this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
To this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
$response = '';
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
$response .= '<option value="' .$titulo . '">' . $titulo . '</option>'; //Concatenate your response
}
echo $response;
?>
But i suggest to use JSON to get a response and parse it on client side.
You can do this by pushing all values in to response array and use json_encode(). At the end you get straight response from the server with just a values, and append thous values whatever you need on client side.
Update
Also you append data to your existing select options. You can just add thous by editing this:
<script type="text/javascript">
$(document).ready(function() {
$("select#producto").focus(function() { //Change to on Focus event
$.ajax({
url: 'fetch_lista_productos_compra.php',
success: function(data) {
$("select#producto").html(data); //Change all html inside the select tag
}
});
});
});
</script>
Test result:
$('select#options').focus(function(){
alert("Hello this is a select trigger");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="options">
<option value="test">Test</option>
</select>
Please don't construct your html on the server, try to just send the raw data and then construct the html client-side, it's better that way and it leaves room for changing the view later without much coupling.
That said, instead of doing:
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
just do
$rows = [];
while ($row = mysqli_fetch_assoc($sql_query)) {
$rows[] = $row;
}
//this is your best bet when sending data from PHP to JS,
//it sends the rows as JSON-like string,
//which you'll parse to an array in the client
echo json_encode($rows);
then in the client
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: (data /*json-like string*/) => {
const dataAsArray = JSON.parse(data);
$.each(dataAsArray, (index, row) => {
//now HERE you construct your html structure, which is so much easier using jQuery
let option = $('<option>');
option.val(row.titulo).text(row.titulo);
$("#producto").append(option);
});
}
});
Regarding your edit about several selects
I don't have access to your server of course so I'm using a mock service that returns JSON. IDs are dynamically generated and all data loading occurs asynchronously after you click on the button.
Try using your url and modify the success function according to your html.
$(document).ready(function() {
$('#add').click(() => {
//how many so far...?
let selectCount = $('select.producto').length;
const select = $('<select class="producto">');
select.attr('id', `producto${selectCount + 1}`);
//then we fetch from the server and populate select
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'get',
success: function(data) {
data.forEach((d) => {
const option = $('<option>');
option.val(d.id).text(d.title);
select.append(option);
});
}
});
document.body.appendChild(select[0]);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='add'>Add product</button><br>
<!--<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>-->
HIH
As it turns out the code in the question was actually working properly, the problem was not the code itself but the fact that, as i stated (sadly on a later edit and not right from the start) in the question, there where more than one <select> using the same id, therefore everytime the AJAX was executed the result was appended to the first <select> only, and it was appended over and over again everytime i clicked it, my solution was unifiying both the AJAX that populated the <select> and the jQuery that created the said dynamic <select>'s all in one script thus solving all of my issues at once.
Below my jQuery/AJAX code:
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 0;
$(add_button).click(function(e) {
e.preventDefault();
$.ajax({
url: '/testground/php/fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
if(x < max_fields) {
x++;
var html = '';
html += '<div class="form-group row" id="inputFormRow" style="margin-bottom: 0px;">';
html += '<label class="col-3 col-form-label font-weight-bold">Producto</label>';
html += '<div class="col-7">';
html += '<select class="custom-select my-1 mr-sm-2" id="producto" name="producto[]" required>';
html += '<option disabled selected value>Elegir...</option>';
html += data;
html += '</select>';
html += '</div>';
html += '<div class="col-1 my-auto" style="padding: 0px 0px 0px 0px;">';
html += '<button id="removeRow" type="button" class="btn btn-danger">X</button>';
html += '</div>';
html += '</div>';
$(wrapper).append(html);
}
}
});
});
$(document).on('click', '#removeRow', function () {
$(this).closest('#inputFormRow').remove(); x--;
});
});
</script>
I want to thank everyone that took the time to help me out with this Swati, Serghei Leonenco and Scaramouche, this community is truly amazing.
<script type="text/javascript">
$(document).ready(function() {
$("#producto").change(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
console.log(data)
// $("#producto").append(data);
}
});
});
});
</script>`enter code here`
try run this and check in your console that weather you are receiving the data from your php or not.
Unable to get value from database in codeigniter. I tried to fetch data based on select box value(menu_code) without refreshing page using ajax but I got result undefined.
This my controller's code : login.php
public function get_menu_rights()
{
if (isset($_POST['name']))
{
$root_id = $this->input->post('menu_root_id');
$data['res'] = $this->login_model->get_menu_check($root_id);
// print_r($data['res']);
echo json_encode($data);
//$this->load->view('pages/role_rights',$data);
}
}
Below is my model code login_model.php
public function get_menu_check($root_id)
{
$this->db->select('menu_code,menu_name');
$this->db->from('create_menu as C1');
$this->db->where('C1.menu_root_id',$root_id);
$this->db->order_by('menu_code');
return $this->db->get()->result_array();
}
This is my view code role_rights.php
<form action="<?php echo base_url('login/get_menu_rights');?>" method="post">
<?php
print"<select class=\"form-control\" name=\"menu_root_id\" onchange=\"javascript:__doPostBack();\" id=\"menu_root_id\">"; ?> <option value="select">select</option>
<?php foreach($result as $res) { ?>
<option value="<?php echo $res->menu_code; ?>">
<?php echo $res->menu_name.'-'.$res->menu_code; ?>
</option>
<?php } ?>
</select>
</form>
</div>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
function __doPostBack()
{
var name = document.getElementById('menu_root_id').value;
var dataString='name='+ name;
$.ajax({
type:"post",
url:"<?php echo base_url('login/get_menu_rights'); ?>",
data:dataString,
cache:false,
dataType: 'json',
success: function(data)
{
var id = data[0];
var vname = data[1];
$('#output').html("<b>menu_code: </b>"+id+"<b> menu_name: </b>"+vname);
}
});
return false;
}
</script>
</div>
<div id="output"></div>
Hope this will help you :
Replace
$root_id = $this->input->post('menu_root_id');
with
$root_id = $this->input->post('name');
Your controller's get_menu_rights method should be like this :
public function get_menu_rights()
{
$root_id = $this->input->post('name');
if(! empty($root_id))
{
$data = $this->login_model->get_menu_check($root_id);
// print_r($data);
echo json_encode($data);
exit;
}
}
Your ajax success function should be like this :
success: function(data)
{
var html = '';
$.each(data,function(k,v){
alert(v);
html += "<b>menu_code: </b>"+v.menu_code+"<b> menu_name: </b>"+v.menu_name
});
$('#output').html(html);
}
There are a few things I noticed
$data is an undefined array & you are settings the result array returned by the model function to it's 'res' key
dataString is not a json neither it's a js array that you are sending
since you used json_encode, you need to use JSON.parse(data) in the ajax success
if you do have the result in $data['res'], then you need to do something like this - data=JSON.parse(data)['res']; now you can get id from data[0]
I think the query return empty please try this Code.....
public function get_menu_check($root_id)
{
$data = $this->db->select('C1.menu_code,C1.menu_name')
->from('create_menu as C1')
->where('C1.menu_root_id',$root_id)
->order_by('C1.menu_code')
->get();
if($data->num_rows() >= 0)
return $data->result_array();
else
return false;
}
I am new to JQUERY and I am trying to search for the something and based on the searched text I am doing an ajax call which will call php function and the PHP is returning me with JSON data.
I want to display the returned data in the Datatable form.
I have my PHP file table.php and JavaScript file jss.js and my main.php.
The PHP file is returning the JSON data and I able to use alert to display it.
I want to know how can I display it in datatable.
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off"/>
<button id="search" name="submit">Search</button>
</div>
my ajax/jss.js file
$(document).ready(function(){
$('#search').click(function(){
var search_query = $('#search_query').val();
if(search_query !='')
{
$.ajax({
url:"table.php",
method:"POST",
data:{search_query:search_query},
success: function(data)
{
alert("HEKKI "+data);
}
});
}
else
{
alert("Please Search again");
}
});
});
my table.php file
<?php
$data=array();
$dbc = mysqli_connect('localhost','root','','acdc') OR die('Could not connect because: '.mysqli_connect_error());
if (isset($_REQUEST['search_query']))
{
$name = $_REQUEST['search_query'];
}
if($dbc)
{
if (!empty($name))
{
$sql = "select c.res1 res1,
cc.res2 res2,
cc.res3 res3,
cc.res4 res4,
cc.res5 res5
from table1 c
inner join table2 cc
on c.id = cc.id
where c.name like '".$name."%'
and cc.ENABLED = 1";
$res = mysqli_query($dbc,$sql);
if(!(mysqli_num_rows($res)==0))
{
while($row=mysqli_fetch_array($res))
{
$data['RES1'] = $row['res1'];
$data['RES2'] = $row['res2'];
$data['RES3'] = $row['res3'];
$data['RES4'] = $row['res4'];
$data['RES5'] = $row['res5'];
}
}
else
{
echo "<div style='display: block; color:red; text-align:center'><br/> Not Found,Please try again!!!</div>";
}
}
}
echo json_encode($data);
/*
*/
?>
Can you please guide me how to display the result in main page.
Setting utf8 as charset is probably a good idea. If you have different charset in your table you will get a JSON error :
mysqli_set_charset($dbc, 'utf8');
Then use mysqli_fetch_assoc instead of mysqli_fetch_array. You want field: value records turned into JSON :
$data = array();
while($row=mysqli_fetch_assoc($res)) {
$data[] = $row;
}
Output the JSON :
echo json_encode( array('data' => $data) );
Now you can use it directly along with dataTables :
<table id="example"></table>
$('#example').DataTable({
ajax: {
url: 'table.php'
},
columns: [
{ data: 'res1', title: 'res1'},
{ data: 'res2', title: 'res2'},
//etc..
]
})
one approach is to create the form fulfiled with data just in table.php file and with support of jQuery you will need to populate the <form id="form_id"> with ajax result $('#form_id').html(ajax_response);
other aproach:
to use jQuery json data to populate every field separately.
var jsonData = JSON.parse( ajax_response ); // decode json
than
$('#id_input_1').val(jsonData.RES1);
$('#id_input_2').val(jsonData.RES2);
$('#id_input_3').val(jsonData.RES3);
Place a placeholder in this case I used #results, and dynamically create a table and append it to the placeholder. I commented out your ajax for this example, but just call the function I created to process the results from within the success callback and pass the new function a javascript object.
$(document).ready(function() {
$('#search').click(function() {
var search_query = $('#search_query').val();
if (search_query != '') {
//$.ajax({
// url: "table.php",
// method: "POST",
// data: {
// search_query: search_query
// },
// success: function(data) {
// alert("HEKKI " + data);
// }
//});
processResults({RES1: "result1", RES2: "result2"});
} else {
alert("Please Search again");
}
});
});
function processResults(obj){
var $tbl = $("<table>");
var $row = $("<tr>");
var trow;
$.each(obj, function(idx, elem){
trow = $row.clone();
trow.append($("<td>" + obj[idx] + "</td>"));
$tbl.append(trow);
});
$("#results").append($tbl);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off" />
<button id="search" name="submit">Search</button>
<div id='results'></div>
</div>
I have this code, where when I click on a value in my first drop list, I need to get new data from MySQL into my second drop list according to my selection.
I have this code here:
$('#sale_type').change(function() {
// get the form information
// this can be done in many ways but we are going to put the form
// data into a data object
var formData = {
'selectedValue' : $('#sale_type').val()
};
// send the data via Ajax
$.ajax({
type : 'POST', // the method we want to use to send the data
url : 'getTypeDetails.php', // the url where we want to
// send the data
data : formData, // the data object we created
dataType : 'json', // what type of data we want to get back
encode : true
})
// execute function when data has been sent and server
// code is processed
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
});
});
And here is getTypeDetails.php:
<?php
require_once('../include/global.php');
$data = $_POST['selectedValue'];
// Connect to database
// Use the data to get the new information
$query = "SELECT * FROM purchases WHERE sale_type = :data";
// MySQL
$results = $conn->prepare($query);
$results->bindValue(":data", $data);
$exec = $results->execute();
$res = $results->fetchAll();
$data = array();
$i = 0;
foreach($res as $row){
$data[i] = $row['sale_details'];
$i++;
}
echo json_encode($data);
?>
the problem is that I can't get the $data[i] into my new drop list with an id=sale_details
So I don't know what to put here:
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
EDIT
Those are my HTML drop lists:
<label for="sale_type" class="col-lg-1 control-label" style="float:right">النوع</label>
<select id="sale_type" name="sale_type" class="dropdown-header" style="float:right">
<option value="undefined">اختر</option>
<?php
foreach($fetchType as $ft){ ?>
<option value="<?php echo $ft['sale_type'] ?>"><?php echo $ft['sale_type'] ?></option>
<?php } ?>
</select>
<label for="sale_details" class="col-lg-1 control-label" style="float:right">الصنف</label>
<select id="sale_details" name="sale_details" class="dropdown-header" style="float:right">
</select>
It should be something like this:
.done(function(data) {
var secondDropdown = $("#second-dropdown");
secondDropdown.empty();
$.each(data, function(index, value) {
secondDropdown.append("<option>" + value + "</option>");
});
return;
}
Replace your js code with my code
<script>
$(document).ready(function() {
$('#sale_type').change(function() {
var formData = { 'selectedValue' : $( "#sale_type option:selected" ).val() };
console.log(formData);
$.ajax({
type: 'POST',
url: 'getTypeDetails.php',
data: formData,
success: function(data){
var obj = jQuery.parseJSON(data);
var secondDropdown = $("#sale_details");
secondDropdown.html('');
for (var prop in obj) {
secondDropdown.append("<option>" + obj[prop] + "</option>");
}
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
});
});
</script>
and add jquery link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
in your <head> tag
I'm tring to send and receive parameters with AJAX without any sucess
First I choose AREA and than the CITIES in this area.
Can you please tell me what do I do wrong?
Client side:
<script>
$(document).ready(function(){
$("#first").click(
function(){
var area_id=$("#area_id").val();
$.ajax({
type: "POST",
url: "recs.php",
data: "area_id="+area_id,
cache:false,
success:
function(data){
$("#second").html(data.message);
}
});
return false;
});
});
</script>
<form method="post" action="tosomewhere.php">
<select id="first" name="area_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="second" name="section"> </select>
</form>
Server Side:
$areaID = $_POST['area_id'];
$second_option = "";
$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = $areaID ORDER BY id ASC");
while($index = mysql_fetch_array($query2))
{
$id = $index['id'];
$name = $index['name'];
$second_option .= "<option value='$id'>$name</option>";
}
echo $second_option;
exit;
Thank you in advanced
After editing:
I changed the code to something even simpler:
Client side:
<script>
$(document).ready(function(){
$("#first").click(
function(){
var area_id=$("#area_id").val();
$.ajax({
type: "GET",
url: "recs.php",
data: "area_id="+area_id,
cache:false,
success:
function(data){
$("#second").html(data);
}
});
return false;
});
});
</script>
<form method="post" action="tosomewhere.php">
<select id="first" name="area_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="second"></div>
</form>
Server side:
some text
I'm still not getting the string into
change
$("#second").html(data.message);
to
$("#second").html(data);
<script>
$(document).ready(function(){
$("#first").click(function(){
var area_id=$("#area_id").val();
$("#second").load('tosomewhere.php?area_id=' + area_id);
return false;
});
});
</script>
Changed the jquery a bit. Using GET.
Also the script has changed:
$areaID = (int) $_GET['area_id'];
$second_option = "";
$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = '$areaID' ORDER BY id ASC");
if (mysql_num_rows($query2) > 0){
while($index = mysql_fetch_array($query2)){
$second_option .= '<option value="'.$index['id'].'">'.$index['name'].'</option>';
}
echo $second_option;
} else {
echo 'No result!';
}
die();
Added (int) before $_GET as a pre-security measurement.
Add this parameter to the ajax function
dataType:'text'
You need to debug code where is actually fault whether you ajax call is actually initialize.
i: check whether value properly fetch in "area_id" js variable
alert(area_id);
ii: if it ok check whether data proper returned from server scriptinog
alert(data); or alert(data.message);
iii: for testing whether you receive data properly, just send out test script.
echo "sample text";
exit;
or try to send data in json format
die('{"message" : "sample text"}');
If all three steps working, then there should be fault in data access script.
If you are not getting output in ajax try using firebug to check what is actually happening in sending request and getting response.