How to iterate associative multidimensional array in Javascript/JSON/AJAX with PHP - php

My database results are multidimensional array.
Here is my code in php file.
$course_detail = array();
while($row=mysqli_fetch_assoc($result))
{
//$course_detail[] = $row;
$course_detail[ strtoupper($row['course_name'][0]) ][] = array(
'course_name' => $row['course_name'],
'duration' => $row['duration'],
'c_desc' => $row['c_desc']
);
}
echo json_encode($course_detail);
And here is my Ajax/Javascript/JSON code.
<script type="text/javascript" >
function fetch(val) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("response").innerHTML = "";
var j = JSON.parse(xhttp.responseText);
for (var i = 0; i < j.length; i++)
{
document.getElementById("response").innerHTML = j[i]['name'] + ' ' + j[i]['duration']+ ' ' + j[i]['c_desc'] ;
}
}
}
xhttp.open('get', 'stream-process.php?sname='+val, true);
xhttp.send();
}
This javascript function is called from submit button with ID of hidden element which is generated dynamically.
Here is the code:
<form action="" method="get">
<?php
$db_manager = new db_manager();
$db_manager->DBLogin();
$sql = "select * from streams";
$result=mysqli_query($db_manager->connection,$sql);
$counter = 1;
while($row=mysqli_fetch_array($result))
{ ?>
<input type="hidden" id="stream_name<?php echo $counter ?>" class="stream" name="sname" value="<?php echo $row["scode"]; ?>">
<li class="list-group-item"><input class="form-control" onclick="fetch(document.getElementById('stream_name<?php echo $counter;?>').value)" type="button" id="submit" value="<?php echo $row["name"]; ?>"/></li>
<?php
$counter++;
}
?>
</form>
</div>
<div id="response" class="stream-detail col-sm-8">
hey there......
</div>
when i click on any button, nothing is displaying. It worked correct with Simple multidimensional array. but i want in Associative Multidimensional Array. So that i can treat each field of each row differently.
Thanks in advance.

Related

how to make a button on a form work when clicked in php?

i have code like this
<body>
<form method = "POST">
<label for="">Star </label>
<input type="text" name = "star"></br>
<input type="submit" value= "Submit">
</form>
<?php
$Star = $Add = $Subs = NULL;
$Picture = "<img src = star.png>";
if($_SERVER['REQUEST_METHOD']=="POST"){
if(isset($_POST['star'])){
$Star = $_POST['star'];
for ($i=1; $i <= $Star + 1 ; $i++) {
echo "$Picture"; }
if(isset($_POST['Op'])){
$op = $_POST['Op'];
switch($op){
case 'ADD':
for ($i=1; $i <=$Star + 1 ; $i++) {
echo "$Picture";
}
case 'SUBS':
for ($i=1; $i <=$Star - 1 ; $i++) {
echo "$Picture";
}
}
}
}
?> <form method="POST">
<input type="submit" value="ADD" name = "Op"/>
<input type="submit" value="SUBS" name = "Op"/>
</form>
<?php } ?>
when I run it in the browser, the submit button works fine and displays a star image according to the input, but when the button is added and minus the star image doesn't increase and decrease. for example, if I input the number of 5 stars and I submit the program it works fine, after that when I click the add or subs button, the stars don't increase or decrease. sorry for my english
You have two forms in this code, first of all, combine both of them into a single form it looks way cleaner than this, and follow the below code it will help to achieve your task. ( Read comments in the code. )
<body>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>">
<label for="">Star </label>
<input type="text" name="star"></br>
<input type="submit" value="Submit" name="submit">
<input type="button" value="ADD" onclick="addNSub(this.value)" /> <!-- (this.value) will send the pressed button attribute value to the function -->
<input type="button" value="SUBS" onclick="addNSub(this.value)" />
</form>
<div id="starContainer">
<?php
$Star = $Add = $Subs = NULL;
$Picture = "<img src = 'star.png' class='starPng'>";
if (isset($_POST['submit'])) {
if (isset($_POST['star'])) {
$Star = $_POST['star'];
if (!empty($Star)) {
for ($i = 1; $i <= intval($Star); $i++) {
echo "$Picture";
}
}
}
}
?>
</div>
<script>
function addNSub(btnValue) {
const parentElement = document.getElementById("starContainer"); //get the star parent dive by it's id
const elements = document.querySelectorAll(".starPng"); //get all the star elements by it's class
if (btnValue == "ADD") { //if button value == ADD this code will execute
for (let i = 0; i <= elements.length; i++) {
if (elements.length == i) {
const getChild = elements[0]; //gets the first element (class ="starPng") under "starContainer" div
const cloneElement = getChild.cloneNode(true); // making clone of that element
parentElement.appendChild(cloneElement); //setting the clone to parent element ("starContainer" div)
}
}
} else if (btnValue == "SUBS") { //if button value == SUBS this code will execute
for (let i = 0; i <= elements.length; i++) {
if (elements.length == i) {
parentElement.removeChild(elements[0]); // removes the first HTML element (class ="starPng") under "starContainer" div
}
}
}
}
</script>
</body>

Insert value of single form called multiple times using ajax call to mysql in php

I am trying to insert single form value called multiple times using ajax call to mysql in php with submit all button . I have store all the forms data to localStorage. But when I am trying to insert all the values to mysql one form value is inserting and other form values is taking null value.
**loadquestions1.php**
<form method="post">
<table>
<tr>
<td>
<?php echo "<h5>Question: ".$question_no ."</h5><h5> ".$question_title ."</h5>"; ?>
</td>
</tr>
</table>
<div class="center">
<textarea placeholder="Write your answer here..." class="outer persisted-text" name="pt<?php echo $question_no; ?>" id="persisted-text" onchange="changeBack();" rows="10" cols="100"></textarea>
<span><input type="hidden" name="question_no<?php echo $question_no; ?>" value="<?php echo $question_no; ?>" /></span>
<span><input type="hidden" name="question_title<?php echo $question_no; ?>" value="<?php echo $question_title; ?>" /></span>
</div>
<button class="btn btn-success" name="save">Save</button>
<?php } ?>
</form>
function load_questions1(questionno)
{
document.getElementById("current_que").innerHTML=questionno;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if(xmlhttp.responseText=="over")
{
window.location="result.php";
alert("hello");
}
else
{
document.getElementById("load_questions1").innerHTML=xmlhttp.responseText;
load_total_que();
var supported = '',
unsupported = 'Oh no! Your browser does not support localStorage.';
if (window.localStorage) {
$('.persisted-text').keyup(function () {
localStorage.setItem(this.name+questionno, this.value);
}).val(function () {
return localStorage.getItem(this.name+questionno) || supported
})
} else {
$('.persisted-text').val(unsupported);
}
}
}
};
xmlhttp.open("GET", "forajax/load_questions1.php?questionno="+ questionno, true);
xmlhttp.send(null);
}
**config.php**
if (isset($_POST['save'])) {
$size = sizeof($_POST);
$number = $size/3;
$query = "SELECT * FROM add_question where online_exam_title='$_SESSION[add_exam]'";
$data = mysqli_query($conn, $query);
$count=mysqli_num_rows($data);
for($i=1;$i<$count;$i++) {
$index1 = 'pt'.$i;
$pt[$i] = $_POST[$index1];
$index2 = 'question_no'.$i;
$question_no[$i] = $_POST[$index2];
$index3 = 'question_title'.$i;
$question_title[$i] = $_POST[$index3];
//$question_no = $_POST['question_no'];
$sql="INSERT INTO subjective_answer (placeholder, exam_type, username, question_no, question_title) VALUES ('$pt[$i]', '$_SESSION[add_exam]', '$_SESSION[username]', '$question_no[$i]', '$question_title[$i]')";
$result=mysqli_query($conn,$sql);
}
if($result)
{
echo "record inserted";
}
}

Populate datalist with mysql fields based on input from another field without reloading page

I am trying to set up a datalist tag that uses fields from my database based on the input from the first field on the form.
I am trying to use AJAX to send the value in the first field (Builder) into my PHP file which will run a query to pull all the records based on that value. Then it echos the options into the datalist for all the contactnames available under that Builder.
<form id="newsurveyform" method="post" action="submitnewsurvey.php">
ID: <input type="text" name="ID" readonly value=<?php print $auto_id; ?>>
Builder:<b style="color:red">*</b> <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
<datalist id="builders">
<?php
while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
echo'<option value="'.$builderinforow['Builder'].'">';
}
?>
</datalist>
Contact Name:
<input list="contactnames" name="contactnames" required>
<datalist id="contactnames">
<div id="contactnamesoptions"> </div>
</datalist>
</form>
<!-- AJAX, send builder value to php file-->
<script>
function findcontactnames(str) {
if (str.length==0){
document.getElementById("contactnames").innerHTML = "";
return;}
else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("contactnamesoptions").innerHTML = this.responseText;
}};
xmlhttp.open("POST", "contactnames.php", true)
xmlhttp.send(str);
}
}
</script>
<?php
include 'dbconnector.php';
$buildername = $_POST["Builder"];
$contactnames = $conn->query("SELECT ContactName FROM SurveyLog'.$buildername.'");
while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
echo'<option value="'.$contactnamerow['ContactName'].'">';
}
?>
Once the user enters the builder, they will click the contact name and it should be populated with all the contact names under that builder.
Right now, it is not populating anything into the contact name field.
In index.php
<form id="newsurveyform" method="post" action="submitnewsurvey.php">
ID: <input type="text" name="ID" readonly value=<?php print $auto_id ?? 0; ?>>
Builder:<b style="color:red">*</b> <input list="builders" name="builders" onchange="findcontactnames(this.value)" required>
<datalist id="builders">
<?php
while ($builderinforow = mysqli_fetch_assoc($builderinfo)){
echo'<option value="'.$builderinforow['Builder'].'">';
}
?>
</datalist>
Contact Name:
<input list="contactnames" name="contactnames" required>
<datalist id="contactnames">
<div id="contactnamesoptions"> </div>
</datalist>
</form>
<!-- AJAX, send builder value to php file-->
<script>
function findcontactnames(str) {
if (str.length==0){
document.getElementById("contactnames").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this);
if (this.readyState == 4 && this.status == 200) {
alert('Fired');
document.getElementById("contactnamesoptions").innerHTML = this.responseText;
// document.getElementById("contactnamesoptions").innerHTML = "working";
}
};
xmlhttp.open("POST", "response.php", true)
xmlhttp.send(str);
}
}
</script>
in response.php
<?php echo "test"; ?>
Once you've verified that works, query the database
EDIT:
Now that you've verified that, query the database in response.php
include 'dbconnector.php';
$buildername = $_POST["Builder"];
$contactnames = $conn->query("SELECT ContactName FROM SurveyLog WHERE `columnName` LIKE '.$buildername.' LIMIT 100");
$queryHTML = '';
$result = 0;
while ($contactnamerow = mysqli_fetch_assoc($contactnames)){
$result = 1;
$queryHTML .= '<option value="'.$contactnamerow['ContactName'].'">';
}
if ($result == 1) {
echo $queryHTML;
} else {
echo 'No Builders found';
}
Note: Change the columnName in the query to your real column name

How to make elements of an array appear one at the time after clicking submit button?

I have following code:
<?php
include_once 'init/init.funcs.php';
$pollid=(int) $_GET['pollid'];
$questions = array();
$result = mysql_query('SELECT kysimus FROM kysimused where kysimustik_id="' . $pollid . '"');
while($row = mysql_fetch_assoc($result)) {
$questions[] = $row['kysimus'];
}
$count=count($questions);
$x=0;
while ($x<$count){
echo $questions[$x];
$x+=1;
}
?>
<form method="get">
<input type="submit" value="Submit">
</form>
It takes the questions from the database which have kysimustik_id=poll_id and echos them out. But how could I make it work so questions will appear one at the time and new one appears only after I click "Submit" button?
You can do like the following
<div class="row text-center">
<button type="submit" class="btn btn-lg btn-info">Click Here!</button>
</div>
$(function(){
var values = [
"hi",
"hello",
"nice",
"wonderful"
];
var counter = 0;
$(".btn-lg").on("click", function(){
if(values.length) {
counter = (counter + 1) % values.length;
$('.row.text-center').append(values[counter] + ' ');
}
});
});
In the above example I have used javascript array. you can easily replace it by your php array
<?php
include_once 'init/init.funcs.php';
$pollid=(int) $_GET['pollid'];
if(isset($_POST['QuestionID'])
{
$questionID = $_POST["QuestionID"];
HandleAnswer($pollid,$questionID,$_POST['Answer']);
}
else
{
$questionID = 0;
}
$questions = array();
$result = mysql_query('SELECT kysimus FROM kysimused where kysimustik_id="' . $pollid . '"');
while($row = mysql_fetch_assoc($result)) {
$questions[] = $row['kysimus'];
}
function HandleAnswer(string PollId, string QuestionID, string Answer){
// Implement piece of code that sets the answer in the database,
// I leave this up to you since i have no Idea how your database is structured
}
$questionID++;
$count=count($questions);
if($questionID < $count){
?>
<form method="post" action="mypage?=<?php echo $pollid; ?>">
<?php echo $questions[$questionID]; ?>
<input type="hidden" name="questionID" value="<?php echo $questionID;?>"/>
<input type="text" name="Answer"/>
<input type="submit" value="Submit">
</form>
<?php }else{ ?>
THese were all our questions, thank you for answering!
<?php } ?>
I didn't test the code myself, but I'm pretty sure it works. Note that this is a hightly unsafe way to do this, because you can edit the value of the hidden field with extensions such as firebug.

PHP Multiple form in same page

I'm doing form in php but I have some problem.
First I will have 3 different form in the same page.
What I want is only 1 form appear and then with the answer a second form will appear and so on.
The answer of the form will be display on the same page.
For now my first form work and after get the answer go to the 2nd form but I want to submit the 2nd form the problem appear.
It delete the answer of my first form and don't do anything (everything start like I am in my first form).
I try to find the problem but can't have idea about how to solve it.
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1?
<input type="number" name="nbtemplate" min="1" max="30">
<input type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php
if(!isset($submitbutton1)) {
if (!empty($_POST['nbtemplate']) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for ($i = 1; $i <= $Nnbtemplate; $i++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
if(isset($submitbutton1) && !isset($submitbutton2)) {
if (!empty($_POST['nbtime']) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST['nbtime'];
for ($j = 1; $j <= $nbtime; $j++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time" name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
}
}
?>
That is some gnarly code you got there, brother. This is a really simple task when handled with some javascript. Then you can have a single post to your php. I like using the jQuery framework so here's a couple links I found quickly: this one and this one
Example code in response to comment about building form elements dynamically:
<html>
<head>
<!-- load jquery library -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<form action="toyourpage.php">
How Many?:
<input type="text" name="number" id="number">
<div id="add"></div>
</form>
<!-- javascript go -->
<script type="text/javascript">
$(document).ready(function()
{
$('input#number').keyup(function()
{
var num = $(this).val(); // get num
if(!isNaN(num)) // check if number
{
$('div#add').html(''); // empty
for(i = 1; i <= num; i++) // add
{
$('div#add').append('New Field ' + i + ': <input type="text" name="next_' + i + '" id="next' + i + '"><br>');
}
}
else
{
alert('Valid number required');
}
});
});
</script>
</body>
</html>
I did some changes on Your code, and have tested, it works.
You had any mistakes in your {} brackets and if conditions. Also as I commented I added extract($_POST).
<?php
extract ( $_POST );
if (! isset ( $submitbutton1 ) && !isset($submitbutton2)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1? <input type="number" name="nbtemplate" min="1" max="30"> <input
type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php ;
}
if (isset ( $submitbutton1 )) {
if (! empty ( $_POST ['nbtemplate'] ) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST ['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or
die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for($i = 1; $i <= $Nnbtemplate; $i ++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
}
}
if ( isset ( $submitbutton2 )) {
if (! empty ( $_POST ['nbtime'] ) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST ['nbtime'];
for($j = 1; $j <= $nbtime; $j ++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time"
name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
?>

Categories