I have a javascript that dynamically builds an html page. In the html page there are textarea boxes for the user to type information in. The information already exists in a database. I would like to populate the textarea boxes with the database in the mysql database.
I have php code that will connect to the database and build an html table with the data, so I know how to do this with php, but I don't know how to do this from the javascrip. I've studied ajax get requests, etc., but I'm still not sure of how to do this.
Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php,
$result = mysql_query("SELECT field_name, field_value
FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
$to_encode[] = $row;
}
echo json_encode($to_encode);
If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />. You can reference that field with this jQuery: $("#field1").val().
Here's a complete example with the HTML. If we're assuming your fields are called field1 and field2, then
<!DOCTYPE html>
<html>
<head>
<title>That's about it</title>
</head>
<body>
<form>
<input type="text" id="field1" />
<input type="text" id="field2" />
</form>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$.getJSON('data.php', function(data) {
$.each(data, function(fieldName, fieldValue) {
$("#" + fieldName).val(fieldValue);
});
});
</script>
</html>
That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value attribute.
To do with javascript you could do something like this:
<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>
Then you can use whatever you want in your javascript to put the text var into the textbox.
Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?
Send AJAX request to php script
PHP script processes request and builds table
PHP script sends response back to JS in form of encoded HTML
JS takes response and inserts it into the DOM
You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.
Related
I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!
I have the following JS code:
<script>
$('#mpxModalEdit').on('show.bs.modal', function(e) {
var editId = $(e.relatedTarget).data('edit-id');
$(e.currentTarget).find('input[name="editId"]').val(editId);
});
</script>
This places the CORRECT edit-id value into a form text box name=editIdas I wish.
I would like to add another line of JS so that it ALSO places the value into a PHP variable since I need to make a subsequent
$query = "select * from playlists where id='editId'
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
That could be the best solution only.
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
Or the another way is to use AJAX.
PHP-Scripts are only run, when you load your page before any js is run or make an AJAX. In addition, PHP runs on the server, while JS is client-side.
My first suggestion would be, to really think, whether you need to do this (or even tell us, why you think it is).
If you really need it, you can perfom an AJAX and send your variable as data to the Server.
Using AJAX call you can pass js values to PHP script. Suppose you are passing editId js value to logtime.php file.
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data: { editId : editId },
success: function(data)
{
alert("success!");
}
});
});
});
<?php //logtime.php
$editId = isset($_POST['editId']);
//rest of code that uses $editId
?>
Place the AJAX call after
$(e.currentTarget).find('input[name="editId"]').val(editId);
line in your js script.
then you can assign to your desired PHP variable in logtime.php file
I'm trying to use the value stored in token in my PHP script to update a database value with SQLite. It wont let me use document.getElementByID....any ideas?
<div id="TokenCount">
<label for="token"><abbr title="Tokens">Tokens</abbr></label>
<input id="token" value="0" />
</div>
<div id="Buttons">
<button id="pay" onClick="pay(10); loadMessage()"><?php $db=sqlite_open("../../logins.db");
$token = document.getElementById('token').value;
sqlite_query($db,"UPDATE Users SET tokens='$token' WHERE user_id='{$_SESSION['user_id']}'");
sqlite_close($db); ?>Pay</button>
</div>
</div>
PHP code is executed server-side, so the website is sent to the client with the result of the PHP code without any PHP found in the source. Because of this HTML tags cannot be used in PHP on a website.
As i said in comments, you can't execute PHP-code(server side code) on client side (in browser).
You should send AJAX query to server, and save this value to mysql on server side.
Javascript(jquery) code:
function loadMessage(){
$.post("setValue.php", {val:document.getElementById('token').value} function( data ) {
alert('success');
});
}
Create new php script for example setValue.php (r use contoller action, or your own staff how you routing pages). Script code:
$token = $_POST['val'];
sqlite_query($db,"UPDATE Users SET tokens='$token' WHERE user_id='{$_SESSION['user_id']}'");
sqlite_close($db);
I trying to store CSV data to database using onclick function. Unfortunately, I am using php code inside javascript function which is not efficient enough. Therefore, I hope that I can get any suggest or solution to improve efficiency of my project by using javascript instead of php to store CSV data into database.
This is javascript with php code :
<script>
function storeQueEmail(){
<?php
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
$record['contact_first'] = $data[0];
$record['contact_last'] = $data[1];
$record['contact_email'] = $data[2];
$record['subject'] = $_REQUEST['subject'];
$record['message'] = $_REQUEST['message'];
$record['status'] = 0;
$oAdminEmail->insertQueEmail($record);
}
} while ($data = fgetcsv($handle,1000,",","'"));
?>
}
</script>
This is HTML code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1" >
Subject : <br/>
<input type="text" name="subject" id="subject" required/> <br/>
Choose your upload type: <br />
<input name="csv" type="file" id="csv" accept=".csv" required/> <br/>
Content : <br/>
<textarea name="message" cols="50" rows="10" required></textarea><br/>
<input type="submit" name="submit" value="Submit" onclick="storeQueEmail()"/>
</form>
</body>
</html>
what are you trying to do there? I think you are speaking about a PHP in
HTML document. So your PHP code inside your function is interpreted on server. As your PHP code has no output your Javascript function is simply empty. Thus as you have registered your Javascript function as onclick handler just nothing would happen.
Remember that standard Javascript code is interpreted on Client (that means in browser) though you PHP code is interpreted on server. As mentioned in the comments above it is possible to use an AJAX or POST/GET - Request to send data to your server and then write it to your DB or file etc.
Another way to do this directly with Javascript is Node.js - serverside Javascript that is able to write to your Database like PHP can do.
The easiest way for you to do it with your HTML code you presented above is to fill in your
action - attribute
in your
form tag
For example:
<form action="proccessData.php" ...>
...
</form>
Don't forget to remove your onclick - attribute inside form's submit input field.
If you know press your submit button your entire form and its content will be send to http://www.xyz.de/proccessData.php. Inside that file you can work with your form data: In your case two text fields and one file upload field. As you may know you could get to the content of text input field send via post via:
$_POST['<name of field>']
To get your uploaded file and proccess it you could use PHP's global
$_FILE[] - Array
Just refer to PHP's manual on php.net or some other online documentation. There's pretty much to find on the web.
I just give you a helpful link to php.net on how to handle file uploads in a correct and therefor secure manner: http://us2.php.net/manual/en/features.file-upload.php
Once you have read your uploaded file via PHP's global $_FILE[] - array just proccess that file via fgetcsv in your proccessData.php and write it line for line to your database.
Hope that helps! It is really not that hard :)
I have two dropdown menus that read their data from a MySQL database. I use PHP for connecting to database. The second dropdowns should get populated based on the selection on the first dropdown. The process seems as below to me (correct me if I'm wrong):
PHP section connects to MySQL database and populates dropdown1.
user selects a value on dropdown1 and onchange event is called.
within the onchange function (which is Javascript), a query is sent to MySQL database to fetch values of dropdown2 based on the dropdown1 selection (here is PHP again, right?).
dropdown2 gets populated.
I don't know how to use Javascript and PHP together in order to do this task (number 3 above); or maybe this is not the way to do it at all. Please advise!
Here is my code. As you see below, I'm putting a Javascript function within a PHP code which I suppose is wrong. That's where I got stuck!
<php
$sql="SELECT distinct category FROM table1";
$result=mysql_query($sql);
$optionsCat="";
while($row = mysql_fetch_row($result)){
$optionsCat.="<option value=\"$row[0]\">$row[0]</option>";
}
function genSubCat($catID){
$sql="SELECT distinct subcategory FROM table1 where category=".$catID;
$result=mysql_query($sql);
$optionsSubCat="";
while($row = mysql_fetch_row($result)){
$optionsSubCat.="<option value=\"$row[0]\">$row[0]</option>";
}
}
?>
<select name="catDropDown" onChange="genSubCat(this)">
<option value="0">Select category</option>
<?php echo $optionsCat?>
</select>
<select name="subcategoryDropDown">
<option value="0">Select subcategory</option>
<?php echo $optionsSubCat?>
</select>
Here we have a simple page with input on it. Type a word into it and then click off of the input. Ajax will call the myphp.php script and return the same word you typed in below the original division.
test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#faq_search_input").blur(function(){
var faq_search_input = $(this).val();
var dataString = 'keyword='+ faq_search_input;
if(faq_search_input.length>1){
$.ajax({type: "GET", url: "myphp.php", data: dataString,
success: function(server_response) {
document.getElementById("searchresultdata").style.display = "block";
$('#searchresultdata').html(server_response).show();
}
});
}
return false;
});
});
</script>
</head>
<body>
<div class="searchholder">
<input name="query" class="quicksearch" type="text" id="faq_search_input" />
<div id="searchresultdata" class="searchresults" style="display:none;"> </div>
</div>
</body>
</html>
myphp.php:
<?PHP
echo $_GET['keyword'];
?>
I think you should first study yourself about using web based languages. The code that you've provided is completely wrong. You're trying to access PHP code through HTML? I mean come on!
First rule: Server based languages can't communicate with Client based languages.
You have to send requests and get responses and the way you want to do that dropdown thing is to send a request to a PHP code and get relevant data from it. As Trufa said in the comment, you may want to look at jQuery library, but before that I think you need to check AJAX.