Am trying to dynamically add the fields for subjects and the grades obtained, but am getting an error "Undefined index: subject in..." when posting those variables using java script.
Could there be something am missing with my posting mechanism. Notice that in the form data am not puting id="subject" to avoid picking the id for only one subject, and am using name="subject[]" to show an array, but I
dont seem to know how to represent this in the java script as we will see below.
form data as follows;
<tr>
<td colspan="6"><div align="center"><strong>
<p style="color:#930">Academic Qualification</p>
</strong></div></td>
</tr>
<?php
require_once("connection/connectPDO.php");
$sql="CALL sp_getSubjects()";
//Initiate and Call Stored Procedure Using PDO
$pdo = new PDOConfig();
$resultsSubject = $pdo->query($sql);
foreach($resultsSubject as $rowSubject)
{
?>
<tr>
<td width="35%" colspan="3"><div align="right"><?php echo $rowSubject['SubjectName']; ?>:<input name="subject[]" type="hidden" value="<?php echo $rowSubject['SubjectID']; ?>" /></div></td>
<td width="65%" colspan="3"><select name="grades[]" id="grades" class="validate[required]">
<option value="">--Select Grade--</option>
<?php
$sql="CALL sp_grabGrades()";
//Initiate and Call Stored Procedure Using PDO
$pdo = new PDOConfig();
$resultset = $pdo->query($sql);
foreach($resultset as $row)
{
?>
<option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
<?php } ?>
</select></td>
<?php } ?>
</tr>
the form looks like this
Academic Qualification
English <--select-->
Biology <--select-->
Science <--select-->
the java script code is as follows;
$(document).ready(function(){
$("#submit").click(function(){
//if invalid do nothing
if(!$("#formD").validationEngine('validate')){
return false;
}
var vgrades = $("#grades").val();
var vsubject = $("#subject").val();
$.post("sendInitialApplication.php",
{
grades : vgrades,
subject : vsubject
/*Handles response from server*/
function(response){
alert(response);
});
alert("You are here");
});
});
the PHP code "sendInitialApplication.php" is as follows
<?php
$method = $_SERVER['REQUEST_METHOD'];
function connect(){
try{
$dbConn = new PDO('mysql:host=localhost; dbname=student', 'root', 'root');
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConn;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
/*Checks if method is HTTP POST*/
if(strtolower($method) == 'post'){
$grades = addslashes($_POST['grades']);
$subjects = addslashes($_POST['subject']);
try {
$dbHandler = connect();
$dbHandler->beginTransaction();
//Saving Various subjects with distinct grade obtained
foreach($subjects as $key => $subject)
{
$setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
$stmt_subject = $dbHandler->prepare($setIndexSubject);
$stmt_subject->bindValue(':vSubjectID', $subject);
$stmt_subject->bindValue(':vGradeObtainedID', $grades[$key]);
$stmt_subject->execute();
$stmt_subject->closeCursor();
}
$dbHandler->commit();
echo "The Operation was Successful!!!!!!";
} catch (PDOException $e) {
$dbHandler->rollback();
die($e->getMessage());
}
}else{
echo "Oops! Make sure Method is POST";
}
?>
I'm expecting that $_POST['subject'] and $_POST['grades'] should be array. Than you cannot use $subjects = addslashes($_POST['subjects']), but $subjects = $_POST['subjects']. Calling addslashes on array throws PHP warning and returns NULL.
Edit:
I suggest modify logic of your code.
Input type hidden, with subject id, will not work, as you expects. Modify your list:
// ... obtaining subjects from db ...
foreach($resultsSubject as $rowSubject) {
?>
<tr>
<td>
<select name="grade[<?= $rowSubject['SubjectID']; ?>]">
<option value="">--Select Grade--</option>
<?php
// ... obtaining grades from db ...
foreach($resultset as $row) {
?>
<option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
<?php
}
?>
</select>
</td>
</tr>
<?php
}
Than serialized form should return array:
grade = array (
subjectID1 => selectedGradeId,
subjectID2 => selectedGradeId,
...
)
And data processing in sendInitialApplication.php:
// prepare db transaction
$grades = $_POST['grade'];
foreach ($grades as $subject => $grade) {
$setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
$stmt_subject = $dbHandler->prepare($setIndexSubject);
$stmt_subject->bindValue(':vSubjectID', $subject);
$stmt_subject->bindValue(':vGradeObtainedID', $grade);
$stmt_subject->execute();
$stmt_subject->closeCursor();
}
// close db transaction
Related
I have a php file that shows all the user details in table form. On click of edit, I am want to set something from DB to local storage using javascript.
So to show a table of users I am doing the following:
<table cellspacing="0">
<tr>
<th>ID</th>
<th>Name</th>
<th>View</th>
<th>Edit</th>
</tr>
<?php
$count=1;
$sel_query="Select * from user_details ORDER BY id desc;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td align="center"><?php echo $count; ?>
<td align="center"><?php echo $row["docname"]; ?>
<td align="center">View</td>
<td align="center">Edit</td>
</tr>
<?php $count++; } ?>
</table>
The above shows the records in the table perfectly.
Now when edit is clicked, I call a javascript function. (This is called before I click on edit? I am not sure why?)
<script type="text/javascript">
function handleLinkClick (e) {
e.preventDefault ();
var id = e.target.href.split ("?").pop ();
var key = <?php echo add(id);?>
console.log(key);
localStorage.setItem ("myKey", key);
//window.location.href = e.target.href;
}
</script>
Now from javascript function, I am trying to call a PHP function a variable is sent from javascript to PHP function to fetch corresponding records details and return that data to javascript, below is the PHP function:
function add($id){
$sel_query="select * from user_details where id=$id";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result))
{
$key = $row["rawText"];
echo $key;
}
return $key;
}
?>
I don't see any results. I am not sure why I am not getting any results? Can some give me the right syntax or correct me?
Thanks!
I am practising AJAX by implementing editable HTML table looking like this:
The logic is this:
User clicks on left column (containing integer);
JS script catches its value and by using AJAX adds them to database;
PHP script fetches this value, makes some calculations, adds them to database and shows result in right column (date in <td>).
Now as expected PHP script needs page refreshing to show calculation result (date in <td>). I'm trying to write JS script which will retrieve calculated data from database and immediately show in HTML table's cell.
Having troubles with it. Asking for help with this issue.
index.php:
<form id="form-wrap" action="functions.php" method="POST">
<select name="select1" required>
<?php
for ($i = 1; $i <= 20; $i++) {
echo "<option>".$i."</option>";
}
?>
</select>
<br>
<input type="text" id="name" name="name">
<input type="date" id="day" name="day">
<input type="submit" name="button_ok" id="button_ok" value="Write">
<input type="submit" name="show" id="show" value="Show table">
</form>
functions.php:
<?php
require_once 'dbconnect.php';
$loged = $_POST["name"];
$day = $_POST["day"];
class Count_Add_Class {
public function CountDays() {
global $day, $loged, $day_remind1, $days_before1;
$currenttime = time();
$days_before1 = $_POST["select1"];
// ... make some calculations with user's input ...
$this->AddDate();
}
public function AddDate() {
global $pdo, $loged, $day, $day_remind1, $days_before1;
if (isset($_POST['button_ok'])) {
// ... insert in database user's inpt and calculation result ...
}
}
}
$obj = new Count_Add_Class();
$obj -> CountDays();
function Count_days_new_data() {
global $pdo, $day, $loged, $day_remind1_updated,
$stmt = $pdo->prepare("SELECT select1 FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$res = $stmt->fetchAll();
foreach ($res as $row) {
$day_remind1_updated = $row['select1'];
}
$day_remind1_updated = $day - ($days_before1_updated * 86400);
$day_remind1_updated = date('Y-m-d', $day_remind1_updated);
}
Count_days_new_data();
function Show() {
global $pdo, $loged, $faq, $day_remind1_updated;
$stmt = $pdo->prepare("SELECT * FROM tablex WHERE name=?");
$stmt->execute([$loged]);
$faq = $stmt->fetchAll();
$s1 = $_POST['editval'];
$id = $_POST['id'];
$stmt2 = $pdo->prepare("UPDATE tablex SET select1=? WHERE
id=?");
$stmt2->execute([$s1, $id]);
$stmt3 = $pdo -> prepare("UPDATE tablex SET day_remind1=?,WHERE
id=?");
$stmt3->execute([$day_remind1_updated, $id]);
require_once 'table.php';
}
Show();
?>
table.php:
<div id="day-data">
<tbody>
<?php
foreach($faq as $key=>$value) {
?>
<tr class="table_row">
<td><?php echo $value['name']; ?></td>
<td aria-label="First" contenteditable="true" onBlur="saveToDatabase(this,'select1','<?php echo $faq[$key]["id"];
?>')" onClick="showEdit(this);"><?php echo $faq[$key]["select1"]; ?>
</td>
<td><?php echo $value['day_remind1']; ?></td>
</tr>
<?php
}
?>
edit.js:
function showEdit(editableObj) {
$(editableObj).css("background","#FFF");
}
function saveToDatabase(editableObj,column,id) {
$(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat
right");
$.ajax({
url: "functions.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
show.js: (inspired by this answer)
$(".tbl tbody").on("click", "tr", function() {
var id = $(this).find("td")[0].text(); // gets the first td of the
clicked tr
var value = $(this).find("td")[1].text()
$.ajax({
url : "table.php",
dataType: "text",
success : function (data) {
$(".day-data").html(data);
},
error: function (data) {
(".tbl").html('No such file found on server');
}
});
});
When user clicks on HTML-table left column it is higligted well; when he changes it, data is addiing to database well. Now when page is refreshed new data is calculated, added to database and shown in HTML-table's right column.
I suppose problem is in show.js. Need some help in correcting this script!
Update1:
Added illustartion of my task's logic:
It is unfortunate, that you have everything in the functions.php file. It doesn't just count the values, it also renders the table. So when you call the function saveToDatabase, the request that you make to functions.php (and i understand it coorectly) already returns the table with the updated data (as argument of the success function). Try removing show.js and changing the success function content in edit.js from this:
$(editableObj).css("background","#FDFDFD");
to this
$(editableObj).css("background","#FDFDFD");
$(".day-data").replaceWith(data);
I'm trying to send two values from a form to another PHP using ajax post method. One value is the value that's already entered in an input box, and the other is a value that is being typed into another input box. It acts like a search box. I tried executing the SQL query in my SQL workbench and it returns the value properly. What am I doing wrong in my code?
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
$("#sbb").html(sbb);
//searchq7();
});
}
This is the input box where I search and get the value from:
<input type="text" name="region" list="state" value="<?php echo $region; ?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" list="sbb" value="<?php echo $suburb; ?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6" >
<option> </option>
</datalist>
This is the search-suburb.php file:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state="'.$st.'" AND `title` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$suburb = $row['title'];
?>
<option value="<?php echo $suburb; ?>"><?php echo $suburb; ?> </option>
<?php
} // while
} // else
} // main if
<input type="text" name="region" list="state" value="<?=(isset($_POST['region'])?$_POST['region']:'');?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" onkeyup="searchq6()" list="sbb" value="<?=(isset($_POST['suburb'])?$_POST['suburb']:'');?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6"></datalist>
Javascript:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
var decode = jQuery.parseJSON(sbb); // parse the json returned array
var str = ""; // initialize a stringbuilder
$.each(decode, function (x, y) {
str+="<option value='" + y.title +"'>";
});
$("#sbb").html(str);
}); // end of post
}// end of searchq6 function
Php:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='{$st}' AND `title` LIKE '%{$searchq}%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
} else{
$data = array();
while($row = mysqli_fetch_array($query))
$data[] = $row;
echo json_encode($data);
}
} // main if
Got the answer from small snippets gathered through the comments
Changed the query to:
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='".$st."' AND `title` LIKE '%".$searchq."%' LIMIT 10")or die("Could not search!");
And the ajax to:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate})
.done(function(sbb) {
$("#sbb").html(sbb);
});
//searchq7();
}
Thanks for all the comments guys
So. I'm making a Forum, and I want to build it with using AngularJS.
First off.
Now, I've set up a connection to my database with:
<?php
session_start();
$db = new mysqli("localhost","root","","uf") or die ("ERROR! With connection!");
function sql($query){
return mysql_query($query);
}
$sql = "SELECT forum_id, forum_name, forum_desc, forum_created FROM forum_tbl";
if($query = $db->prepare($sql)){
$query->bind_result($f_id, $f_name, $f_desc, $f_created);
$query->execute();
$query->store_result();
}else{
echo $db->error;
}
?>
It's separated to 2 files, First being db_connect.php and second core.php
I've made the tables above, they have sample data.
How can I now make the f_id, f_name,.. to JSON encoded data? And use that JSON in my main.js file to use data.forumid?
I have made php to read the data from the database using:
<?php if($query->num_rows !==0):
while($row = $query->fetch()):
?>
<tr>
<td><?= $f_id;?></td>
<td><?= $f_name;?></td>
<td><?= $f_desc;?></td>
<td><?= $f_created;?></td>
</tr>
<?php endwhile; endif; ?>
BUT I do NOT want to read the data like that.
I would love to use ng-repeat.
You should store the rows in an array and then use json_encode() to convert it to json:
$rows = array();
while($row = $query->fetch()) {
$rows[] = $row;
}
echo json_encode($rows);
So.
I did this with....
<a ng-click="setRoute('forum')" href="#/forum/id=<?php echo $f_id;?>" class="list-group-item">Link</a>
And in my html is ofcourse the ng-app="urheilu"
var app = angular.module('urheilu', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/forum/id=:id', {
templateUrl: function(urlattr){
return 'app/components/forums/threadlist.php?id=' + urlattr.id + '';
}
})
});
Thats how I did my dynamic linking.
DONE.
-Kevin
I'm a really beginner in the ajax domain, and I really need help.
In fact I have done a query to receive some data from a database.
Here on the header I have:
<script type="text/javascript">
<?php if(isset($_GET['p']) AND $_GET['p']=='create_dossier') {?>
function writeInDiv(text){
var objet = document.getElementById('code_client');
objet.innerHTML = text;
}
function ajax()
{
var xhr=null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "ajaxclient.php?code_client=<?php echo $_GET['code_client'] ; ?>", false);
xhr.send(null);
writeInDiv(xhr.responseText);
setInterval("ajax()",5000);
}
<?php }?>
</script>
on the page ajaxclient.php I have the following code:
<?php require_once('Connections/localhost.php'); ?><?php mysql_select_db( $database_localhost ); ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<table width="100%" border="0" id="box-table-a">
<tr>
<th scope="col" width="15%">CODE CLIENT</th>
<th scope="col" width="15%">RAISON SOCIALE</th>
<th scope="col" width="55%">ADRESSE </th>
<th scope="col" width="15%">ACTION</th>
</tr>
<?php
$code_client=$_GET["code_client"];
$sql="SELECT * FROM `client` INNER JOIN `adresse_client` ON `client`.`code_client` = `adresse_client`.`code_client` WHERE `client`.`code_client`='".$code_client."'";
if (mysql_errno() <> 0)
{
echo mysql_error(),'<br>',$sql,'<br>';
die();
}
$result=mysql_query($sql);
while($donnees=mysql_fetch_assoc($result))
{?>
<tr>
<td><?php echo $donnees['code_client'] ; ?></td>
<td><?php echo $donnees['raison_sociale'] ; ?></td>
<td><p align="left"> <?php echo $donnees['rue'].'<br>'.$donnees['complement1'].'<br>'.$donnees['complement2'].'<br>'.$donnees['code_postal'].' - '.$donnees['ville'].'<br>'.$donnees['pays'] ; ?></p></td>
<td><a href="index.php?p=create_dossier2&code_client=<?php echo $data['code_client'] ; ?>"><img src="images/001_18.gif" width="24" height="24" /></td>
</tr>
<?php }
?></table>
</body>
</html>
The page called create_dossier.php contain:
<form action="#" method="get"><fieldset>
<legend>CRÉANCIER</legend>
<br />
<label>Raison sociale:</label><input type="hidden" name="p" value="create_dossier" /> <input type="text" name="code_client" onkeypress="form.submit()" /></fieldset><p align="center"><input type="submit" name="enreg" value="Chercher !" /></form>
What I would like is to display the data without sending the page and the thing is that it always send the form before returning any data. For that I do not need ajax.
I really do not know what wrong and how to correct it.
You should returning the result of query as XML or JSON and filling the tables with XML in calling file.
This is an example php.file (Need to convert to PDO)
require("dbinfo.php");
// Get parameters from URL
$code_client=$_GET["code_client"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysql_connect ($host, $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$sql="SELECT * FROM `client` INNER JOIN `adresse_client` ON `client`.`code_client` = `adresse_client`.`code_client` WHERE `client`.`code_client`='".$code_client."'";
if (mysql_errno() <> 0)
{
echo mysql_error(),'<br>',$sql,'<br>';
die();
}
$result=mysql_query($sql);
while($donnees=mysql_fetch_assoc($result))
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("client");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("'code_client'", $row['code_client']);
//$newnode->setAttribute("xxx", $row['xx']); list all other
}
}
echo $dom->saveXML();
?>
in fact, you should prevent form submitting like this:
onclick="return doSomeAction();"
function doSomeAction() {
// create XHR object
// send data
// handle response
return false;
}
doSomeAction() = ajax() in your case
don't forget to return false