I have a PHP project containing textboxes to visualize STACK data structure concept; as seen in the screenshot below:
I am passing PHP values to JavaScript function and adding value only to the index number where there is no value (i.e Top of stack)
Below is the code:
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Data Structure Visualization</title>
<link rel=stylesheet href=StackStyleSheet.css>
<script type="text/javascript">
function addElement($id, $value)
{
var id = $id;
var value = $value;
//correct id and value is passed here.
var textbox = document.getElementById(id);
//this LOC does not execute and returns to the php code
textbox.value = value;
}
</script>
<body>
<?php include 'header.php'; ?>
<form method="POST" action="">
<div id ="container">
<div id="top">
<h3>STACK (ARRAY IMPLEMENTATION)</h3>
</div>
<div id="bottom">
<input id="inputBox" type="text" name="inputNumber" value="">
<button id="pushButton" type="submit" class="button button1" name = "PUSH">Push</button>
<button id="popButton" type="submit" class="button button2" name = "POP">Pop</button>
<button id="clearButton" type="submit" class="button button3" name = "CLEAR">Clear Stack</button>
</div>
<div id="operation">
<input type="text" name="5E" value="" class="operation1 obutton6">
<input type="text" name="4E" value="" class="operation1 obutton5">
<input type="text" name="3E" value="" class="operation1 obutton4">
<input type="text" name="2E" value="" class="operation1 obutton3">
<input type="text" name="1E" value="" class="operation1 obutton2">
<input type="text" name="0E" value="" class="operation1 obutton1">
</div>
</div>
</form>
<?php
include 'footer.php';
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['PUSH']))
{
$val0E = (int)$_POST['0E'];
$val1E = (int)$_POST['1E'];
$val2E = (int)$_POST['2E'];
$val3E = (int)$_POST['3E'];
$val4E = (int)$_POST['4E'];
$val5E = (int)$_POST['5E'];
//creating an associative array to store/add/delete values in the index locations
$elementsindex = array("0E"=>$val0E ,"1E"=>$val1E,"2E"=>$val2E, "3E"=>$val3E, "4E"=>$val4E, "5E"=>$val5E);
foreach ($elementsindex as $key => $value)
{
if(($elementsindex[$key])==null)
{
//value copied from textbox
$id = $key;
$value = $_POST['inputNumber'];
//value pushed in
$elementsindex[$key] = $value; //saves value against element index
//value reflected on screen box
echo '<script type="text/javascript">';
echo 'addElement("'.$id.'", "'.$value.'");';
echo '</script>';
break;
}
else if(($elementsindex[$key])!=null)
{
continue;
}
}
}
}
</body>
</html>
In the foreach loop, if the value at bottom index i.e index = 0E is null/zero, then a new value is added to it, after which we exit from the loop using break;
But, at the JavaScript function addElement(), the following code does not execute and immediately returns and no value is filled in the textbox.
var textbox = document.getElementById(id);
//this LOC does not execute and returns to the php code
textbox.value = value;
Where is the code wrong?
Related
I have an associative array $row[Description, Name, ID_Item]. When a user select "Name" by event onchange into function I want to pass 2 variables $row[Description] and $row[ID_Item].
So, I guess it should be something like:
<form action="/delete.php" method="post">
<select name="NameSelect" id="ID_Select" onchange = "ShowItemInfo('.$row['ID_Item'].', '.$row['Description'].' ,)">
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value = " '.$row['Description'].''.'¶'.''.$row['ID_Item'].' " > '.$row['Name'].' </option>';
}
mysqli_free_result($res);
mysqli_close($conn);
?>
</select>
It doesn't work, so can anybody help? Because due to inability to pass these variables I have to pass them via DOM with separator "¶" but it is obviously a crutch:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Delete your records</title>
</head>
<body>
<h2>
<?php
$conn = mysqli_connect("www.mywebsite.com", "username", "password", "Goods")
or die ('Cannot connect to db');
$query = "select ID_Item, Name,Description from Item";
$res = mysqli_query($conn, $query);
?>
<form action="/delete.php" method="post">
<select name="NameSelect" id="ID_Select" onchange = "ShowItemInfo()">
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value = " '.$row['Description'].''.'¶'.''.$row['ID_Item'].' " > '.$row['Name'].' </option>';
}
mysqli_free_result($res);
mysqli_close($conn);
?>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly >
</form>
</h2>
<script>
function ShowItemInfo() {
var str = document.getElementById("ID_Select").value;
var res = str.split("");
var Id = 0;
var Description = "";
var i = 1;
while (res[i] != "¶") {
Description = Description.concat(res[i]);
i++;
}
for (var j = i+1; j < res.length - 1; j++) {
Id = 10 * Id + parseInt(res[j],10);
}
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
</script>
</body>
</html>
Instead of adding values using separator you can use custom html attributes and set one value inside these attributes . So , your php code for options will look like below :
echo '<option desc=".$row['Description']." value = ".$row['ID_Item']." > '.$row['Name'].' </option>';
Demo Code :
function ShowItemInfo() {
//get selector
var selector = document.getElementById("ID_Select")
var Id = selector.value; //value
var Description = selector.options[selector.selectedIndex].getAttribute("desc"); //custom attribute desc
//set them
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
<select name="NameSelect" id="ID_Select" onchange="ShowItemInfo()">
<option desc="soemthing1" value="1"> sss</option>
<option desc="soemthing2" value="2"> sss2</option>
<option desc="soemthing3" value="3"> sss3</option>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly>
Update 1 :
You can achieve same by passing value whenever onchange event is called .
Demo Code :
function ShowItemInfo(Id, Description) {
//set them
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
<!--pass values as parameter using `this`-->
<select name="NameSelect" id="ID_Select" onchange="ShowItemInfo(this.value,this.options[this.selectedIndex].getAttribute('desc'))">
<option desc="soemthing1" value="1"> sss</option>
<option desc="soemthing2" value="2"> sss2</option>
<option desc="soemthing3" value="3"> sss3</option>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly>
I really can't find a solution anywhere on the web because my problem is a bit unique.
I am made two radio buttons, Division and External. When it is clicked, the Division radio button displays drop down list and the External one displays an input text box.
This is the code I Html made.
<html>
<head>
<title> Submit a Contract </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
function ShowHideDiv() {
var client1 = document.getElementById("client1");
var client2 = document.getElementById("client2");
var division = document.getElementById("division");
var external = document.getElementById("external");
division.style.display = client1.checked ? "block" : "none";
external.style.display = client2.checked ? "block" : "none";
}
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='<input type="text" name="client_details" value="" />';
else document.getElementById('div1').innerHTML='';
}
</script>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<label for = "client1">
<input type="radio" name="client_type" id = "client1" value="Division" onclick="ShowHideDiv()"/> Division
</label>
<label for ="client2">
<input type="radio" name="client_type" id = "client2" value="External" onclick="ShowHideDiv()"/> External
</label>
<br><br>
<div id="division" style="display:none">
Division:
<select name="client_details" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="">Choose Division...</option>
<option value="Distribution">Distribution</option>
<option value="Transmission">Transmission</option>
<option value="Generation">Generation</option>
<option value="Procument">Procument</option>
<option value="Other">Others</option>
</select>
<br><br>
<div id="div1"></div>
</div>
 
<div id="external" style="display:none">
External:
<input type="text" name="client_details" value=""/>
</div>
<br><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
This is the php code.
<?php
require("config.php");
if(isset($_POST['submit']))
{
$client_type = isset($_POST ['client_type']) ? $_POST['client_type'] :null;
$client_details = isset($_POST ['client_details']) ? $_POST['client_details'] :null;
$sql = "SELECT * FROM contracts";
$query = "INSERT INTO contracts
(
`client_type`,
`client_details`) VALUES (
'$client_type',
'$client_details')" ;
if ($con->query($query) === TRUE)
{
echo "<br><br> New record created successfully";
echo $query;
}
else {
echo "Error: " . $query . "<br>" . $con->error;
}
$con->close();
}
?>
The external radio button and the input text box is working fine as both of the value successfully inserted in the database.
But for the division, it inserts only the value Division.
What is it that I do wrong?
Try this :
I have put the condition for type in the start of the code and change the name of the dropdown.
your php code
<?php
require("config.php");
if(isset($_POST['submit']))
{
echo $client_type = isset($_POST ['client_type']) ? $_POST['client_type'] :null;
if($client_type == 'Division'){
$client_details = isset($_POST ['client_details1']) ? $_POST['client_details1'] :null;
}
else{
$client_details = isset($_POST ['client_details']) ? $_POST['client_details'] :null;
}
echo $query = "INSERT INTO contracts
(
`client_type`,
`client_details`) VALUES (
'$client_type',
'$client_details')" ;
if ($con->query($query) === TRUE)
{
echo "<br><br> New record created successfully";
echo $query;
}
else {
echo "Error: " . $query . "<br>" . $con->error;
}
$con->close();
}
?>
Your HTML code
<html>
<head>
<title> Submit a Contract </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
function ShowHideDiv() {
var client1 = document.getElementById("client1");
var client2 = document.getElementById("client2");
var division = document.getElementById("division");
var external = document.getElementById("external");
division.style.display = client1.checked ? "block" : "none";
external.style.display = client2.checked ? "block" : "none";
}
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='<input type="text" name="client_details" value="" />';
else document.getElementById('div1').innerHTML='';
}
</script>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<label for = "client1">
<input type="radio" name="client_type" id = "client1" value="Division" onclick="ShowHideDiv()"/> Division
</label>
<label for ="client2">
<input type="radio" name="client_type" id = "client2" value="External" onclick="ShowHideDiv()"/> External
</label>
<br><br>
<div id="division" style="display:none">
Division:
<select name="client_details1" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="">Choose Division...</option>
<option value="Distribution">Distribution</option>
<option value="Transmission">Transmission</option>
<option value="Generation">Generation</option>
<option value="Procument">Procument</option>
<option value="Other">Others</option>
</select>
<br><br>
<div id="div1"></div>
</div>
 
<div id="external" style="display:none">
External:
<input type="text" name="client_details" value=""/>
</div>
<br><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
Version by prakash tank is correct and maybe even better. I post this solution so you know there is also other way to go around and in notes I explained to you what you did wrong.
<html>
<head>
<title> Submit a Contract </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
function ShowHideDiv() {
var client1 = document.getElementById("client1");
var client2 = document.getElementById("client2");
var division = document.getElementById("division");
var external = document.getElementById("external");
division.style.display = client1.checked ? "block" : "none";
external.style.display = client2.checked ? "block" : "none";
}
function showfield(name){
if(name=='Other')document.getElementById('div1').innerHTML='<input type="text" name="client_details" value="" />';
else document.getElementById('div1').innerHTML='';
}
</script>
</head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<label for = "client1">
<input type="radio" name="client_type" id = "client1" value="Division" onclick="ShowHideDiv()"/> Division
</label>
<label for ="client2">
<input type="radio" name="client_type" id = "client2" value="External" onclick="ShowHideDiv()"/> External
</label>
<br><br>
<div id="division" style="display:none">
Division:
<!-- client_details has to be changed to client_detailsDiv as after clicking "submit" data from Division and External were put in to the same variable "client_details" so even if External was empty PHP though that it's suppose to be empty and as long as external
DO NOT MIX TWO TYPES OF FORM TYPES AS ONE VARIABLE = DON'T GIVE THEM THE SAME name - in other words you can't give same name for SELECT and TEXT and so on.-->
<select name="client_detailsDiv" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="">Choose Division...</option>
<option value="Distribution">Distribution</option>
<option value="Transmission">Transmission</option>
<option value="Generation">Generation</option>
<option value="Procument">Procument</option>
<option value="Other">Others</option>
</select>
<br><br>
<div id="div1"></div>
</div>
 
<div id="external" style="display:none">
External:
<!--client_details has to be changed to client_detailsExt for reason described above-->
<input type="text" name="client_detailsExt" value=""/>
</div>
<br><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
<?php
require("config.php");
if(isset($_POST['submit']))
{
$client_type = isset($_POST ['client_type']) ? $_POST['client_type'] :null;
/*
$client_details = isset($_POST ['client_details']) ? $_POST['client_details'] :null;
above functions was wrong as I already explained it got $_POST['client_type'] for the External - PHP works the way that it gets variable from the first $_POST['same_name'] and then from second $_POST['same_name'] and then overwrites value of first $_POST['same_name'] and for this reason it displayed only value for External and none for Division as when user set External, Division was empty. So if you would switch form for External as first and put form for Division as second then you wouldn't get variable from External but from Division.
$client_details = isset($_POST ['client_details']) ? $_POST['client_details'] :null;
so what we need to do is to to put this code:
*/
if(!empty($_POST['client_detailsDiv'])) {$client_details = $_POST['client_detailsDiv'] ? $_POST['client_detailsDiv'] :null;}
else {$client_details = $_POST['client_detailsExt'] ? $_POST['client_detailsExt'] :null;}
// at fist we make sure that client_detailsDiv is not empty, if it's not than we set client_detailsDiv as $client_details. But if it's empty we use else statement to
$sql = "SELECT * FROM contracts";
$query = "INSERT INTO contracts
(
`client_type`,
`client_details`) VALUES (
'$client_type',
'$client_details')" ;
if ($con->query($query) === TRUE)
{
echo "<br><br> New record created successfully";
echo $query;
}
else {
echo "Error: " . $query . "<br>" . $con->error;
}
$con->close();
}
?>
Below is the HTML/PHP code, in which i need to validate any of the checkbox out of 5 before submit the Form.
function checkAddress(checkbox)
{
if (checkbox.checked)
{
document.frmUser.action = "edit_user.php";
document.frmUser.submit();
}
else {alert("checkbox");}
}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Details Form</title>
<script language="javascript" type="text/javascript">
function checkAddress(checkbox)
{
if (checkbox.checked)
{
document.frmUser.action = "edit_user.php";
document.frmUser.submit();
}
else {alert("checkbox");}
}
</script>
</head>
<body>
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php
i=0;
while(i=5){
?>
<input type="checkbox" name="users[]" value="<?php echo i; ?>" >
<input type="button" name="update" class="button" value="Update" onClick="checkAddress(this);" />
<?php
$i++;}
?>
</form></div></body></html>
I think you are trying to do this
function checkAddress(checkbox) {
if (checkbox.checked) {
document.frmUser.action = "edit_user.php";
//document.frmUser.submit();
} else {
document.frmUser.action = "#";
alert("checkbox");
}
}
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php $i=0; while($i<=5){ ?>
<input type="checkbox" name="users[]" onClick="checkAddress(this);" value="<?php echo $i; ?>">
<?php $i++;} ?>
<input type="submit" name="update" class="button" value="Update" />
</form>
</div>
Some errors in your code
you have not used $ while denoting the variable i
you are taking the button inside the while loop so it also repeating with the checkboxes.
You are calling onClick="checkAddress(this);" from your button, so this refers to the button and not a checkbox, so then in your function checkbox.checked is testing if the button is checked - which obviously it never will be.
To test whether at least one checkbox is checked you could loop through them testing them in turn, but you can also do it in one step as follows:
if (document.querySelector('form[name="frmUser"] input[name="users[]"]:checked')) {
// at least one is checked
}
The .querySelector() method returns the first matching element (which is a truthy value for use in an if test), or returns null if no matching elements are found (which is a falsey value for use in an if test).
(If the page has only one form with one group of checkboxes then you could simplify the selector to something like .querySelector(':checked'), but I think it is better to be explicit about which items you're testing.)
In context:
function checkAddress()
{
if (document.querySelector('form[name="frmUser"] input[name="users[]"]:checked')) {
alert("Success! (form would be submitted here)");
//document.frmUser.action = "edit_user.php";
//document.frmUser.submit();
} else {
alert("You must select at least one checkbox");
}
}
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<input type="checkbox" name="users[]" value="1" >
<input type="checkbox" name="users[]" value="2" >
<input type="checkbox" name="users[]" value="3" >
<input type="checkbox" name="users[]" value="4" >
<input type="checkbox" name="users[]" value="5" >
<input type="button" name="update" class="button" value="Update" onClick="checkAddress();" />
</form>
</div>
There was another problem with the code posted - the variable i wasn't correctly defined ~ it should have been $i
Rather than assigning the function directly to the button you can create an event listener like this.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Details Form</title>
<script language="javascript" type="text/javascript">
function validate(e){
var form=e.target.parentNode;
var col=form.querySelectorAll('input[type="checkbox"]');
var checked=[];
if( col )for( var n in col )if( col[n].nodeType==1 ){
if( col[n].checked ) checked.push( col[n].name );
}
if( checked.length > 0 ){
form.action='edit_user.php';
form.submit();
} else {
alert('You MUST tick at least one checkbox');
}
}
function bindEvents(){
var bttn=document.forms['frmUser'].querySelectorAll('input[type="button"]')[0];
bttn.addEventListener( 'click', validate, false );
}
document.addEventListener('DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php
$i=0;
while( $i <= 5 ){
echo "<input type='checkbox' name='users[]' value='{$i}' >";
$i++;
}
echo "<input type='button' name='update' class='button' value='Update' />";
?>
</form>
</div>
</body>
</html>
<html>
<head>
<script language="javascript" type="text/javascript">
function checkAddress()
{
if (document.querySelector('form[name="frmUser"] input[type="checkbox"]:checked')) {
alert("Success! (form would be submitted here)");
//document.frmUser.action = "edit_user.php";
//document.frmUser.submit();
} else {
alert("You must select at least one checkbox");
}
}
</script>
</head>
<body>
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<?php
$i=0;
while($i<=5){
?>
<input type="checkbox" name="users[]" value="<?php echo $i; ?>" >
<input type="button" name="update" class="button" value="Update" onClick="checkAddress(this);" />
<?php
$i++;}
?>
</form></div></body></html>
I've been having a problem calling a function declared in an external .js file.
I've made an include of the .js file in the main page, but apparently it works in part (Just one function it is called correctly, the others generate an "Uncaught ReferenceError: function is not defined ")
Here's the Js file:`
<script type="text/javascript">
var maxAmount = 170;
// Modify the counter textField by given the textField to control and his counter
function textCounter(id_Tf, id_Cd) {
// Method that is called succesfully
var element = document.getElementById(id_Tf);
var nameLenght = element.value.length;
var countDisplay = document.getElementById(id_Cd);
if(nameLenght <= maxAmount){
countDisplay.value = maxAmount - nameLenght;
}
else{
countDisplay.value = "0";
}
function titleShow(){
theTitle = val('title').replace(/^\s+|\s+$/g,"");
get('out_title').innerHTML = theTitle;
if(get('check_bold').checked == true){
highlightTerms('out_title');
}
}
function snippetShow(){
console.log("I've entered here");
theSnippet = val('description').replace(/^\s+|\s+$/g,"");
if(theSnippet.length + dateLength <= 156){
get('out_snippet').innerHTML = theSnippet;}
else{
var snipLimit = 153 - dateLength;
snippetSpace = theSnippet.lastIndexOf(" ",snipLimit);
get('out_snippet').innerHTML = theSnippet.substring(0,snippetSpace).concat(ellipsis.bold());}
}
function urlFunction(){
var theURL = val('in_url');
theURL = theURL.replace('http://','');
theURL = theURL.replace(/^\s+|\s+$/g,"");
get('out_url').innerHTML = theURL;
if(get('check_bold').checked == true){
highlightURL();}}
And here's the Main page: '
<?php
include('Code/Php_code.php');
include('Code/Js_code.js');
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<form action="Database_Interface.php" method="post"><br>
Title:<br>
<input type="text" id="title" name="title" size="150" maxlength="150" value="<?php echo $title ?>" onKeyUp='textCounter("title","countDisplay");'><br>
<input readonly type="text" id="countDisplay" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
Description:<br>
<input type="text" id="description" name="description" size="150" value="<?php echo $tags['description'] ?>" onKeyUp='textCounter("description","countDisplay2");'><br>
<input readonly type="text" id="countDisplay2" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
Keywords:<br>
<input type="text" id="keywords" name="keywords" size="150" value="<?php echo $tags['keywords'] ?>" onKeyUp='textCounter("keywords","countDisplay3");'><br>
<input readonly type="text" id="countDisplay3" size="3" maxlength="3" value="150"> Characters Remaining
<br><br>
<input type="submit" value="Carica sul database">
<input type="button" value="see" onclick='snippetShow();'>
</form><br>
<div style="background-color:#f2f2f2; border:1px solid; border-color: black; position:relative;">
<h3><span id="out_title"></span></h3>
<div>
<cite><span id="out_url" ><?php echo $site ?></span></cite>
</div>
<div>
<span id="out_snippet">sdsdsdfvbfbf</span>
</div>
</div>
The answer is: why just the first method is called successfully while the other two generate an error?
Your first function seems to lack a closing } bracket. The last bracket is from the else block. Fixed:
function textCounter(id_Tf, id_Cd) {
// Method that is called succesfully
var element = document.getElementById(id_Tf);
var nameLenght = element.value.length;
var countDisplay = document.getElementById(id_Cd);
if(nameLenght <= maxAmount) {
countDisplay.value = maxAmount - nameLenght;
}
else {
countDisplay.value = "0";
}
}
First of all close <script> tage at end of your js.php file byv </script>
Do not include js file before <doctype> tag.
include it in <head> tag OR before </body>
I want to pass values to a PHP script so i am using AJAX to pass those and that part works. But in the same function I want retrieve those values that I passed to the PHP script. The problem is I cannot retrieve any value from the PHP file. I have search high and low, but now come to you for answers. How can I store the variable passed on to the PHP script so that my ajax can retrieve it? My code is as follows:
This is my form :
<!-- file album.php -->
<html>
<head>
<?PHP
include ("conection/connect.php");
?>
<script type="text/javascript" src="jstbl/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function cekjumlah(tableID)
{
var hitung=document.getElementById(tableID).rows.length;
var jumlah = hitung-1;
document.getElementById("media").value=jumlah;
}
</script>
</head>
<title></title>
<body>
<form name="form1" id="form1" method="post">
Jumlah Inputan :
<input type="text" id="media" name="media" size="5">
<input type="text" id="data_barang" name="data_barang" size="60" onKeyPress="onEnterPenjualan(event);">
<br><br>
<table id="tabelimei" border="1">
<tr id="Last">
</tr>
</table>
<br><br>
<div id="menu">
<p>
<input type="submit" name="simpan" value="Simpan" onClick="cekjumlah('tabelimei')">
<input onClick="deleteRow('DivTambah')" name="button" type="submit" value="Hapus" />
</p>
<p id="hasil">hasil</p>
</div>
</form>
</body>
</html>
And this is my jquery :
function onEnterPenjualan(e){// => Digunakan untuk membaca karakter enter
var key=e.keyCode || e.which;
if(key==13){// => Karakter enter dikenali sebagai angka 13
$(function(){
var data_barang = $("#data_barang").val();
$.ajax({
url: "ambildatabarang.php",
data: "data_barang="+data_barang,
cache: false,
success: function(data){
console.log(data);
alert(data);
}
});
var nama = alert (data.$nama);
var baris = document.getElementById("data_barang").value;
var i = 1;
var row = $(document.createElement('tr')).attr("id", 'DivTambah' + i);
row = '<tr>'+
'<td>1</td>'+
'<td><input name="cek[0]" id="cek" type="checkbox" size="10" /></td>'+
'<td><input name="qty_penjualan[0]" type="text" id="qty_penjualan" value="1" size="10" required/></td>'+
'<td><input type="text" name="imei_penjualan[0]" id="imei_penjualan" size="60" value="'+baris+'" required/></td>'+
'<td><input type="text" name="nama_penjualan[0]" id="nama_penjualan" size="30" value = "'+nama+'"required/></td>'+
'<td><input type="text" name="hargajual_penjualan[0]" id="hargajual_penjualan" value="300000" size="15" required/></td>'+
'<td><input type="text" name="diskon_penjualan[0]" id="diskon_penjualan" size="15" value="0"/></td>'+
'<td><input type="text" name="total_penjualan[0]" id="total_penjualan" size="15" value="300000" required/></td>'+
'<td><button type="button" class="del">Del</button></td>'+
'</tr>';
$(row).insertBefore("#Last");
var hapus = "";
document.getElementById('data_barang').value=hapus;
document.getElementById('data_barang').value.focus();
i++;
});
$(".del").live('click', function(){
$(this).parent().parent().remove();
});
}}
And this is my PHP file :
<?php
if (isset($_GET['data_barang'])){
// Instructions if $_POST['value'] exist
include ("conection/koneksidb.php");
$databarang = $_GET['data_barang'];
$datalengkapbarang = mysql_query("SELECT i.id_imeibarang, jb.nama_jenisbarang, b.type_barang, b.hargajual_barang FROM jenisbarang jb, barang b, imeibarang i WHERE i.id_imeibarang='$databarang' and i.idbarang_imeibarang=b.id_barang and b.idjenis_barang=jb.id_jenisbarang");
$angka = 1;
while($k = mysql_fetch_array($datalengkapbarang)){
echo $no[$angka] = $angka;
echo $imei[$angka]=$k['id_imeibarang'];
echo $nama[$angka]=$k['nama_jenisbarang'].$k['type_barang'];
echo $harga[$angka]=$k['hargajual_barang'];
$angka = $angka+1;
}
}
?>
to send the some data to php and get the result of the php file to javascript synchronously, this is what you need
function sendData (data1,data2)
{
if (window.XMLHttpRequest)
AJAX=new XMLHttpRequest();
else
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX)
{
AJAX.open("POST", "url.php", false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.send("data1=" + data1 + "&data2=" + data2);
return AJAX.responseText;
}
else
return null;
}
now, on your php file, you just get your data like this
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
once you work with the data in your php file, and then you echo the result, it is returned by the javascript function, so you just need to use it like this in your javascript file
var data_from_php = sendData(data1,data2);