been scratching my head for hours on this one,
I have the below JQuery code that watches for a change in the select with the name of "CategoryID". It then posts the value of the "CategoryID" select to a PHP processor script which queries MySQL for the sub categorys and returns the updated options and populates the "SubCategoryID" select.
In the PHP processor script if I var_dump($_POST) at the top of the script I get an empty POST array. I've also tried dumping the $_REQUEST but still empty print_r() gives the same empty array
However the script runs fine and retrieves the correct data from the db and populates the web page.
I can even change the script and save the "CategoryID" to the DB and it populates it with the correct value...
As a relative nubee to JS for my own understanding how is this possible.
I have looked at some of the other questions posted but none of them give a solution
$(document).ready(function() { $('select[name="CategoryID"]').change(function() {
var selectedCategoryID = $('select[name="CategoryID"] option:selected').val();
var selectedSubCategoryID = $('select[name="SubCategoryID"] option:selected').val();
$.ajax({
method: "POST",
url: '/../_JQuery/PHPProcessorScript.php',
data: { CategoryID : selectedCategoryID, SubCategoryID : selectedSubCategoryID },
cache: false
}).done(function(data) {
$("select[name=SubCategoryID]").html(data);
})
})
})
PHP Processor script
var_dump($_POST); exit; // Returns an empty array with no ajax values
// If I remove exit the script returns the expected result so the ajax values are being parsed somehow...
$_POST['CategoryID'] = trim($_POST['CategoryID']);
$_POST['SubCategoryID'] = trim($_POST['SubCategoryID']);
if (empty($_POST['CategoryID'])) {
print '<option value="">select a category first</option>';
}
if (!empty($_POST['CategoryID'])) {
if (ctype_digit($_POST['CategoryID'])) {
if (strlen($_POST['CategoryID']) <= 11) {
$DBConnection = new database_connector();
$PS1SQL = 'SELECT
ID,
Description
FROM db_table
WHERE
CategoryID = :CategoryID';
$Statement = $DBConnection->Prepare($PS1SQL);
$Statement->bindParam(':CategoryID', $_POST['CategoryID'], PDO::PARAM_INT);
$Statement->Execute();
if ($PS1RS = $Statement->fetchAll(PDO::FETCH_ASSOC)) {
$PS1RS = array_merge(array(000 => array('ID' => 0, 'Description' => 'choose a sub category')), $PS1RS);
foreach ($PS1RS as $Key => $SubCategory) {
if ($_POST['CategoryID'] == $SubCategory['ID']) {
$SubCategoryList .= "<option value=\"$SubCategory[ID]\" selected=\"true\">$SubCategory[Description]</option>\n";
} else{
$SubCategoryList .= "<option value=\"$SubCategory[ID]\">$SubCategory[Description]</option>\n";
}
}
print $SubCategoryList;
} else {
print '<option value="" selected="true">Oops! no sub categorys available</option>';
}
}
}
I have some form data which I'm saving in JSON format using jQuery (this is all working fine).
But I then want to take the JSON data and display it in a PHP for loop. This is where I'm having trouble as jQuery's serializeArray and JSON.stringify just adds each form value in one bit chunk e.g.
check in, check out, room, adults, children, check in, check out, room, adults, children, check in, check out, room, adults, children
But I want to separate each room e.g.
(Room 1) check in, check out, room, adults, children
(Room 2) check in, check out, room, adults, children
(Room 3) check in, check out, room, adults, children
JSFiddle of how the form data is created (everything working fine): https://jsfiddle.net/kuohhm2q/
PHP I'm using to try a display JSON data in for loop (not working):
<?php
$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';
$data = json_decode($json_data, true);
//print_r($data);
foreach($data as $key => $val) { ?>
<?php echo $key; ?>
<?php } ?>
The issue is how you're building the JSON. Each item has it's own object due to the use of serializeArray() on the form, which means you have no idea what property is for what room.
To fix this use map() to build the array of objects per room. Like this:
function save_all_rooms() {
$(".save_all_rooms").on('click', function(e) {
var formData = $('.add_new_form .the_form').map(function() {
return {
check_in: $(this).find('[name="check_in"]').val(),
check_out: $(this).find('[name="check_out"]').val(),
room_type: $(this).find('[name="room_type"]').val(),
adults: $(this).find('[name="adults"]').val(),
children: $(this).find('[name="children"]').val()
}
}).get();
console.log(formData);
});
}
Updated fiddle
The result of this will be in the below format, where each object contains the properties of a room. This can then be easily iterated over:
[{
"check_in": "07/04/2017",
"check_out": "07/10/2017",
"room_type": "option_1",
"adults": "1",
"children": "1"
}, {
"check_in": "07/28/2017",
"check_out": "07/31/2017",
"room_type": "option_3",
"adults": "3",
"children": "3"
}]
I think this should work
<?php
$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';
$data = json_decode($json_data, true);
//print_r($data);
foreach($data as $key => $val) {
foreach($val as $val_key=>$val_val) {
echo $val_key.":".$val_val."</br>";
}
}
?>
you should use $data as $key and echo $key['name']
<?php
$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';
$data = json_decode($json_data, true);
// echo "<pre>";
// print_r($data);
$i=0;
foreach($data as $key) {
if($i==2) break;
echo 'Name: '.$key['name'];
echo "<br>";
echo 'Value: '.$key['value'];
echo "<br>";
$i++;
}
?>
Use json_decode to read the json value and you can use array_slice to keep the first two elements.Try this one:
<?php
$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';
$data = json_decode($json_data);
foreach(array_slice($data,0,2) as $key => $val) {
echo $val->name."-".$val->value."<br>";
} ?>
check the Output here
I have a leaderboard where if you click on a name a popup is displayed : https://jsfiddle.net/pvwvdgLn/1/
In practice, I will pull the list of the leaderboard from a DB.What you see here in the list are static names of employees,just for reference. So,how do I assign names using data attributes and search for that name in the JSON?
There are various fields in the popup like: Name,Email,Date of birth etc which I want to display for the respective person whose name is clicked by the user.
I have below JSON which is fetching me the array which contains all these data of all the people in the list :
<?php
session_start();
$servername = "xxxxx";
$connectioninfo = array(
'Database' => 'xxxxxxxxxxxxx'
);
$conn = sqlsrv_connect($servername, $connectioninfo);
if (!$conn) {
echo 'connection failure';
die(print_r(sqlsrv_errors() , TRUE));
}
$q1 = "select top 10 *
from pointsBadgeTable
WHERE WeekNumber ='week51'
order by pointsRewarded desc";
$stmt = sqlsrv_query($conn, $q1);
if ($stmt == false) {
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors() , TRUE));
}
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
}
while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first
//Set content type to json
header('Content-Type: application/json');
//Echo a json object to the browser
echo json_encode($result);
?>
As can be seen in the query,it fetches JSON for all the top10 ,whose names can be seen in the list.
the html and JS related to the popup is here : https://jsfiddle.net/woef5mn6/
How can I display the respective data in the popup from the JSON only for the person whose name is clicked ?
please help me.
I have edited your fiddle to show how your problem can be solved. This is just a simple solution. It needs to modified according to your requirement.
Here is the fiddle
I am creating the employee list from your JSON and populating the ordered list
function employeeList() {
$("#myOL").empty();
$.each(employee, function(i,o) {
$("#myOL").append("<li><mark>" + o.EmployeeName + "</mark><small>" + o.score + "</small></li>");
});
}
Then onclick of the individual employee, i am getting his details from JSON by his name and then populating the popup details (as a best practice here - you should get the employee details by calling a service through ajax using a unique identifier [employeeId] ):
function getEmployeeByName(name) {
var index = -1;
var filteredObj = employee.find(function(item, i) {
if(item.EmployeeName === name){
index = i;
}
});
return employee[index];
}
Hope this helps!
Is it possible to update the server-side JSON file using AJAX in bootstrap-table?
data-url="scripts/users.php"
I am using a PHP file to echo the output of the sql queries to the table.
First Name | Last Name | Category | Group
This works well, but I want to add 4 select tags each to filter a column. I have replicated the server-side JSON within users.php but this time it will echo the filtered rows to the JSON.
Can this be done? How can I switch to the filtered JSON?
NOTE: all this logic is within users.php (aside from the AJAX of course).
if (!empty($_POST['first_name'])) {
//code to create and return filtered JSON
} else if (!empty($_POST['last_name'])) {
//code to create and return filtered JSON
} else if (!empty($_POST['category'])) {
//code to create and return filtered JSON
} else if (!empty($_POST['group'])) {
//code to create and return filtered JSON
} else {
//code to create and return unfiltered JSON
/*THIS ALWAYS EXECUTES ONLOAD, BUT **I WANT IT TO GIVE WAY FOR THE FILTERED JSON AND ONLY REACTIVATE ONLOAD OR IF ALL FILTERS ARE REMOVED***/
}
UPDATE:
In my users.php code I have successfully been able to run each filtered query individually (depending on what is selected). When the page first loads the table is empty but present. Users must select at least one option for the table to output any data.
I am having issues letting the table (written in the .html page) know to switch to the filtered results while the filter is active.
Here is the code that resides in each of the if/else conditions:
$limit = $_GET['limit'];
$offset = $_GET['offset'];
fname = $_POST['first_name'];
if (!empty($_POST['first_name'])) { //filter by the selected name
//get TOTAL rows for PAGINATION
$stmt_TOTAL_ROWS = "SELECT first_name, last_name, category, group
. "\
n "
. "
FROM users
.
"\n"
.
"WHERE first_name ='$fname'";
$result_TOTAL_ROWS = mysqli_query($mysqli, $stmt_TOTAL_ROWS);
$num_rows_TOTAL_ROWS = mysqli_num_rows($result_TOTAL_ROWS);
$stmt = "SELECT first_name, last_name, category, group
. "\
n "
. "
FROM users
.
"\n"
.
"WHERE first_name ='$fname' ORDER BY first_name LIMIT $offset, $limit";
$result = mysqli_query($mysqli, $stmt);
$cart = array();
$i = 0; //index the entries
if ($num_rows_TOTAL_ROWS > 0) { //if table is populated...
// enter data of each row
while ($row = mysqli_fetch_assoc($result)) {
$cart[$i] = array(
"First Name" => htmlspecialchars($row['first_name']),
"Last Name" => htmlspecialchars($row['last_name']),
"Category" => htmlspecialchars($row['category']),
"Group" => htmlspecialchars($row['group']),
);
$i = $i + 1; //add next row
}
//encoding the PHP array
$json_server_pagination_data = array(
"total" => intval($num_rows_TOTAL_ROWS), // total rows in data
"rows" => $cart, //data
);
echo json_encode($json_server_pagination_data); // allow table to access the data
} else {
//do nothing . no data in sql query
}
}
I'm in the process of establishing a website which uses JQuery's auto complete to give users suggestions on pages. I store the page ID and title in a SQL database (connecting using PDO). At the moment, I've got the auto complete feature working, however, I am absolutely stumped on how to get the auto complete list to turn into clickable links which direct the user to the relevant page based off the page ID in the database.
Here's my search.php file
<?php
require('includes/connect.class.php');
if (isset($_GET['term'])) {
$return_arr = array();
try {
$stmt = $conn->prepare('SELECT id, locationName FROM locations WHERE locationsName LIKE :term');
$stmt->execute(array(
'term' => '%' . $_GET['term'] . '%'
));
while ($row = $stmt->fetch()) {
$return_arr[] = $row['locationName'];
}
}
catch (PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($return_arr);
}
?>
and my JavaScript
$(function() {
$(".locationlist").autocomplete({
source: "search.php",
minLength: 1
});
});
The database looks like this
Locations
|---ID---||---locationName---|
| 1 || Test1 |
| 2 || Test2 |
----------------------------
I've done some research, and I believe I need to modify JQuery to display an array of objects. I'm not too sure how to do this.
What would be the best way to have my auto complete list get the page ID from the SQL database and become clickable links?
You don't actually need for clickable links there. You can redirect the page within the autocomplete's select event , where you have access to the selected item object:
ui (Type: Object):
item (Type: Object):
An Object with label and value properties for the selected option.
ui.item.value will be the page ID generated with your PHP
$(".locationlist").autocomplete({
source : "search.php",
minLength: 1,
select : function(event, ui){
// You may need to change this part, as I don't know the exact values:
location.href = "http://your-site.com/" + ui.item.value;
}
});
As for your PHP, you can modify the output array like so:
while ($row = $stmt->fetch()) {
$return_arr[] = array(
'value' => $row['ID'],
'label' => $row['locationName']
);
}