communication between PHP and JS when a row is added in JS - javascript

I have a php code as shown below:
Php code:
<?php
$output['house_sitting_date_yes_no']=$_POST['house_sitting_date_yes_no'];
if(file_exists('../feeds/ptp-ess_landing_house.json')){
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_house.json'));
}
?>
<?php if($data) { ?>
<form>
<!-- Sitting Days START -->
<div class="sitting-days" style="display:flex; justify-content:center; margin-bottom:20px;">
<!-- Yes/No START -->
<div class="yes-no">
<h4 style="text-align:center;">Yes/No</h4>
<select name="house_sitting_date_yes_no" id="house-yes-no" style="height:24px;">
<option value="nada" <?php if($data->{"house_sitting_date_yes_no"}=="nada"){echo 'selected';}?>>Please choose an option</option>
<option value="yes" <?php if($data->{"house_sitting_date_yes_no"}=="yes"){echo 'selected';} ?>>Yes</option>
</select>
</div>
<!-- Yes/No END -->
</div>
<!-- Sitting Days END -->
</form>
<? } else {
echo 'Cannot read JSON settings file';
}
?>
The above php code corresponds to the following fiddle. In the fiddle, its adding a new row on click of a button in Javascript.
I haven't included JS code in the above php code. Add new row button lets us add as many rows as we want. After adding we can enter Yes in the input box and then Save.
Problem Statement:
I am facing one issue at this moment. When I am adding new rows, form do get saved but newly added rows get deleted leaving back only one row (Date and Yes/No).
I am wondering what changes I should make in the php code above so that when we add new rows, it should have some values associated with it so that when we save the form newly added rows should stay
there with their respectibve values.
When there is one row (when I am not adding new row), everything is pulled from the JSON and its working perfectly fine.

You'll need to make some alterations to both your HTML, JS and PHP for it to work properly. No communication is needed from JS to PHP. The form submission already works, right?
Modify the name attribute value.
Because you have multiple select and input elements in your code you'll want to be able to send all of the values of these elements to the server. But because they all have the same name attribute values you'll need to make a modification to these values.
Add a [] to the end of the name. This enables PHP to read every house_sitting_date_yes_no as an array. That means that every, in this case, select field value on the page will be send to the server in the global $_POST variable.
Check the example below.
<select name="house_sitting_date_yes_no[]">
...
</select>
The name has a [] at the end to indicate that there will be multiple values under the same name of house_sitting_date_yes_no.
<?php
$_POST[ 'house_sitting_date_yes_no' ] // array( 'yes', 'no', 'nada' )
?>
On the serverside you can access these values like you normally would do. But in this case it is not a string but an array with multiple strings. One string for each, in this example, select field.
An ID can only be used ONCE. Use classes instead.
Your newRow function creates a new row. Which is a perfect way to do it but the function also outputs elements with id's. ID's have to be unique and cannot be on the page more than once.
Wherever the id's can be removed, remove them and use a class instead. Or make them unique like they should be.
Storing the values in JSON
You were already on your way with this one with opening and decoding the JSON file. I assume you want your JSON to be updated with more data instead of overwriting the current data.
Since the data will be stored in associative array that is encoded to JSON it's possible to use array_merge_recursive to combine these arrays and their values.
After combining the values encode the array back to JSON and use file_put_contents to save your file again.
$output = array();
$output['house_sitting_date'] = $_POST['house_sitting_date'];
$output['house_sitting_date_yes_no'] = $_POST['house_sitting_date_yes_no'];
$file_url = '../feeds/ptp-ess_landing_house.json';
if (file_exists($file_url)) {
// Get current file.
$current_data = json_decode(file_get_contents($file_url));
// Combine data if possible, or create a new data.
if (is_array($current_data)) {
$new_data = array_merge_recursive($current_data, $output);
} else {
$new_data = $output;
}
// Update the file with new data.
$updated_data = json_encode($new_data);
file_put_contents($file_url, $updated_data);
}
I hope this helps you out.

Ok from what I see in your code is the old way I used to do things when working with PHP
I used to mix PHP with HTML and Javascript which on a big projects makes things a lot harder to maintain and debug especially many years down the line .You end up with many if else statements that could complicate your code
As well as if the PHP server is hanging because of shared hosting traffic or latency at least the clients browser does not hang. XHR and Rest API's were the Aha moment for me...
So I changed the way I worked with the web technologies and started working with rest API clients and separating my front end and back end technologies
Here is my suggestion
HTML Forms, XHR and Jasvascript posts to the rest PHP server for
every onclick event (this keeps the browser fast and wont hang like a php page sometimes does when working with background service)
The server handles each request reads the JSON from the file and
slots the new entry in then saves the file (PHP ONLY in the background)
Javascript then refreshes the JSON cache. At the end of the XHR request display the dates page (do this by adding keywords like async and await )
Here is the start..
Call this file post.PHP
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');
if($_POST)
{
echo json_encode($_POST);
//Open your Existing JSON file here and do the edits to append the new data
//Note weather your data passed or failed you have to respond back to the XHR request in the front end with json_encode...
}else{
echo json_encode(
array('message' => 'Post Created')
);
}
?>
Its the same as a rest client access point. This file is where you edit your json with the update ...
The snippet is the frontend with the XHR and a special technique to extract form data from a HTML form
function rowAdd(event) {
document.getElementById("rows")
.insertAdjacentHTML('beforeend', newRow());
}
// Iterator to get allow unique for ID;s
let i =0 ;
function newRow() {
i++;
return `
<div id="default-node" class="sitting-days" style="display:flex; justify-content:center; margin-bottom:20px;">
<div class="select-date" style="margin-right:30px;">
<input type="date" id="house-sitting-date`+i+`" name="house_sitting_date`+i+`" value="">
</div>
<div class="yes-no">
<select name="house_sitting_date_yes_no`+i+`" id="house-yes-no`+i+`" style="height:24px;">
<option value="nada" selected>Please choose an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
`
}
let xtart = document.getElementById('xhrStart');
xtart.addEventListener('click',function(){console.log('Xstarted')
// First iterate over the form and get all the form Values
var element = {};
var data = new FormData(theForm);
// Display the key/value pairs
for(var pair of data.entries()) {
// console.log(pair[0]+ ', '+ pair[1]);
element[ pair[0].toString() ] = pair[1];
}
console.log(element);
// Time to send the control over to PHP to do its magic
let xhr = new XMLHttpRequest();
xhr.open('POST', 'post.php');
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.responseType = 'json';
xhr.send(JSON.stringify(element));
//xhr.send();
// the response is {"message": "Hello, world!"}
xhr.onload = function() {
let responseObj = xhr.response;
alert(responseObj.message); // Hello, world!
};
});
<h3 style="text-align:center;margin-top:45px;">Sitting Days</h3>
<div class="add-new-row-button">
<input type="button" id="addRow" value="Add New Row" onclick="rowAdd()" />
</div>
<form id='theForm'>
<div id="rows">
<div class="sitting-days" style="display:flex; justify-content:center; margin-bottom:20px;">
<div class="select-date" style="margin-right:30px;">
<h4 style="text-align:center;">Select Date</h4>
<input type="date" id="house-sitting-date" name="house_sitting_date" value="">
</div>
<div class="yes-no">
<h4 style="text-align:center;">Yes/No</h4>
<select name="house_sitting_date_yes_no" id="house-yes-no" style="height:24px;">
<option value="nada" selected>Please choose an option</option>
<option value="yes">Yes</option>
</select>
</div>
</div>
</div>
<input type='button' value='Submit' id='xhrStart'>
Note I gave the form an ID and created and iterator so each new element in the form is unique
Here is the snippet ...
PHP leaves you also slightly in the dark about the weather data was received or not and using XHR allows you to easily see server responses with Google debugging tools ... Node JS , react and and all the other great technologies have used the same principals of rest api because it allot simpler and it makes debugging on chrome a breeze
Here is an image of the debug
Trust this helps and allows you to work far more efficiently

<?php
echo "<div id='demo'></div>";
?>
<script type="text/JavaScript">
// Function is called, return
// value will end up in x
var x = myFunction(11, 10);
document.getElementById("demo").innerHTML = x;
// Function returns the product of a and b
function myFunction(a, b) {
return a * b;
}
</script>

Related

Converting Javascript to PHP Variable [duplicate]

This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 months ago.
I'm looking for some help I am trying to get the value that is selected on the first dropdown (id="select1") without submitting the form after some research I have been able to get the value of the first dropdown and output it with an alert with the below.
<select name="select1" id="select1" class="form-control" required="required"
onchange="getValue(this)">
<script>
function getValue(obj){
alert(obj.value);
}
</script>
What I'm struggling to do is store it as a php variable which I can use in the second dropdown (id="select2) this is my code any help with pointing me in the right direction would be appreciated.
<div class="form-group">
<label>Select 1</label>
<br>
<select name="select1" id="select1" class="form-control" required="required"
onchange="getValue(this)">
<option disabled selected>-- Select 1 --</option>
<?php
$records = mysqli_query($conn, "SELECT name1 From table_001");
while($row = mysqli_fetch_array($records))
{
echo "<option value='". $row['name1'] ."'>" .$row['name1'] ."</option>";
}
?>
</select>
</div>
<script>
function getValue(obj){
return(obj.value) ;
}
</script>
<?php
$phpvar = "OUTPUT OF THE ABOVE JS";
?>
<div class="form-group">
<label>Select 2</label>
<br>
<select name="select2" id="select2" class="form-control" required="required">
<option disabled selected>-- Select 2 --</option>
<?php
$records1 = mysqli_query($conn, "SELECT name2 From table_002 where name1 = '$phpvar'");
while($row = mysqli_fetch_array($records1))
{
echo "<option value='". $row['name2'] ."'>" .$row['name2'] ."</option>";
}
?>
</select>
</div>
If I've understood your question right, you can't just "store" a variable in php. PHP is a server side, JS is a client side. The only way to exchange data between them is an http request-response pair. (We're not talking about websockets etc)
You can do the http request in two ways:
Form submit. When you're submiting a form, the data form this form is sent to a server either via GET or POST method. Then the server performs some actions and send a response. The page then is refreshed (or you are redirected to another page etc).
AJAX request. The principle is the same except you don't leave the actual page (there is no page refresh or redirection). The JS code is doing a request, then it receives a response event when response comes from server, and then you can do whatever you want with this response (insert it on the page, change select value etc).
Form submit way
I don't think this is your case, cause you need first of all submit the first form and then the page will be refreshed and the new page will be returned with the first form cleared but with a desired value inserted from php in a second form
AJAX way
This is the preferable solution for you. You can make an ajax request either with
XMLHttpRequest (the old way) or fetch (the modern way). These are two native ways in browser (there exist also a lot of libraries, like jquery.ajax(), that are mostly the wrappers above these two methods described above).
Here is a basic example using fetch API, you may put this in a onChange event handler for your first select (:
fetch('./some_address.php')
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
// your server-side script may return a complex (or not :) json object or just a plain text, read the documentation for your case
return response.json(); // or return response.text();
})
.then((data) => {
// do whatever you need with your response from the server, for example set the value for your second select
});

How to pass value of the table row into the variable in modal

I have a table from which I am successfully passing values into the textfields in modal. However, I need to create the select dropdown within modal, which will be based on value passed from the row.
Table
edit | ref. number |
.edit_record button | AAA01 |
js
$(document).ready(function () {
$('.edit_record').on('click', function() {
$('#edit_record_modal').modal('show');
$tr = $(this).closest('tr');
var data = $tr.children("td").map(function() {
return $(this).text();
}).get();
console.log(data);
$('#ref').val(data[1]);
});
});
modal
<div class="form-group">
<input id="ref" type="text" name="ref" class="form-control">
</div>
<div class="form-group">
<select name="selectDate" id="selectDate" onchange="">
<?php
$ref_list_result= mysqli_query($db_conn,"SELECT ref_no FROM record WHERE
caller_number= /*the value of row*/");
while ($row = mysqli_fetch_array($ref_list_result)) {
$ref_no = $row['ref_no'];
?>
<option value=<?php echo $ref_no ?>><?php echo $ref_no ?></option>
<?php } ?>
</select>
</div>
Is it possible to pass that value from #ref textfield into the php variable, so I can compare it against condition in SQL's WHERE clause? Perhaps, maybe there is a different way to do this?
Short Answer: You cant pass variables in PHP and JavaScript unless you are using an API to transfer data
Long Answer:
If you only know how PHP works, it is what is called a "Pre-templater" which means that in the server, or somewhere it is deployed, the server translates PHP codes into HTML and JavaScript depending on your echo. This means that by the moment the code you've written gets sent to the browser, it is all HTML, JS and CSS.
Alternative Approach: You could try building an API using PHP, and use AJAX to modify the dropdown. Search the following in google "PHP API" and "AJAX Call On PHP".

Submit form on same page without reloading and use POST variable

I need to get the value of a post variable from a form and transform this to a PHP variable to use it on the same page without reloading it
Actually I got this :
$(function() {
$("#submit_post").click(function() {
var select = $("select").val();
$.post("process.php",{select:select},function(result){
$('#result').append(result);
});
});
})
And
<form method="post">
<select name="select" id="select">
<option value="1">Test</option>
</select>
<input type="submit" id="submit_post" value="Envoyer" onclick="return false;"/>
</form>
<div id="result"></div>
When I do :
<?php var_dump($_POST["select"]); ?>
I got : null
But on div result I got : 1
...
I need to lake this "1" a php variable
Your code runs fine on my server. Maybe you aren't totally clear on the function of the superglobals.
If the "result" div contains "1" after you press the button, then that means process.php is correctly receiving your POST request and echoing back the value of $_POST["select"]. You will get "NULL" if you try to just navigate your browser to process.php, because when you do so you are making a separate request which doesn't contain any POST variables. The superglobal arrays don't persist between different calls to process.php unless you create that functionality using $_SESSION, a DB, or some kind of text/json/xml storage system. The following changes to your PHP will allow you to click your button and then separately navigate to process.php and see your data:
<?php
session_start();
if ($_POST["select"]) {
$_SESSION["data"] = ($_POST["select"]);
}
var_dump($_SESSION);
?>
Please correct me if I have made the wrong assumptions and this is not helpful.
-Ben

JQuery populating select box but after post options disappear

I have an SVG map. When someone clicks on a state say, "Kansas" it displays a form and populates the state select box with the state that was clicked on say, it's Kansas. Code - This is working fine. This code is in the head.
var itemval= '<option value="'+data.name+'">'+ stateData[data.name].fullName+'</option>';
$("#SelItem").html(itemval);
When the form is submitted and it posts back to the same page, I'm using
<form method="POST" action="theform.php" onsubmit="return validateForm(this);">
When the page post back to the same page the select box is empty. The select box is there but with no option.
I've searched on Google I found the code below plus a few similar ways but they don't work. I've used this code in the head and under the select but no luck.
var selectedVal = $("#SelItem").val();
$("#SelItem").val(selectedVal);
**HTML**
<select id="SelItem"><option></option></select>
I've been working on this for hours but can't seem to find a solution.
Can someone tell me how to keep the select value after the form has been submitted and returns to the same page?
When the page loads you need to check for the presence of your posted value, and if it's there pass the php value to either the javascript code to populate the select option, or use it directly in the html creating the select options.
First off, you should give your select a name attribute in the html so the value is passed into the $_POST array in php:
<select id="SelItem" name="SelItem">
Here's one way you can populate it in javascript (note this code relies on the var stateData being in the same scope):
$(document).ready(function(){
<?php if (!empty($_POST['SelItem'])): ?>
var posted_state = '<?php echo $_POST['SelItem'];?>';
if (stateData[posted_state] !== undefined) {
var itemval= '<option value="'+posted_state+'" selected>'+ stateData[posted_state].fullName+'</option>';
$("#SelItem").html(itemval);
}
<?php endif; ?>
});
EDIT: An alternative to the above would be to put it in the html for the select tag:
<select id="SelItem" name="SelItem">
<?php if (!empty($_POST['SelItem'])): ?>
<option value="<?php echo $_POST['SelItem'];?>" selected>
<?php echo $_POST['SelItem']; // this would be better if you can replace it with fullname ?>
</option>
<?php else: ?>
<option></option>
<?php endif; ?>
</select>
Note this method has a couple issues as it's written. First off, the option text in this example won't be the state full name but the abbreviation. Next, you shouldn't trust the contents of $_POST because a malicious user can easily change it to a value you didn't intend it to be. It would be better to validate the value of $_POST['SelItem'] in your php code that handles the post to make sure it is actually one of the correct values before using it. That is why in the previous example I did the check if (stateData[posted_state] !== undefined) before attempting to add the value to your select.
EDIT:
To provide the state fullname from php you need an array of states defined on the php side also (I only see it in your javascript code which is client side).
So in php if you have something like:
$states = array(
'AK' => 'Alaska',
'AL' => 'Alabama',
// etc...
);
Then you can use the posted state abbreviation to get the fullname:
if (array_key_exists($_POST['SelItem'], $states))
$fullname = $states[$_POST['SelItem']];

Send values to a client page

I would like to ask what code should i start to study to perform this kind of task in a webpage...the thing is the server and client is both active..if the server type a values in the input(boxes) and click send it will automatically send it to the client page wich is already opened by a client....is this possible??im just a newbie programmer...help me please.
what code should i study and is there any tutorial about this? can i have a link? please
This should do the work:
get_data.php
<?php
/* Your db-code
Put it in an array called $data
like:
$data = array('name' => $row['name'], 'age' => $row['age']); */
header('Content-type: application/json');
echo json_encode($data);
?>
JS
function check_for_data() {
$.post('get_data.php', function(data){
$("#name").html(data.name);
$("#age").html(data.age);
$('#'+data.gender+'').prop('selected', true);
// etc...
}, "json");
}
setInterval(check_for_data, 5000);
HTML
<input type="text" id="name">
<input type="text" id="age">
<select>
<option id="male" value="male"></option>
<option id="female" value="female"></option>
</select>
<!-- etc -->
Note
1. You've got to have the name the id to the <option> tags the same as the possible values from the database for gender.
2. Functions like this tend to go heavy on the server. If this will be used by many people on your site, you can make the function check for new data less often (right now it does so every 5000 milliseconds (5 seconds)).

Categories

Resources