My Post methot in my PHP file and AJAX not working - javascript

I have the following problem, I am trying to use JQUERY and AJAX, but when I use the Post method, it does not post to the php file. I get an error undefined array key I know there are many more threads with this question, I've searched them all, watched a lot of tutorials, but nothing helps. The mistake remains. The weirdest thing is when I do a success check to see the value it shows the correct value. My source code is:
SevenTops_Test3.php
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Seven Tops Plovdiv</title>
<link rel="stylesheet" type="text/css" href="Style/mystyle2.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="Script/MyScript2.js"></script>
<script src="jquery-3.6.3.js"></script>
<script src="Raion.js"></script>
<script>
$(document).ready(function () {
$("#Raion").change(function () {
var x = $(this).val();
alert(x),
$.ajax({
url: 'fresh_db_raion3.php',
type: 'POST',
data: { raion : x },
success: function (data) {
alert(x);
// Stuff
},
error: function (data) {
alert("Not Ok");
// Stuff
}
});
});
});
</script>
<script>
$(document).ready(function () {
$("#Query").click(function () {
var x = 5;
alert(x);
$("#lists").load("fresh_db_raion3.php", { raion : x});
});
});
</script>
</head>
<body>
<?php
include 'db_connection_string.php';
include 'fresh_db_raion3.php';
?>
<div id="Top_Button">
<table>
<tr>
<td>
<input type="submit" class="Submit" id="Query" name="query" value="Заявка">
</td>
<td>
<input type="submit" class="Submit" id="Read" value="Преглед" />
</td>
<td>
<input type="submit" class="Submit" id="Delete" value="Изтрий" />
</td>
<td>
<button type="submit" class="Submit" id="Menu">
<img src="Picture/Menu.png" id="Menu_Img" />
</button>
</td>
</tr>
</table>
</div>
<hr />
<div>
<select id="Raion" name="raion" >;
<option selected disabled> Избор</option>
<?php
all_raion();
?>
</select>
</div>
<div id="lists" style="overflow:scroll;">
<?php
db_klient();
?>
</div>
<div id="Down_Control">
<table>
<tr>
<td>
<input type="number" id="number" />
</td>
<td>
<input class="label_down" id="label_down1" value="%" readonly>
</td>
<td>
<input type="checkbox" class="Submit" id="check" />
</td>
<td>
<input type="button" value="Запиши" class="Submit" id="Down_Btn_Insert" />
</td>
<td>
<textarea id="label_down2" readonly>кашон/стек</textarea>
</td>
<td>
<input type="checkbox" class="Submit" id="check1" />
</td>
</tr>
</table>
</div>
</body>
</html>
fresh_db_raion3.php
<?php
include "db_connection_string.php";
$getraion = $_POST['raion'];
echo $getraion;
function all_raion(){
$result_raion = $GLOBALS['db']->query('SELECT * FROM Raion');
$rowas_raion = $result_raion->fetchAll(PDO::FETCH_ASSOC);
foreach ($rowas_raion as $GLOBALS_k => $v)
{
echo '<option value=' . $GLOBALS_k . '>' . $v['Raion_Name'] . '</option>';
}
}
function db_klient(){
print_r( $GLOBALS['getraion']);
echo '<br>';
$result_klient = $GLOBALS['db']->query("SELECT* FROM Klient WHERE Raion_ID=". $GLOBALS['getraion']);
$row_klient = $result_klient->fetchAll(PDO::FETCH_ASSOC);
foreach ($row_klient as $kk => $vv)
{
echo '<input type=radio value=' . $vv['Klient_Name'] . ' name = klient_name>
<label>'. $vv['Klient_Name'] . '</label><br>';
}
}
I know the code must be very lame, but I'm very new..
And the database schema is this:
Raion CREATE TABLE "Raion"("Raion_ID" INTEGER PRIMARY KEY, "Raion_Name" TEXT NOT NULL)
Kategorii CREATE TABLE "Kategorii" ( "Kategorii_ID" INTEGER PRIMARY KEY, "Kategorii_Name" TEXT NOT NULL)
Stoki CREATE TABLE "Stoki" ( "Stoki_ID" INTEGER PRIMARY KEY, "Kategorii_ID" INTEGER NOT NULL, "Stoki_Name" TEXT NOT NULL)
Klient CREATE TABLE "Klient" ("Klient_ID" INTEGER PRIMARY KEY, "Raion_ID" INTEGER NOT NULL, "Klient_Name" TEXT NOT NULL)
youtube tutorials, answers in various topics in here in the forum

Related

HTML how to validate any of checkbox which are in Array before submit

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>

JavaScript uncaught reference error using onclick attribute in input form tag

JavaScript Function
function submitToServer(formObject)
{
if(validateUserName(formObject["userName"]) && validatePassword(formObject["password"]))
{
formObject.submit();
}
}
HTML FORM FIELD
<form method="POST" action="SignIntoPortal">
<table>
<tr>
<td> User Name : </td>
<td>
<input type="text" id="userName" name="userName" onblur="validateUserName(this)">
<span id="userName_help" />
</td>
</tr>
<tr>
<td> Password : </td>
<td>
<input type="password" id="password" name="password" onblur="validatePassword(this)">
<span id="password_help" />
</td>
</tr>
<br>
</table>
<input type="button" name="submitButton" id="submitButton" value="Submit" onclick="submitToServer(this.form);">
</input>
</form>
The above is my code, which validates data and submits the form. but i keep getting
Uncaught ReferenceError: submitToServer is not defined
error, which I am unable to resolve. what could be the reason?
But, when I tried it with different form it worked with different names and fields.
EDIT
the difference between the code that worked and this is that, the former code does not use table it works smooth. Does scope change with table ?
You can find the code here CODE FIDDLE
You can get .html file here
SignIn.html
<html>
<head>
<title>Sign into Shopping Zone</title>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-8">
<style>
body
{
font: 14px verdana;
}
h1
{
font: arial-black;
color: blue;
}
</style>
<script type="javascript" language="text/javascript">
function submitToServer(formObject)
{
if(validateUserName(formObject["userName"]) && validatePassword(formObject["password"]))
{
formObject.submit();
}
}
function validateUserName(inputField)
{
if(inputField.value.length == 0)
{
document.getElementById("userName_help").innerHTML = "Please enter value";
return false;
}
else
{
document.getElementById("userName_help").innerHTML = "";
return true;
}
}
function validatePassword(inputField)
{
if(inputField.value.length == 0)
{
document.getElementById("password_help").innerHTML = "Please enter value";
return false;
}
else
{
document.getElementById("password_help").innerHTML = "";
return true;
}
}
</script>
</head>
<body>
<h1><b><i>Shopping Zone</i></b></h1>
<p> Kindly Provide Login info
</p>
<!-- SignIn Form Data for Passing to SignIntoPortal-->
<form method="POST" action="SignIntoPortal">
<table>
<tr>
<td> User Name : </td> <td><input type="text" id="userName" name="userName" onblur="validateUserName(this)"><span id="userName_help" /></td>
</tr>
<tr>
<td> Password : </td> <td><input type="password" id="password" name="password" onblur="validatePassword(this)"><span id="password_help" /></td>
</tr>
<br>
</table>
<input type="button" name="submitButton" id="submitButton" value="Submit" onclick="submitToServer(this.form)"></input>
</form>
</body>
</html>
in the script header, your 'type' and 'language' attributes are mixed up. type should be 'text/javascript' and language should be 'javascript' although the language attribute is not required
<script type="text/javascript" language="javascript">

How to insert values from dynamically added rows into database

I've been stuck on this for days. I really appreciate your help.
I'm working on a php form that generates dynamically added rows when
the user click the button ADD.
To save the values into the database, users must click the SUBMIT
button.
The problem that i'm facing is that the database doesn't save the
values from the dynamic rows.
AUTOCOMPLETE & DYNAMIC ROWS
<script>
//autocomplete
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#ItemName" ).autocomplete({
source: "user/requisition_search.php",
minLength: 1,
select: function( event, ui )
{
$('#ItmId').val(ui.item.id);
$('#StkId').val(ui.item.stkId);
$('#ItmNameDis').val(ui.item.value);
$('#ItmUOM').val(ui.item.uom);
$('#ItmQty').val(ui.item.qty);
}
});
});
//dynamic rows
$(document).ready(function(){
$("#add").on("click",function(){
var rowcount = $("#rowcount").val();
var row =
'<tr id="'+rowcount+'"><td>'+$("#ItmId").val()+'</td><td><input readonly="readonly" name="StkId[]" value="'+$("#StkId").val()+'"/></td><td>'+$("#ItemName").val()+'</td><td>'+$("#ItmUOM").val()+'</td><td>'+$("#ItmQty").val()+'</td><td><input readonly="readonly" name="ReqQty[]" value="'+$("#ReqQty").val()+'"/></td></tr>';
rowcount = parseInt(rowcount)+1;
$("#rowcount").val(rowcount);
$("#dataTab").append(row);
$("#dataTab").show();
$("#submit").show();
});
});
</script>
HTML
<form name="jqtest" action="submit.php" method="post">
<label for="ItemName">Search : </label>
<input id="ItemName" size="50"/>
<label for="ItmId">Item Id </label>
<input name="ItmId" id="ItmId" readonly="readonly"/>
<label for="StkId">Stock Id </label></td>
<input name="StkId" id="StkId" readonly="readonly"/>
<label for="ItmNameDis">Item Name </label>
<input name="ItmNameDis" id="ItmNameDis" size="50" readonly="readonly"/></td>
<label for="ItmUOM">Unit Of Measurement </label>
<input name="ItmUOM" id="ItmUOM" readonly="readonly"/>
<td><label for="ItmQty">Quantity Available </label>
<input name="ItmQty" id="ItmQty" readonly="readonly"/>
<label for="ReqQty">Quantity </label>
<input name="ReqQty" id="ReqQty" onkeypress="return numbersOnly(event)" onkeyup="ItmQty_Availability()" disabled="disabled"/>
<p>
<input type="reset" name="reset" id="reset" value="RESET"/>
<input type="button" name="add" id="add" value="ADD"/>
</p>
<input type="hidden" name="rowcount" id="rowcount" value="1"/>
<table id="dataTab" width="90%" style="display:none;" border="1" cellpadding="0" cellspacing="0">
<tr>
<th>Item ID</th>
<th>Stock ID</th>
<th>Item name</th>
<th>UOM</th>
<th>Quantity Available</th>
<th>Quantity Requested</th>
</tr>
</table>
<p> </p>
<p><input style="display:none;" type="submit" name="submit" id="submit" value="SUBMIT"/></p>
</form>
submit.php
<?php
$num = $_POST['rowcount'];
for($i=0;$i<$num;$i++)
{
$strStkId = "";
if(!empty($_POST)){
if(isset($_POST["StkId[]"])){
$strStkId = $_POST["StkId[]"];
}else{
echo "<font color=red>Enter the Stock Id</br></font>";
}
}
$strReqQty = "";
if(!empty($_POST)){
if(isset($_POST["ReqQty[]"])){
$strReqQty = $_POST["ReqQty[]"];
}else{
echo "<font color=red>Enter the Quantity</font>";
}
}
$tsql =
"INSERT INTO REQUISITION
(RequestQuantity, StockId)
VALUES
('$strReqQty','$strStkId')
";
$result = sqlsrv_query($conn, $tsql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if (!$result) {
die ('<script>
window.alert("Please enter the requisition details !")
window.location.href = "requisition.php"; </script>');
}
else
echo '<script>alert("Your Requisition is In Process"); </script>';
sqlsrv_close($conn);
}
?>
UPDATED
I've learnt that name="StkId" and name="StkId[]" clashes in the dynamic rows and the inputs.
So i've change into something like this :
var row = '<tr id="'+rowcount+'"><td>'+$("#ItmId").val()+'</td><td><input readonly="readonly" name="StkId2" value="'+$("#StkId").val()+'"/></td><td>'+$("#ItemName").val()+'</td><td>'+$("#ItmUOM").val()+'</td><td>'+$("#ItmQty").val()+'</td><td><input readonly="readonly" name="ReqQty2" value="'+$("#ReqQty").val()+'"/></td></tr>';
Now the data are inserted into the database but IF the user enters more than one item, only one data is inserted into the database. What did i do wrong? I guess its at the submit.php part but i can't figure out why.
You won't get dynamically generated row values in $_POST on submitting the form because those are not at all form inputs but just displaying as row in a table. But you can achieve your functionality with the help of jQuery AJAX. On clicking the submit button, calls your submit.php using AJAX. The sample solution for how to retrieve values of those dynamically rows is given below. You can adapt this method for your requirement.
Main Page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Dynamic Rows</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#add").on("click",function(){
var rowcount = $("#rowcount").val();
var row = '<tr class="dynamic" id="'+rowcount+'"><td>'+$("#itemid").val()+'</td><td>'+$("#itemname").val()+'</td><td>'+$("#uom").val()+'</td><td>'+$("#quantity").val()+'</td></tr>';
rowcount = parseInt(rowcount)+1;
$("#rowcount").val(rowcount);
$("#dataTab").append(row);
$("#dataTab").show();
$("#submit").show();
});
$("#submit").on("click",function(){
alert("submit");
var jsonObj = [];
i=0;
$("#dataTab tr.dynamic").each(function(){
var td = $(this).find('td');
itemId = td.eq(0).text();
itemName = td.eq(1).text();
uom = td.eq(2).text();
quantity = td.eq(3).text();
jsonObj.push({
itemId: itemId,
itemName: itemName,
uom: uom,
quantity: quantity,
});
});
var dataString = JSON.stringify(jsonObj);
$.ajax({
url: "submit.php",
type: "POST",
data: {json:dataString},
success: function(response){
alert(response);
}
});
});
});
</script>
</head>
<body>
<form name="jqtest" action="#">
Item ID : <input type="text" name="itemid" id="itemid"/><br/><br/>
Item name : <input type="text" name="itemname" id="itemname"/><br/><br/>
UOM : <input type="text" name="uom" id="uom"/><br/><br/>
Quantity : <input type="text" name="quantity" id="quantity"/><br/><br/>
<p> <input type="reset" name="reset" id="reset" value="RESET"/> <input type="button" name="add" id="add" value="ADD"/> </p>
<input type="hidden" name="rowcount" id="rowcount" value="1"/>
</form>
<table id="dataTab" style="display:none;" border="1">
<tr>
<th>Item ID</th>
<th>Item name</th>
<th>UOM</th>
<th>Quantity</th>
</tr>
</table>
<p> <input style="display:none;" type="button" name="submit" id="submit" value="submit"/> </p>
</body>
</html>
submit.php
<?php
$arr = json_decode($_POST['json']);
for($i=0; $i<count($arr); $i++)
{
echo "Row ".$i."\n";
echo "itemId > ".$arr[$i]->itemId.", itemName > ".$arr[$i]->itemName.", uom > ".$arr[$i]->uom.", quantity > ".$arr[$i]->quantity."\n";
}
?>

AJAX onkeyup event trigger in php code

I am a newbie in AJAX script and javascript. I am using AJAX to get search suggestion when the user type the first letter in the search box. But after typing the AJAX and javascript code, I could not get any suggestion coming out below the search box. I wonder if someone could help me to fix this problem?
By the way, I hope that the suggestion limit would be 5. How can I do this?
Code for index.php:
<html>
<head>
<title>
Brandon's Search Engine
</title>
<style type="text/css">
#suggestion {
border: 1px solid black;
visibility: hidden;
}
#suggestion a {
font-size: 12pt;
color: black;
text-decoration: none;
display: block;
width: 450px;
height: auto;
}
#suggestion a:hover {
background-color: #dddddd;
}
</style>
</head>
<script type="text/javascript">
function getSuggestion(q) {
var ajax;
if(window.XMLHttpRequest)//for ie7+, FF, Chrome
ajax = new XMLHttpRequest();//ajax object
else
ajax = new ActiveXObject("Microsoft.XMLHTTP");//for ie6 and previous
ajax.onreadystatechange = function {
if(ajax.status == 200 && ajax.readyState == 4) {
document.getElementById("suggestion").innerHTML = ajax.responseText;
}
}
ajax.open("GET", "suggestion.php?q=$query" + q, false);
ajax.send();
}
</script>
<body>
<form method="GET" action="search.php">
<input type="hidden" name="page" value="0" />
<table align="center">
<tr>
<td>
<h1><center>Brandon's Search Engine</center></h1>
</td>
</tr>
<tr>
<td align="center">
<input type="text" name="q" size="90"
onkeyup="getSuggestion(q)" autocomplete="off" />
</td>
</tr>
<tr>
<td align="center">
<input type="submit" value="Search" />
<input type="reset" value="Clear" />
</td>
</tr>
</table>
</form>
<div id="suggestion" size="90">
</div>
</body>
</html>
Code for suggestion.php:
<?php
include 'connect.php'; //connect with database
$query = $_GET["q"];
if($query != "")
{
$stmt = "SELECT * FROM searchengine WHERE title LIKE '%" . mysqli_real_escape_string($con,$query) . "%' OR link LIKE '%" . mysqli_real_escape_string($con,$query) . "%' LIMIT 0 , 10";
$result = mysqli_query($con,$stmt) or die(mysqli_error($con));
$number_of_result = mysqli_num_rows($result);
if ($number_of_result < 1) {
echo "Your search did not match any documents. Please try different keywords.";
} else {
//results found here and display them
while ($row = mysqli_fetch_assoc($result))//show first 10 results
$title = $row["title"];
$link = $row["link"];
echo "<div id='sugg-search-result'>";
echo "<a href='$link' id='sugg-title'>" . $title . "</a>";
echo "</div>";
}
}
?>
Thanks in advance.
Your missing php delimiter's here.
Change this:
ajax.open("GET", "suggestion.php?q=$query" + q, false);
To:
ajax.open("GET", "suggestion.php?q=<?php echo $query;?>"+q, false);
Updated answer:
In the keyup function, the parameter your passing is incorrect.
<input type="text" name="q" size="90" onkeyup="getSuggestion(q)" autocomplete="off" />
Instead pass the value what has been typed:
<input type="text" name="q" size="90" onkeyup="getSuggestion(this.value)" autocomplete="off" />
Change this:
ajax.open("GET", "suggestion.php?q=$query" + q, false);
To:
ajax.open("GET", "suggestion.php?q="+q, false);
jQuery ajax:
function getSuggestion(q){
$.ajax({
type: "GET",
url: "suggestion.php",
data: {item:q},
success:function(data){
alert(data);
$("#suggestion").html(data);
}
});
}
suggestion.php:
$value = $_GET['item'];
// enter the query here and echo the results
Note: Do not forget to include jQuery library.
Let's start with this:
// some common external JavaScript - learn now - common.js
//<![CDATA[
var doc = document, bod = doc.body;
var IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function E(e){
return doc.getElementById(e);
}
//]]>
// this page external JavaScript - thispage.js
//<![CDATA[
var q = E(q);
function getSuggestion(){
var xhr = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
E('suggestion').innerHTML = xhr.responseText;
}
}
xhr.open('GET', 'suggestion.php?q='+q.value, false);
xhr.send();
}
q.onkeyup = getSuggestion;
//]]>
Now your HTML:
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>
Brandon's Search Engine
</title>
<style type='text/css'>
#import 'external.css';
</style>
</head>
<body class='njs'>
<form method='GET' action='search.php'>
<input type='hidden' name='page' value='0' />
<table align='center'>
<tr>
<td>
<h1><center>Brandon's Search Engine</center></h1>
</td>
</tr>
<tr>
<td align="center">
<input type='text' name='q' id='q' maxlength='90' autocomplete='off' />
</td>
</tr>
<tr>
<td align='center'>
<input type='submit' value='Search' />
<input type='reset' value='Clear' />
</td>
</tr>
</table>
</form>
<div id='suggestion'></div>
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='thispage.js'></script>
</body>
</html>

Button click not working

The following code was working very well. Suddenly, the Edit button click stopped working. When the user used to click Edit button, a JSON code executed. But it is not recognizing the click now. Something happened accidentally? Please assist.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"></meta>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
<script src="js/calendar.js" type="text/javascript"></script>
<link href="js/calendar.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" href="css/wysiwyg.css" type="text/css">
<script type="text/javascript" src="js/wysiwyg.js"></script>
<script type="text/javascript" src="js/wysiwyg-settings.js"></script>
<!-- JSON implementation to get data through JQuery/AJAX -->
<script type="text/javascript">
$(document).ready(function(){
$("#Edit").click(function(){
$.getJSON("fetchvalues.php?UpdateRecordID=" + $.cookie('UpdateRecordID'),
function(data){
//Fill the Form with the data values
document.getElementById('LDate').value = data[0];
document.getElementById('Places').value = data[1];
document.getElementById('Company').value = data[2];
document.getElementById('Designation').value = data[3];
document.getElementById('ProjectDetails').value = data[4];
document.getElementById('DesiredCandidate').value = data[5];
document.getElementById('HRName').value = data[6];
document.getElementById('HRContact').value = data[7];
document.getElementById('Email').value = data[8];
});
});
});
</script>
<title>Job Listing Entry</title>
</head>
<body>
<table id="main" cols="2">
<tr>
<td>
<Form id="frmNewEntry" method="post" action="insert_listing.php">
<table id="tblEntry" cols="3" style="border-color:lightblue; border-style:solid;">
<tr><td colspan="3" bgcolor="lightblue" align="center"><strong>Real-Time Vacancy Entry</strong></td></tr>
<tr><td>Date:</td><td><input id="LDate" name="LDate" type="text" size="20" maxlength="11"/>[Select Date from the Calendar Control]
<script type="text/javascript">
WYSIWYG.attach('all', full);
calendar.set("LDate");
</script></td>
<td>
<table>
<tr>
<td rowspan="6">
<!-- <iframe src="show_db_vacancy_entries.php" height="800px" width="300px" bordercolor="cyan">
</iframe> -->
</td>
</tr>
</table>
</td>
</tr>
<tr><td>Places:</td><td><input id="Places" name="Places" type="text" size="35" maxlength="30" onblur="this.value=MakeInitialCapital(this.value);"></td></tr>
<tr><td>Company:</td><td><input id="Company" name="Company" type="text" size="50" onblur="this.value=MakeInitialCapital(this.value);">
<!-- <input type="button" value="Make Initial Capital" align="left" onclick="this.value=MakeInitialCapital(this.value);"></tr> -->
<tr><td>Designation:</td><td><input id="Designation" name="Designation" type="text" size="50" onblur="this.value=MakeInitialCapital(this.value);"></td></tr>
<tr><td>Project Details:</td><td><textarea id="ProjectDetails" name="ProjectDetails" cols="100" rows="10"></textarea></td></tr>
<tr><td>Desired Candidate:</td><td><textarea id="DesiredCandidate" name="DesiredCandidate" rows="3" cols="100"></textarea> <br></td></tr>
<tr><td>HR Name:</td><td><input id="HRName" name="HRName" type="text" size="50" onblur="this.value=MakeInitialCapital(this.value);"> <br></td></tr>
<tr><td>HR Contact:</td><td><input id="HRContact" name="HRContact" type="text" size="50"> <br></td></tr>
<tr><td>Email:</td><td><input id="Email" name="Email" type="text" size="50"> <br></td></tr>
<tr></tr>
<tr>
<td bgcolor="lightblue">
<input id="Clear" name="Clear" value="Clear" type="button" onclick="ClearFields();">
</td>
<td bgcolor="lightblue">
<input id='Submit' name='Submit' value='Submit' type='submit' />
</td>
</tr>
</table>
</Form>
</td>
<td>
<table id="list" cols="2" style="border:none">
<tr>
<td colspan="2" style="border:none">
<iframe src="show_db_vacancy_entries.php" height="600px" style="border:none;">
</iframe>
</td>
</tr>
<tr>
<td align="left">
<input id="Edit" name="Edit" value="Edit Record" type="button" />
</td>
<td align="right">
<input id="Delete" name="Delete" value="Delete" type="button" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<script language="JavaScript" type="text/javascript">
function MakeInitialCapital(str)
{
return str.toLowerCase().replace(/\b[a-z]/g, cnvrt);
function cnvrt() {
return arguments[0].toUpperCase();
}
}
//Convert initials to capital in a certain control
function MakeInitialCapitalControl(controlName)
{
var ctrl = document.getElementById(controlName).value;
if(/^[A-Z]/.test(ctrl.value)) {
ctrl.value = ctrl.value.toLowerCase();
return;
}
/* ctrl.value = ctrl.value.toLowerCase().replace(/\b[a-z]/g, function {
return arguments[0].toUpperCase();
});*/
}
function ClearFields()
{
document.getElementById('Email').value = "";
document.getElementById('HRContact').value = "";
document.getElementById('HRName').value = "";
document.getElementById('DesiredCandidate').value = "";
document.getElementById('ProjectDetails').value = "";
document.getElementById('Designation').value = "";
document.getElementById('Company').value = "";
document.getElementById('Places').value = "";
document.getElementById('LDate').value = "";
}
</script>
I've tested the code, after removing all the external JS and CSS files, and it seems to work fine.
The problem is most likely with the JSON data that you are getting back. Perhaps you did something to the PHP file it is calling, so that the JSON object is malformed, or there is a PHP warning being printed. (Could be a result of a change in the PHP configuration, too)
I would suggest that you try using the page in Firefox with the Firebug addon active (or something equivalent). It will show you exactly what the JSON request is returning, and whether there are any errors with the request.
As Atli said, the code looks fine. Im curious about this $.cookie('UpdateRecordID'), being part of the querystring. What happens if the cookie is not set?
Can you verify a proper response via firebug?

Categories

Resources