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)).
Related
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
});
I currently make my first Wordpress website using Java script snippets for a countdown that refreshes itself constantly and allows me to click a button once every 6 hours. So I managed that the time refreshes itself but I need one permanent variable that tells me if I already clicked the button or not (since it should work wether I refresh the page, go to another side or even log in with another user).
Basically I just want one variable that changes between 0 and 1.
I implemented a hidden input field and it works just fine as long as I stay on the side (refreshing the side works as well) but as soon as I change the page it sets the variable back. I tried to implement a global variable in the function.php of my theme (and a function as well) but it still doesn't work.
I tried it like this:
global $x;
echo $x;
And this:
function displayX() {
global $x;
$x = "0";
echo $x;
}
The thing is I don't want to set a value because the variable needs to be changeable any time.
That's my current html:
<input type="text" id="id1" value="<?php echo $x; ?>" <="" input="">
But it just doesn't work.
My second approach was to make the input field permanent (but updateable) - again this approach works as long as I don't change the side.
I tried it like this:
<span id="00">
<input type="text" id="id1">
</span>
Can anybody please help me? Also please specifiy where I have to set the global variable since there are so many function.php files.
THANK YOU!
Easiest way to do that is using of update_option and get_option.
update_option is for save data to database that will be permanent.
get_option is for fetching data from database.
<form method="post">
<input type="text" name="permanent" id="permanent" value="<?php echo get_option('permanent_data'); ?>"/>
<input type="submit" name="save" value="submit"/>
</form>
You can catch form data in backend using an action like this:
in functions.php
add_action('init','save_permanent');
function save_permanent(){
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
}
Below code checks that if form is submitted:
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
If form submitted it gets value of input text that named permanent
Mentioned code permanent the data in database as name of permanent_data
If you want to fetch stored data you just call get_option(option name) like this:
<?php echo get_option('permanent_data'); ?>
For first question you can do it in such way:
in functions.php
<?php
if(if(isset($_POST['save']))){
update_option('already_clicked', '1');
}
And for fetch stored data you can use:
<?php
if(get_option('already_clicked') == '1'){
//do somthing
}
?>
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".
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>
I am new to this forum. I have been developing a interface and have got stuck with PHP and Javascript.
My Site has 3 Buttons
<button id="ProjectSource" class="testbutton" onClick="AddNewProject(this.id);">Project Source</button>
<button id="SelfCons" class="testbutton" onclick="AddNewProject(this.id)">Self Cons</button>
<button id="Currency" class="testbutton" onclick="AddNewProject(this.id)">Currency</button>
These buttons are sent to a Javascript function on the same page which will store the button ID in a variable, which is later used in another PHP.
Now I have an Select Box in the same page and I get the data from the database using PHP.
<select size="10" id="Database" onClick="ClearAdd()" >
<?php
while($row = mysql_fetch_assoc($get))
{
?>
<option value = "<?php echo($row['ProjectSource'])?>" >
<?php echo($row['ProjectSource']) ?>
</option>
<?php
}
?>
</select>
My First Problem is
If you see I am currently using $row['ProjectSource']), But what I need is the ID of the buttons which corresponds to the field name in the database.
My Second Problem is
The Select functions loads when the page loads, I want that to refresh when I click on any buttons.
Thanks in Advance for your help!
use mysql fetch query
For example:
while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
}
For your second Problem you should implement ajax. Either using javascript or jquery.
Regarding first problem it is not clear What are the field names and how button Id is implemented? It would be better if you post some code
Can you implement some kind of mapping of your fieldName to your buttonId using associative array? like array("fieldName1"=>"id1",....)