I am working on a form whereby JavaScript is used to add another line item. The purpose is to add line items to an invoice. I have successfully got this to work ok when using text boxes in my form, but am stuck on how to get this to work with a dropdown box that makes a call to mysql to get the dropdown box data.
Here is what I have.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
include $_SERVER['DOCUMENT_ROOT']."/includes/header.php";
?>
<script type="text/javascript">
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><select name='myInputs[]'><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>";
document.getElementById(divName).appendChild(newdiv);
}
</script>
<form method="POST">
<div id="dynamicInput">
Entry 1<br><select name="myInputs[]"><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
</form>
So here is some info on what is going on. Right now, the JavaScript code above shows the MySQL query in it. This kills the add line item functionality. If I simply remove the query but leave the other php in, the add line item begins to work again, but of course there is no data in the drop down.
In the form itself, it gets the first line item from the database without using javascript and this is working ok.
I feel like I am getting close, but don't know where to go from here.
Thanks in advance.
EDIT:
Thanks to Nick, I got this working. Here is the code.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
include $_SERVER['DOCUMENT_ROOT']."/includes/header.php";
?>
<script type="text/javascript">
var counter = 1;
function addInput(div){
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (++counter) + " <br><select name='myInputs[]'>" + xmlhttp.responseText + "</select>";
}
document.getElementById(div).appendChild(newdiv);
}
xmlhttp.open("GET", "update_text.php", false);
xmlhttp.send();
}
</script>
<form method="POST">
<div id="dynamicInput">
Entry 1<br><select name="myInputs[]"><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>
</div>
<input type="button" value="Add" onClick="addInput('dynamicInput');">
</form>
Then the update_text.php
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$result = mysql_query("SELECT * FROM salesitem");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
?>
And here is my php post into the database which is not working for the javascript add line item, only for the original entry that is created from the form. (I have other fields besides the dropdown).
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$company = mysql_real_escape_string($_POST['company']);
foreach($_POST['item'] as $i => $item)
{
$item = mysql_real_escape_string($item);
$quantity = mysql_real_escape_string($_POST['quantity'][$i]);
mysql_query("INSERT INTO invoice (company, item, quantity) VALUES ('$company', '".$item."', '".$quantity."') ") or die(mysql_error());
}
echo "<br><font color=\"green\"><b>Invoice added</b></font>";
?>
Thanks, please let me know if I can clean this up better.
Sadly the way you'r trying to do it wont work due to the nature of PHP.
When a client requests your page from the server ALL the php is executed.
So the php block inside your javascript function is actually just the static result of your php.
You'll need to use XMLHttpRequests/Ajax to request the new data from the server.
Here's a quick (and probably fairly bad) example!
Modification to your javascript function:
var counter = 1;
function addInput(div) {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var d = document.getElementById(div);
d.innerHTML=d.innerHTML +"<div>Entry " + (++counter) + " <br><select name='myInputs[]'>" + xmlhttp.responseText + "</select></div>";
}
}
xmlhttp.open("GET", "updated_list.php", false);
xmlhttp.send();
}
A new php file on your server: (updated_list.php)
<?php
// you'll need to include stuff to connect to your database here
$result = mysql_query("SELECT * FROM salesitem");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
?>
update
I did say it was a bad example :) my original code overwrote the contents of your div instead of adding to it, which ive updated. this was only an example, you should read up on AJAX and how to request data from the server.
You cannot use server code inside a javascript function after the page is load.
The server side code is like it's name - code that runs on the server. so after the page finish loading it "get back" to the client and only client code (javascript) can run now.
so your line
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><select name='myInputs[]'><?php $result = mysql_query("SELECT * FROM salesitem"); while($row = mysql_fetch_array($result)) { echo "<option value=\"".$row['name']."\">".$row['name']."</option>";} ?></select>";
is a bit mistake.
what you can do is to return the data from the database to the javascript (using json will be the best option) and then build the select box dynamically using the raw data that came from the server that is now a javascript data.
so let's say your data is
var data = [{name:'n1'},{name:'n2'},{name:'n3'}];
You can run this data using javascript and build your combo:
var newSelect = document.createElement('select');
for(var i=0;i<data.length;i++){
var name = data[i].name;
newSelect.options[newSelect.options.length] = new Option(name,name);
}
This is a classic example for AJAX (Asynchronous Javascript And XML) - the basic concept is that when an action is carried out (e.g. a button clicked to show content), some JavaScript calls a PHP (asynchronously), the PHP runs, returns an XML file (although this can actually be any file format you want, some people now prefer to use JSON because it's easier to parse), and the contents of the this XML / JSON are displayed, also using JavaScript.
Although the example above is displaying content, there's no reason why any action where you need to run on the server (e.g. inserting data to a database) can't also be done asynchronously.
SO is not a place for code to be written for people - so now I've given you a hint as to where to start, and as an exercise for the reader ( / question asker!), have a look at some AJAX tutorials, make sure you understand the concept, write some code, and come back if still can't get it working!
Good luck :)
Related
I want to pass JavaScript variables to PHP using a hidden input in a form.
But I can't get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?
Here is the code:
<script type="text/javascript">
// View what the user has chosen
function func_load3(name) {
var oForm = document.forms["myform"];
var oSelectBox = oForm.select3;
var iChoice = oSelectBox.selectedIndex;
//alert("You have chosen: " + oSelectBox.options[iChoice].text);
//document.write(oSelectBox.options[iChoice].text);
var sa = oSelectBox.options[iChoice].text;
document.getElementById("hidden1").value = sa;
}
</script>
<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<?php
$salarieid = $_POST['hidden1'];
$query = "select * from salarie where salarieid = ".$salarieid;
echo $query;
$result = mysql_query($query);
?>
<table>
Code for displaying the query result.
</table>
You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.
<DOCTYPE html>
<html>
<head>
<title>My Test Form</title>
</head>
<body>
<form method="POST">
<p>Please, choose the salary id to proceed result:</p>
<p>
<label for="salarieids">SalarieID:</label>
<?php
$query = "SELECT * FROM salarie";
$result = mysql_query($query);
if ($result) :
?>
<select id="salarieids" name="salarieid">
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
}
?>
</select>
<?php endif ?>
</p>
<p>
<input type="submit" value="Sumbit my choice"/>
</p>
</form>
<?php if isset($_POST['salaried']) : ?>
<?php
$query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
$result = mysql_query($query);
if ($result) :
?>
<table>
<?php
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
echo '</tr>';
}
?>
</table>
<?php endif?>
<?php endif ?>
</body>
</html>
Just save it in a cookie:
$(document).ready(function () {
createCookie("height", $(window).height(), "10");
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
And then read it with PHP:
<?PHP
$_COOKIE["height"];
?>
It's not a pretty solution, but it works.
There are several ways of passing variables from JavaScript to PHP (not the current page, of course).
You could:
Send the information in a form as stated here (will result in a page refresh)
Pass it in Ajax (several posts are on here about that) (without a page refresh)
Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var PageToSendTo = "nowitworks.php?";
var MyVariable = "variableData";
var VariablePlaceholder = "variableName=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xmlhttp.open("GET", UrlToSend, false);
xmlhttp.send();
I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.
Here is the Working example: Get javascript variable value on the same page in php.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's how I did it (I needed to insert a local timezone into PHP:
<?php
ob_start();
?>
<script type="text/javascript">
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
<?php
$offset = ob_get_clean();
print_r($offset);
When your page first loads the PHP code first runs and sets the complete layout of your webpage. After the page layout, it sets the JavaScript load up.
Now JavaScript directly interacts with DOM and can manipulate the layout but PHP can't - it needs to refresh the page. The only way is to refresh your page to and pass the parameters in the page URL so that you can get the data via PHP.
So, we use AJAX to get Javascript to interact with PHP without a page reload. AJAX can also be used as an API. One more thing if you have already declared the variable in PHP before the page loads then you can use it with your Javascript example.
<?php $myname= "syed ali";?>
<script>
var username = "<?php echo $myname;?>";
alert(username);
</script>
The above code is correct and it will work, but the code below is totally wrong and it will never work.
<script>
var username = "syed ali";
var <?php $myname;?> = username;
alert(myname);
</script>
Pass value from JavaScript to PHP via AJAX
This is the most secure way to do it, because HTML content can be edited via developer tools and the user can manipulate the data. So, it is better to use AJAX if you want security over that variable. If you are a newbie to AJAX, please learn AJAX it is very simple.
The best and most secure way to pass JavaScript variable into PHP is via AJAX
Simple AJAX example
var mydata = 55;
var myname = "syed ali";
var userdata = {'id':mydata,'name':myname};
$.ajax({
type: "POST",
url: "YOUR PHP URL HERE",
data:userdata,
success: function(data){
console.log(data);
}
});
PASS value from JavaScript to PHP via hidden fields
Otherwise, you can create a hidden HTML input inside your form. like
<input type="hidden" id="mydata">
then via jQuery or javaScript pass the value to the hidden field. like
<script>
var myvalue = 55;
$("#mydata").val(myvalue);
</script>
Now when you submit the form you can get the value in PHP.
I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.
It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.
One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:
<img src="pic.php">
The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.
PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.
If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.
Here's a previous question that you can follow for more information: Ajax Tutorial
Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.
<?php
if(isset($_POST))
{
print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="data" value="1" />
<input type="submit" value="Submit" />
</form>
Clicking submit will submit the page, and print out the submitted data.
We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -
function statusChangeCallback(response) {
console.log('statusChangeCallback');
if (response.status === 'connected') {
// Logged into your app and Facebook.
FB.api('/me?fields=id,first_name,last_name,email', function (result) {
document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
console.log(document.cookie);
});
}
}
And I've accessed it (in any file) using -
<?php
if(isset($_COOKIE['fbdata'])) {
echo "welcome ".$_COOKIE['fbdata'];
}
?>
Your code has a few things wrong with it.
You define a JavaScript function, func_load3(), but do not call it.
Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
Your form has no means to submit it. It needs a submit button.
You do not check whether your form has been submitted.
It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:
<?php
if (isset($_POST['hidden1'])) {
echo "You submitted {$_POST['hidden1']}";
die;
}
echo <<<HTML
<form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
<input type="submit" name="submit" value="Test this mess!" />
<input type="hidden" name="hidden1" id="hidden1" />
</form>
<script type="text/javascript">
document.getElementById("hidden1").value = "This is an example";
</script>
HTML;
?>
You can use JQuery Ajax and POST method:
var obj;
$(document).ready(function(){
$("#button1").click(function(){
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: "addperson.php",
type: "POST",
async: false,
data: {
username: username,
password: password
}
})
.done (function(data, textStatus, jqXHR) {
obj = JSON.parse(data);
})
.fail (function(jqXHR, textStatus, errorThrown) {
})
.always (function(jqXHROrData, textStatus, jqXHROrErrorThrown) {
});
});
});
To take a response back from the php script JSON parse the the respone in .done() method.
Here is the php script you can modify to your needs:
<?php
$username1 = isset($_POST["username"]) ? $_POST["username"] : '';
$password1 = isset($_POST["password"]) ? $_POST["password"] : '';
$servername = "xxxxx";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO user (username, password)
VALUES ('$username1', '$password1' )";
;
if ($conn->query($sql) === TRUE) {
echo json_encode(array('success' => 1));
} else{
echo json_encode(array('success' => 0));
}
$conn->close();
?>
Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.
May be you could use jquery serialize() method so that everything will be at one go.
var data=$('#myForm').serialize();
//this way you could get the hidden value as well in the server side.
This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.
Just set a cookie with the data you want to pass to PHP using javascript in the browser.
Then, simply read this cookie on the PHP side.
We cannot pass JavaScript variable values to the PHP code directly... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.
So it's better to use the AJAX to parse the JavaScript value into the php Code.
Or alternatively we can make this done with the help of COOKIES in our code.
Thanks & Cheers.
Use the + sign to concatenate your javascript variable into your php function call.
<script>
var JSvar = "success";
var JSnewVar = "<?=myphpFunction('" + JSvar + "');?>";
</script>`
Notice the = sign is there twice.
I have a problem with updating the data I display from my db. Initially, when the page opens I display the date corresponding to the current date but then the user can change the date by entering it in a text box and when he clicks update all the data displayed should be deleted and the data corresponding to the new date should be displayed. Right now I have a javascript function which deleted all the data in the div when the button is clicked. The div holds the data I want to change. But I don't know how to add new data into the div. I tried to add php code to look up the database for the data in the javascript function but I don't know how to add it to the text box.
function changedate()
{
document.getElementById("label1").innerText=document.getElementById("datepicker").valu e;
document.getElementById("selecteddate").innerText=document.getElementById("datepicker" ).value;
document.getElementById("teammembers").innerHTML = "";//empties the div(teammembers)
<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
}
}
?>
}
You can use a combination of jQuery and AJAX to do this. Much simpler than it sounds. To see that this is the right answer for you, just view this example.
In the below example, there are two .PHP files: test86a.php and test86b.php.
The first file, 86A, has a simple selection (dropdown) box and some jQuery code that watches for that selection box to change. To trigger the jQuery code, you could use the jQuery .blur() function to watch for the user to leave the date field, or you could use the jQueryUI API:
$('#date_start').datepicker({
onSelect: function(dateText, instance) {
// Split date_finish into 3 input fields
var arrSplit = dateText.split("-");
$('#date_start-y').val(arrSplit[0]);
$('#date_start-m').val(arrSplit[1]);
$('#date_start-d').val(arrSplit[2]);
// Populate date_start field (adds 14 days and plunks result in date_finish field)
var nextDayDate = $('#date_start').datepicker('getDate', '+14d');
nextDayDate.setDate(nextDayDate.getDate() + 14);
$('#date_finish').datepicker('setDate', nextDayDate);
splitDateStart($("#date_finish").val());
},
onClose: function() {
//$("#date_finish").datepicker("show");
}
});
At any rate, when the jQuery is triggered, an AJAX request is sent to the second file, 86B. This file automatically looks stuff up from the database, gets the answers, creates some formatted HTML content, and echo's it back to the first file. This is all happening through Javascript, initiated on the browser - just like you want.
These two files are an independent, fully working example. Just replace the MYSQL logins and content with your own fieldnames, etc and watch the magic happen.
TEST86A.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "test86b.php", // "another_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
</head>
<body>
<select name="students" id="stSelect">
<option value="">Please Select</option>
<option value="John">John Doe</option>
<option value="Mike">Mike Williams</option>
<option value="Chris">Chris Edwards</option>
</select>
<div id="LaDIV"></div>
</body>
</html>
TEST86B.PHP
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
$server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
$login = 'abcd1234';
$pword = 'verySecret';
$dbname = 'abcd1234_mydb';
mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
mysql_select_db($dbname) or die($connect_error);
//Get value posted in by ajax
$selStudent = $_POST['theOption'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT `user_id`, `first_name`, `last_name` FROM `users` WHERE `first_name` = '$selStudent' AND `user_type` = 'staff'";
$result = mysql_query($query) or die('Fn test86.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = '
<h1>Found in Database:</h1>
<ul style="list-style-type:disc;">
';
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_assoc($result)) {
$r = $r . '<li> ' . $row['first_name'] . ' ' . $row['last_name'] . ' -- UserID [' .$row['user_id']. ']</li>';
}
} else {
$r = '<p>No student by that name on staff</p>';
}
//Add this extra button for fun
$r = $r . '</ul><button id="theButton">Click Me</button>';
//The response echoed below will be inserted into the
echo $r;
Here is a more simple AJAX example and yet another example for you to check out.
In all examples, note how the user supplies the HTML content (whether by typing something or selecting a new date value or choosing a dropdown selection). The user-supplied data is:
1) GRABBED via jQuery: var sel_stud = $('#stSelect').val();
2) then SENT via AJAX to the second script. (The $.ajax({}) stuff)
The second script uses the values it receives to look up the answer, then ECHOES that answer back to the first script: echo $r;
The first script RECEIVES the answer in the AJAX success function, and then (still inside the success function) INJECTS the answer onto the page: $('#LaDIV').html(whatigot);
Please experiment with these simple examples -- the first (simpler) linked example doesn't require a database lookup, so it should run with no changes.
You want to output a literal JS statement with whatever you get back from php, basically:
document.getElementById("teammembers").innerHTML = // notice no erasing, we just
// overwrite it directly with the result
"<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
// so just show it!
echo $email_users; // think about this for a second though
// what are you trying to achieve?
}
}
?>"
This is a vast question, not very specific. Checkout more about AJAX requests - basically from javascript you will have a call to the server that retrieves your data.
This is a snippet from the javascript library jQuery :
$.ajax({
type: "POST",
url: "emails.php",
data: { user: "John" }
}).done(function( msg ) {
$('teammembers').html(msg);
});
hope this will give you a starting point
Javascript:
var counter = 1;
var limit = 5;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <br><select name='vehicle[]' id = 'vehicle'><option value = ''>Vehicle "+ (counter + 1) +"</option><option value = '.$brand.' '.$name.'>'.$brand.' '.$name.'</option>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
PHP/HTML:
<script type = "text/javascript" src="js/addinput.js"></script>
<form name="form1" method="POST" action="services.php" onsubmit="return valid()">
<br><br><br><center>
<table class="form" border=1>
<tr>
<td class="head" colspan="2" >Select Vehicle:</td>
</tr>
<tr ></tr>
<tr>
<td colspan="2" class="info">
<div id="dynamicInput">
<br><select name = "vehicle[]" id = "vehicle1">
<option value = "">Vehicle 1</option>';
include_once "vehicledbconnect.php";
$queryveh = mysql_query("SELECT * FROM vehicletbl");
while($fetch_2 = mysql_fetch_array($queryveh)) {
$brand = $fetch_2['vehbrand'];
$name = $fetch_2['vehname'];
echo '<option value = "'.$brand.' '.$name.'">'.$brand.' '.$name.'</option>';
}
echo '</select>';
echo '<input type="button" value="Add another vehicle" onClick="addInput(\'dynamicInput\');"></div>';
Hi. Is it possible to insert PHP values in a javascript? I have a program here that if the customer click the submit button (echo '), a new drop-down form will appear. And I want the drop down form to contain all of the values of the query ($queryveh = mysql_query("SELECT * FROM vehicletbl");). In my default drop-down form, all values of the query are shown. Please help me guys. I am desperate for an answer. Javascript is my weakness. Thanks a lot.
edit:
newdiv.innerHTML = " <br><select name='vehicle[]' id = 'vehicle'><option value = ''>Vehicle "+ (counter + 1) +"</option>" + "<?php include 'vehicledbconnect.php'; $queryveh = mysql_query('SELECT * FROM vehicletbl'); while($fetch_2 = mysql_fetch_array($queryveh)) { $brand = $fetch_2['vehbrand']; $name = $fetch_2['vehname']; <option value = '.$brand.' '.$name.'>'.$brand.' '.$name.'</option> }?>";
Can this be the solution? I've tried but it's not working, if this can be the solution, maybe there's only something wrong with my code here.
The only way to retrieve values from a server from javascript is to use AJAX.
Well you can do it without AJAX if you don't mind a page refresh, but I don't think that is what you want.
I would use a jQuery load function. This is the simplest example I can muster up for you.
You will need to download jQuery (http://docs.jquery.com/Downloading_jQuery) and include it in your html header:
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
Then you can make a simple function to call; either as a onclick or onchange depending on your preference.
function reloadDropDown()
{
document.getElementById('dynamicInput').innerHTML = 'Loading ...';
var v_name = document.formname.elementname.value;
$('#dynamicInput').load("dropdownload.php", { vehicle_name : v_name });
}
Let me go through this. dropdownload.php would have your '$queryveh' made drop down code. Javascript basically plonks whatever happens in dropdownload.php on to a div with the id 'dynamicInput' When javascript loads dropdownload.php it sends via POST a variable by the name vehicle_name which you can use as $_POST['vehicle_name'] within dropdownload.php.
So, dropdownload.php may look something like this.
<?php
$queryveh = mysql_query("SELECT * FROM vehicletbl WHERE vehname = '{$_POST['vehicle_name']}'");
// collect the data and put it in to an Array I like to do this so I can check the array to make sure it has something in it if not return an error message but I will skip that for the purpose of this explanation.
while($ucRow = mysql_fetch_array($queryveh, MYSQL_ASSOC)) array_push($resultsArray, $ucRow);
?>
<select name = "vehicle[]" id = "vehicle1">
<?php
foreach ($resultsArray as $fetch_row){
?>
<option value = "<?php echo $fetch_row['vehbrand'].' '.$fetch_row['vehname'].'; ?>"><?php echo $fetch_row['vehbrand'].' '.$fetch_row['vehname']; ?></option>
<?php } ?>
</select>
?>
I'm not entirely certain on the end result you are after but that is a basic jQuery ajax call. If you can grasp that, you are half way to a truly dynamic web page / app with some further practice with this area. Hope that gives you a direction to go in :)
JavaScript gets evaluated on the client ..so like Html ..so it is to be used the same way.
-> yes, you just use php in your javascript as long as its defined to be evaluated by php first (usually within a .php file)
edit:
just to clarify, if you want to get values within javascript from the server by php.. you need to have a look at what danishgoel said: Ajax (Asynchronous JavaScript) ..see - since Rikudo Sennin disrespected the link, another http://en.wikipedia.org/wiki/XMLHttpRequest ..or even better have a look at a javascript framework that does most of the stuff for you (f.e. jQuery)
I have two drop-down boxes. I want to populate second drop-down box on selection in the first drop-down box. My values are retrieving from database. Is this possible without using php or I need intermediate ajax and php file to get values from first drop-down and populate values file. Or this is possible without using php I mean only using Jquery. Please give me hint to do that.
Suppose I have 2 countries. First is INDIA and second is USA. ON first drop-down I am selecting countries and if first dropdown is selected than second dropdown populate its respective states.
if you encode your data into JSON format, then you can do something like this:
for HTML:
<select name='country' id='country'>
<option value='india'>India</option>
<option value='usa'>USA</option>
</select>
<select name='dates' id='dates'>
</select>
jQuery:
data = {
india: ['2011-03-11','2010-02-01'],
usa: ['2006-03-11','2009-02-01']
}
$('#country').change(function(){
var dateopts = ''
$.each(data[$(this).val()],function(i,v){
dateopts += "<option value='"+v+"'>"+v+"</option>"
})
$('#dates').html(dateopts)
})
Which when the country is changed, will build and populate the options for the second select box.
See the working example here: http://jsfiddle.net/xHxcD/
The above method requires all data to be sent to client side with the initial page request. If you have lots of data, it would be better to receive the data via AJAX. It would be simplest to do this by building an object in PHP with the same data structure as your client side, then use json_encode to convert it into as JSON string and echo it out.
Reading this into your client side would then be as simple as this:
$.ajax('myJsonData.php?country=india',function(jsonData){ data.india = jsonData })
You could do it either way. If you dont want to use ajax, just load every single option into an object. Then when you select something from select #1, populate #2 with the assoicated array of data from your object.
If I were doing it, I wouldn't do it with ajax unless there was a TON of data.
Yes you can do it without using php. For that you've to assign two different states list in Javascript array and base on the selection just change the options in the other select box. As simple as that.
You can assign the javascript array using your serverside scripting language while loading the page if you're using database to store the states.
But do not do this unless you've very small amount data. In your case you've only 2 countries so you can go ahead with it.
Lets take an easy example, I'm using this for the same purpose that you want and it works perfectly fine.
This is the country dropdown:
<?php
$countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
echo "<select name='country' id='country' onchange=\"reload(this.form)\" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
while($clist=mysql_fetch_array($countrylist))
{
echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
}
echo "</select>";
?>
This is the region dropdown:
<select name="region" id="region" ></select>
Now make a seperate file named crlist.js and include it in the page having above code like this:
<script type="text/javascript" src="crlist.js"> </script>
code for crlist.js:
var request = false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
#end #*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}
function go() {
if (request.readyState == 4) {
//if (request.status == 200) {
var response = request.responseText;
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
var records=response.split('|');
for (i=1; i<records.length; i++) {
//alert("rcord="+records[i]);
var record=records[i].split('*');
var region=record[0];
//alert("region="+region);
var regionid=record[1];
//alert("regionid="+regionid);
var x=document.createElement('option');
//var y=document.createTextNode(region);
x.text=region;
//x.value=region;
//alert(x.text);
//x.appendChild(y);
//list.appendChild(x);
list.options.add(x);
}
//}
}
}
function initCs(path) {
if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
var country=document.getElementById('country');
country.onchange=function() {
if(this.value!="Select") {
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
//while (list.childNodes[0]) {
//list.removeChild(list.childNodes[0]);
//}
}
fillSelect(this.value,path);
//alert(this.value);
}
//fillSelect(country.value);
}
Now make a seperate file named crlist.php.
Code for crlist.php:
<?php
require_once 'yourconfigfile.php';
$cname = $_GET['country'];
$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
}
?>
Now add following script on the page having dropdowns:
<script type="text/javascript" src="crlist.js"> </script>
<script>
$(document).ready(function() {
initCs("");
});
</script>
This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure.
Reference to my answer: Cascade Dropdown List using jQuery/PHP
Hope this helps.
I am trying to do pagination using javascript but all in vain, please help..
<script language="Javascript">
function nextclicked()
{
document.getElementById("clickednext").value = document.getElementById("clickednext").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$_POST['clickednext']. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
UPDATE :
<div class=d2 align=left>
<a href="#" onclick=" nextclicked(); submit();" >
Next
</a>
UPDATE ENDS......
The first time when i click the Next hyperlink label, then it works, that is, 10 is assigned $_POST['clickednext'] and the next 10 values appear from the database, but the second time i click the label , then it doesn't?
Your code is completely wrong.
You should scrap it and start all over again.
I will show you how to do so.
I have a rule when it comes to Ajax, and it goes like this.
If you cannot do the functionality without Ajax, there's no way you should attempt to do it with Ajax.
If you know anything about javascript, you'll know that XmlHttpRequest makes working with Ajax hellish. Hence why we have javascript frameworks such as JQuery and Mootools. You might also like a php ajax framework called PHPLiveX. I only use JQuery, so here's how to do the solution in JQuery.
Step 1: Strip your ajax and create the solution in php
This pagination tutorial in php will help.
Step 2a: Create the ajax with PHPLiveX
PHPLiveX is really cool and underated, as it allows you to use php functions without reloading the whole page, in a more convienient way, than if you'd used javascript.
PHPLiveX will help you the best.
It's pretty straightforward. You call a php function to do something, return some values, and choose the target: of where you want the values to go.
I personally would use PHPLiveX for this job, as it's better suited. JQuery is more for postdata.
Step 2b: Create the ajax in JQuery
I'm going to assume that you know how to select elements by id with JQuery and append or replaceWith them. If not you can look the function up.
Below is the code required to submit a POST or GET with JQuery. Adapt this to your code. You'll have to modify the code below to add appending and stuff.
$(".tornfieldcard").click(function() {
var dataString = $("#addfieldForm").serialize();
//lets get the form data and use that
var newValue = $("#newValue").val();
var itemid4 = $(this).attr("itemid4");
var dataString = "itemid=" + itemid + "&newValue=" + newValue;
//or get the attr/valu from elements
$("#loading5").show();
$("#loading5").fadeIn(400).html('<img src="icons/loading.gif">');
$.ajax({
type: "POST",
url: "ajaxcontrols.php",
data: dataString,
cache: false,
success: function(html){
$("#loading5").remove();
$(".fieldcardNEW").fadeOut('slow');
$('.fieldcardNEW').remove();
$("#conveyorbelt_"+itemid4+"").append("<div class=\"fieldcard\"><b>"+attribute+"</b> <br><div itemid=\""+itemid4+"\" attribute=\""+attribute+"\">"+value+"</div></div>");
}
});
Here's a little algorithm I wrote using php to create pagination:
$x=$numStories;
$y=$x%5;
$z=($x-$y)/5;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
Where 5 is the number of stories per page, and $numStories is the total amount of stories (or in your case, news articles) you wish to use.
Then, just display the amount of pages ($numPages) in any way you'd like, and your good to go.
[EDIT]
I created an archive.php page, that took a page number as a GET parameter (archive.php?page=3). From there, I selected the first five entries in my database after $pageNum (in this case 3) * 10 (or however many posts per page you are wanting to display.
The best thing to do is make as much of your code dynamic and flexible, so that it is self sustaining.
[EDIT 2]
<script>
function nextclicked()
{
document.forms["newsmanager"].submit();
}
</script>
<?php
$currentPage = $_POST['page'];
$numStories = //get the total amount of entries
$x=$numStories;
$y=$x%10;
$z=($x-$y)/10;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
if(isset($currentPage) && $currentPage>=1)
{
$currentPage = $currentPage +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$currentPage. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
<form>
<input type='hidden' name='page' text='' value='<?php echo "$currentPage"' />
</form>
Next-->
PHP is server-side language. you have to put your php code to
<?php
=====
<script language="Javascript">
function nextclicked()
{
document.getElementById("next").value = document.getElementById("next").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
<?php
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .intval($_POST['clickednext']). ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
additionally, user can't click to hidden form field. you need, for example button and have onclick event ready
<button name="next" value="1" onclick="nextclicked();">Next</button>