How to insert PHP values into Javascript? - php

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)

Related

How to send the values of the query variables into php variable for inserting into database? [duplicate]

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.

MySQL Query Within JavaScript

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 :)

Get selected select value from a listbox with mysql data to open another listbox and fetch mysql data using this value

Im starting in javascript so, I need to do this : From a list box(already has mysql data using php) I want to get the current selection id (select,selected I think in Java) and fill a listbox with data using the id of the first listbox.But this must happens on onChange property of the listbox1 but on selection.
Here is what I have so far
Html code
Select a Region
$result_disp = mysql_query($query_disp, $cn);
$res=mysql_select_db("xxxx",$cn) or die("Note: " . mysql_error());
$res=mysql_query("select Region_ID, Region_Description from regions");
while($query_data = mysql_fetch_array($res))
{
?>
<option value="<? echo $query_data["Region_ID"]; ?>"
<?php if ($query_data["Region_ID"]==$_post['Region_ID']) ?>>
<? echo $query_data["Region_Description"]; ?></option>
<? } ?>
<select name="Dep" id="Items">
<option>Département</option>
</select>
javascript
function setSelect(id,value) {
var sel = document.getElementById(id);
var option, options = sel.options;
var i = options.length;
while (i--) {
option = options[i];
option.selected = (option.value == value)? true : false;
}
}
thanks in advance!
If you want to manipulate and query the DOM, use the great javascript library jQuery.
Once you have jQuery downloaded and included in your page, you can then do things like this:
<select id='myFirstSelect'>
<option value="1"/>
<option value="2"/>
</select>
javascript: (Bind a function to the 'changed'-event)
$('#myFirstSelect').changed(function(){
var selectedValue = $(this).val();
//do something with selectedValue, e.g. $('#someOtherSelect').val(selectedValue);
});
I haven't tested this code, it's just to give you an idea how much faster and more elegant you get ahead, once you get into jQuery (keywords: Selectors and Events)

Populate input with database data on select change

I'm an absolute beginner in the HTML/Php/JavaScript world. I'm trying to make this page:
dropdown list with titles of documents
when something is selected, populate input fields below with data from PostgreSQL to allow for update
submit button to update database with corrected values from user.
1 and 3 are ok (already tried this with an insert-only form).
My code looks like this (simplified, without dbconn):
echo "<select name='listedoc' size=1>";
while ($ligne = pg_fetch_array($result, null, PGSQL_ASSOC))
{
echo '<option value="'.$ligne['id_doc'].'">'.$ligne['doc_titre']. '</option>';
}
echo "</select>";
The input fields (simplified, there are 4 fields actually):
<p><form name="saisiedoc" method="post" action="docupdins.php"></p>
<table border=0>
<tr><td>Texte</td>
<?php
echo '<td> <textarea name="content" cols="100" rows="30"></textarea> </td>';
?>
</tr><tr>
<td colspan=2>
<input type=submit value="Valider la saisie" name="maj"> </td>
</tr>
</table>
</form>'
Then JQuery script :
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
});
});
</script>
The php to select fields (docsel.php):
<?php
include('../scripts/pgconnect.php');
$iddoc = $_POST['id'];
$sql="SELECT * FROM document where id_doc = $iddoc";
$result = pg_query($db, $sql);
if (!$result) {
echo "ERREUR<br>\n";
exit;}
$row = pg_fetch_row($result);
$doctyp = $row[1];
$doctitre = $row[2];
$docauteur = $row[3];
$doccontent =$row[4];
pg_free_result($result);
pg_close($db);
}
?>
Whatever I do, I can't get back values. I tried value="'.$doctitre'" in the input,
echo $doctitre, to no avail . Is my code logic correct ? Thank you for your help
you are close. the script docsel.php needs to return the data to the html-page.
you have it already setup to receive the data in the callback function
$.post("docsel.php", {id:id},function(data) {
$('textarea[name="content"]').text(data.content);
});
in order to have something in data.content, the php script sends json data:
$result = [];
$result['content'] = $doccontent;
echo json_encode($result);
maybe you need to read the docs on $.post and json_encode... good luck.
There are a couple of things you need to change here.
Firstly, and most importantly your docsel.php script has a gaping security hole. You should never ever ever place unsanitised input e.g. directly from a user, straight into a SQL query because it allows for SQL injection. Essentially, SQL injection allows a malicious user to end the programmers query and submit their own. To get round this you must sanitise any user input - so in this case pass the user input through the function pg_escape_literal() before putting it into your query.
Secondly, your docsel.php script must put out some kind of output for the AJAX request. You can do this by using echo and I would recommend you encode it into JSON. Code example:
$return_vals = array("doctype" => $doctyp, "doctitle" => $doctitre, "docauthor" => $docauteur, "doccontent" => $doccontent);
echo json_encode(array("document" => $return_vals));
Lastly, in your jQuery script, you aren't actually doing anything with the data that is returned from your AJAX post request. Inside the callback function, you need to then add the returned fields to your select dropdown. Code example:
<script>
$(document).ready(function(){
$("select#listedoc").change(function () {
var id = $("select#listedoc option:selected").attr('value');
$.post("docsel.php", {id:id},function(data) {
//FILL THE DROPDOWN HERE
$(data).each(function(elem) {
$("#dropdown-id").append("<option value='" + elem.doctitle + "'>" + elem.doctitle + "</option>");
});
}, "json");
});
</script>
A mute and pedantic point, but when making requests for content then you should be using GET instead of POST.

pagination using javascript in php and mysql

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>

Categories