Formatting JSON data and displaying in a PHP for loop - javascript

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

Related

JQuery GET request won't get correct data from php echo

I am trying to fill a table using a jquery .get request, the url being a php file. The php gets data from a database, then it should return a json array back to the jquery, array which will fill the table. While the length of the array is returned as it should, the table cells are empty.
Here is my get.php function:
<?php
$mysqli=new mysqli("localhost:3306","root","","leagues");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$return_arr = array();
$query = "SELECT * FROM league";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row())
{
$return_arr[] = $row;
}
}
$mysqli->close();
header('Content-Type: application/json');
echo json_encode($return_arr);
?>
And here is my jquery get function
$.get('php/get.php',function(responseJson)
{
if(responseJson!=null)
{
$("#tableleague").find("tr:gt(0)").remove();
var table1 = $("#tableleague");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['teams']);
rowNew.children().eq(1).text(value['playedgames']);
rowNew.children().eq(2).text(value['wongames']);
rowNew.children().eq(3).text(value['tiegames']);
rowNew.children().eq(4).text(value['lostgames']);
rowNew.children().eq(5).text(value['scoredgoal']);
rowNew.children().eq(6).text(value['receivedgoal']);
rowNew.children().eq(7).text(value['points']);
rowNew.appendTo(table1);
});
}
});
Here is how my webpage looks, with the php file response shown.
Since the response is ok, what am I doing wrong that the cells aren't filled? Thank you.
If you look at your JSON data, you can see that there are no keys such as teams or playedgames. This is because you used fetch_row() in the PHP. Change that to fetch_assoc():
while ($row = $result->fetch_assoc())
This will give you $row with the field names as keys instead of using numerical keys that fetch_row() provides.
You can turn the php json into javascript object
obj = JSON.parse(json);
es:
var json='{"ex1":"test","ex2":[{"sub1":"test"},{"sub2":""s2test}],"ex3":true}';
var obj = JSON.parse(json);
after you can acces to data with :
obj.ex1 // test
obj.ex2[0].sub2 //s2test

Autocomplete json_encode return by column

I'm using the autocomplete UI for my search box. Below is my php code:
<?php
include 'connect.php';
if (isset($_GET['term'])) {
$value = $_GET['term'] . '%';
$return_arr = array();
$stmt = $conn->prepare("SELECT * FROM jobs WHERE jobname LIKE ? or formtype LIKE ?");
$stmt->bind_param("ss", $value, $value);
$stmt->execute();
$stmt->bind_result($entryid, $jobnumber, $jobname, $formtype, $date);
while ($stmt->fetch()) {
$return_arr[] = $jobname;
$return_arr[] = $formtype;
}
echo json_encode($return_arr);
}
?>
Everything works perfectly fine. But I kind of want for the while statement to return all $jobname values first before the $formtype values. In short, I want the values to be returned by column and not by row. I'm not sure how it is possible because I tried putting them inside do while and foreach statements but both didn't work for me.
Also for some reason, when I create another echo statement, the:
echo json_encode($return_arr);
stops working.
. But I kind of want for the while statement to return all $jobname values first before the $formtype values.
Build two arrays and then merge them:
$ar1 = [];
$ar2 = [];
while($stmt->fetch()) {
$arr1[] = $jobname;
$arr2[] = $formtype;
}
$return_arr = array_merge($arr1, $arr2);
Also for some reason, when I create another echo statement, the:
echo json_encode($return_arr);
stops working.
Because autocomplete expects json object and you want to try give him json object and something else

php/mysql write array to json file

I have the following issue, my php code gets the required data from the dB:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
As you see this writes to a json file - results:
{"0":{"nmech":"2.00","nelect":"2.00","nplant":"2.00","ncivil":"2.00"}}
When I use the following js code to extract from json file:
$.getJSON('newport.json', function(data) {
console.log(data);
The console log using chrome displays the following:
[Object]
0: Object
nmech: "3.00"
__proto__: Object
length: 1
only shows the first key/value pair and not all 4 K/V pair? Can someone explain what I am doing wrong please.
Writing the results to a json file is overkill, IMHO. Why not just add the json into a Template or Page view (PHP).
<script>
// Create settings from PHP/Session and
// Initialize Registration Namespace
var registrationSettings = <?php echo (!empty($data)) ? #json_encode($data) : json_encode(array()); ?>;
Registration.init({ settings: window.registrationSettings });
</script>
Obviously, you don't have a Registration namespace object, but this just an example approach to setting settings from PHP when the page first loads.
All you really need it to output some data.
<script>
var newport = <?php echo (!empty($emparray)) ? #json_encode($emparray) : json_encode(array()); ?>;
</script>
Or maybe a more simple way to write it would be.
<script>
var newport = <?php echo (!empty($emparray)) ? #json_encode($emparray) : '[]'; ?>;
</script>
I can see your trying to file (or cache) the results. You should probably just write an AJAX method in your PHP controller to handle the request. The data could be cached server side in Memcached or some other fast handler of data. Most PHP frameworks support memcached.
This is ok, because your PHP array looks like this:
<?php
$arr = [
[
"key1" => "value1",
"key2" => "value2",
]
]
You must use data[0]['key'] to access key1 part of first element.
Another (better solution) is to not to use while loop in php, since you are expecting 1 element in your case to be returned from mysql. Use like this then:
<?php
require('dB_connect.php');
$reportID = intval($_GET['q']);
$sql = "SELECT nmech, nelect, nplant, ncivil FROM `flashreport` WHERE ID = '".$reportID."'";
$result = mysqli_query($dbc, $sql);
//Get first row from db.
$emparray = mysqli_fetch_assoc($result);
file_put_contents("newport.json", json_encode($emparray,JSON_FORCE_OBJECT));
mysqli_close($dbc);
?>
Now your data will be in javascript like you expected on beginning.

Passing Select Value through Javascript/Jquery/AJAX to php varibale

I have a code, where when i select a value through Drop-down, the name I am selecting should pass through a PHP variable $ch so a second drop-down which runs a mysql query.
Here is my code for first dropdown:
<select name="cha_name" id="cha_name" onChange="fillcha(this.value);">
<option value="0">--SELECT--</option>
<?php
$res = mysqli_query($con, "select customer_code, customer from master_customer where is_cha = 1 order by customer") or die(mysqli_error($con));
while($row = mysqli_fetch_array($res)){
echo "<option value=\"".$row[1]."$$".$row[0]."\" ".(($row[1]==$wo_order[1])?"selected='selected'":"").">".$row[1]."</option>";
}
?>
</select>
When i select this, the value should be capture in a PHP variable $ch without reloading the page show the PHP variable can be used further in a mysql query. Kindly help as I am still in learning phase for JQuery and Ajax.
the mysql query is as follows:
SELECT container_no FROM `cex_work_order_det` WHERE `cha_name`='$cha'
for that you have to use jquery and ajax
jquery code
<script>
$("document").ready(function()
{
$("select[name='cha_name']").change(function() // function sorting Domain according to server name
{
var customer_code=$("select[name='cha_name']").val();
$.get('ajax_actions.php?act=your-act-name&customer_code='+customer_code,function(data)
{
alert(data);
});
});
});
</script>
ajax_actions.php
<?php
error_reporting(0);
foreach ($_GET as $name => $value) { $$name = $value; }
foreach ($_POST as $name => $value) { $$name = $value; }
// warning Dont chnage anything in This ajax action file
// -------------------------------------------------------------------------------
if($act=="your-act-name") // do your actions
{
// fire here your query and echo you result here
}

how to get the value of array sent from AJAX POST in php?

i am having a probelem with ajax multiple delete. I've sucessfully set the values of the checkbox slected in a variable.
the problem i have to solve is how to get the value of the sent array in php.
here is the ajax post code
<script>
$("#delete-btn").click(function(e){
e.preventDefault();
var id = new Array();
$(".check:checked").each(function() {
id.push($(this).attr('value'));
});
$.post("../ajax/multiDelete.php",{id:id},function(data){
alert(data);
});
});
</script>
now, the php page
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
echo $value;
}
}
?>
when the data is alerted, i only get "array";
i do not know about JSON, so if there is anything i can do without it then your help is most appreciated! thanks : D
Since id is an array and in your code you are wrapping it inside an array again. Instead of that,do this :
<?php
if(isset($_POST['id'])){
// Don't use array($_POST['id']) as id is already an array
$id = $_POST['id'];
foreach($id as $value){
echo $value;
// Here you'll get the array values
}
}
?>
If you want retun array from php - user json_encode()
echo json_encode(array($_POST['id']));
P.S. JS function alert() can`t print arrays or object. Use console.log(data) and you will see result in developer console of your browser.
This is not related to your question, but I just wanted to show you a better way of getting the id values, without creating a new array variable and then pushing items into the array, by using the jQuery .map() method:-
$("#delete-btn").click(function (e) {
e.preventDefault();
// Get all the values in the array 'id' variable
var id = $(".check:checked").map(function () {
return this.value || 0;
}).get();
$.post("../ajax/multiDelete.php", { id: id }, function (data) {
alert(data);
});
});
Hope this helps!
Don't pass array variable in AJAX. Convert id array to JSON using JSON.stringify(id).
In PHP backend,use
<?php $val = json_decode($_REQUEST['id']);
foreach($val as $ids){
echo $ids;
}
use $val array to proceed further in php.
You have to access your checked value by-
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
foreach($value as $value1){
echo $value1;
}
}
}
?>
Because this is an array inside array.

Categories

Resources