ajax calling php loop with form not working on first loop only - javascript

I have a page called events.php that lists past and upcoming events, using ajax to call on pastevents.php and upcomingevents.php, which both have forms that collect users' opinions on past events and whether they will attend future events; then a handle sends it to psql db.
Everything works except the first iteration of the looped form does not submit correctly. Instead of continuing onto pastevents-handle.php, it doesn't post and returns a get on events.php; so I see the user's response in the url bar, but it never gets to the db. I made a test page that didn't use ajax by copy-pasting all the code and that works, so it's definitely something to do with ajax, but neither me or my professor could find out what.
I don't know how to use jquery yet, so please answer with plain javascript.
Here's events.php:
<script>
//show past events
function showPastEvents(str) {
document.getElementById('pastevents').style.display = "block";
document.getElementById('hideoldbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("pastevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pastevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "pastevents.php?q="+str, true);
xhttp.send();
}
function hidePastEvents() {
document.getElementById('pastevents').style.display = "none";
document.getElementById('hideoldbutton').style.display = "none";
}
//show upcoming events
function showUpcomingEvents(str) {
document.getElementById('upcomingevents').style.display = "block";
document.getElementById('hidenewbutton').style.display = "block";
var xhttp;
if (str == "") {
document.getElementById("upcomingevents").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("upcomingevents").innerHTML = this.responseText;
}
};
xhttp.open("POST", "upcomingevents.php?q="+str, true);
xhttp.send();
}
function hideUpcomingEvents() {
document.getElementById('upcomingevents').style.display = "none";
document.getElementById('hidenewbutton').style.display = "none";
}
</script>
<!-- page content -->
<div class="content">
<h6>Past events</h6>
<form name="postpastevents" action=""/>
<div id="pastevents"></div>
<input type="button" onClick="hidePastEvents()" id="hideoldbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showPastEvents()" id="showoldbutton" value="Show past"/>
<br>
<br>
<!-- ####### -->
<h6>Upcoming events</h6>
<form name="postupcomingevents" action=""/>
<div id="upcomingevents"></div>
<input type="button" onClick="hideUpcomingEvents()" id="hidenewbutton" value="Hide" style="display:none;"/>
</form>
<input type="button" onClick="showUpcomingEvents()" id="shownewbutton" value="Show upcoming"/>
Here is pastevents.php (it's the same code for upcomingevents.php):
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
$query = "SELECT eventname, eventdate, location, eventdesc FROM events WHERE eventdate < current_date ORDER BY eventdate;";
$result = pg_query($query);
while ( $row = pg_fetch_assoc($result) ) {
$i = 0;
echo "<tr>"; //table row
foreach ($row as $key => $value) {
if ($i == 0) {
$eventname = $value;
}
if ($i == 1) {
$eventdate = $value;
}
$eventinfo = $value;
echo "<td>"; //1 column each loop
echo "$eventinfo";
if ($i == 1) {
echo date(" (l, F jS)", strtotime($eventdate));
}
echo "<br><br>";
echo "</td>";
$i++;
}
echo "<td>";//1 column while same event
?>
<div>
<form name="pasteventsurvey" action="pastevent-handle.php" method="post">
What did you think of the event?
<select name="pasteventopinion">
<option value="">(Choose one)</option>
<option value="good">Loved it!</option>
<option value="okay">Liked it</option>
<option value="bad">Needs improvement</option>
<option value="time">Time conflict</option>
<option value="NA">NA</option>
</select>
<input type="hidden" name="eventname" value="<?php echo $eventname; ?>">
<input type="submit" name="enter" value="Submit"><input type="reset" name="erase" value="Clear">
</form>
</div>
<?php
echo "</td>";
echo "</tr>"; //-table row
}
pg_close($conn);
?>
Here's pastevents-handle.php:
<?php
$conn = pg_connect ('dbname=xxxx') or die ('Connect failed ');
pg_query_params("INSERT INTO eventsurveypast(eventname, opinion) VALUES ($1, $2)", array($name, $opinion));
echo "email is $idkey, eventname is $name, pastopinion is $opinion";
pg_close($conn);
?>
(I edited a bit for space, ignore anything that isn't vital)

It is illegal to have a form inside another form.
Remove the outer form and everything should work fine, except you have another problem with the code.

Related

Trigger JS function on pageload when populating select box from database

I have the following js script that triggers onChange of the select box below.
It then retrieves data from a table and returns some input fields populated with the data (using PHP code below). Then saves the data.
This part works fine.
However, if I run the script again, and it populates the selected option from DB and shows as a selected option, but it does not display the populated input fields returned from the PHP code/DB query since I am not triggering the onChange again.
I tried to add 'window.onload = showAgentOne;' under the JS for the onChange function, assuming it would see the value in (str) from the select box, but I am probably missing something as it does not work.
New to JS - I hope this makes sense.
JS:
function showAgentOne(str) {
if (str == "") {
document.getElementById("agent1").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("agent1").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "user_agent1.php?q=" + str, true);
xmlhttp.send();
}
window.onload = showAgentOne; // trigger function on pageload - not working
HTML:
<select name="narid" onchange="showAgentOne(this.value)" class="form-control">
<option selected="selected" disabled value="">select agent</option>
<?php
$sql = "select last_name, first_name, active, nrds_id from ft_form_2 ORDER BY last_name";
$sql_result = mysqli_query($mysqli,$sql);
while ($row = mysqli_fetch_array($sql_result)) }?>
<option value="<?php echo $row[" nrds_id "]; ?>" <?php if($narid_agent1==$ row[ "nrds_id"]) { echo ' selected '; } ?> >
<?php echo strtoupper($row["last_name"]) . ' > ' . $row["first_name"] . ' ' . $row["last_name"] . ' ['.$active.']'; ?>
</option>
<? } ?>
</select>
<div id="agent1"></div>
PHP (user_agent1.php) ------------------------- $q=$_GET["q"]; $sql="SELECT pay_to_name,nrds_id FROM ft_form_2 WHERE nrds_id = $q"; $result = mysqli_query($mysqli,$sql); while($row = mysqli_fetch_array($result)) { ?>
<input type="text" name="narid_agent1" value="<?php echo $row['nrds_id']; ?>">
<input type="text" name="pay2_agent1" value="<?php echo $row['pay_to_name']; ?>">
<?php } ?>
'window.onload = showAgentOne;' is a good try but it is expecting a str param, otherwise it returns and do nothing. That's why nothing happens.
You will have to try something like
window.onload = function (event) {
let str = 'ADD_YOUR_VALUE_HERE';
showAgentOne(str);
}
But I can't help you with what str should be.

Retrieving large data amount as datalist from Remote PC

I have a simple HTML page that allows the user to select the amount of fields to enter information. Once the user selects a number, a Javascript onchange method is called that sends the parameter to a PHP page where data is retrieved from a database and stored in a datalist, that is dynamically appended to the HTML page.
When I access this function on the host PC, everything works perfectly. However, when I access this from a remote client, the input fields dont generate automatically.
Here is the code:
<html>
<head>
<script>
function GetInfo(str) {
if (str == "") {
document.getElementById("items").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("items").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/Return-List.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form method="POST" action="../php/Submit.php">
<label>Number of Items</label>
<input type="number" name="numberofitems" onchange='GetInfo(this.value)'>
<br/>
<div id="items"></div>
<input type="submit" value="Go" />
</form>
</body>
</html>
PHP:
<?php
include("connection.php");
if($conn->connect_error) {
die("Connection Failed");
} else {
$items = $_GET['q'];
$fields = "";
$query = mysqli_query($conn,"SELECT name, desc FROM ItemTB");
for($i=1; $i<=$items ; $i++) {
$fields .= "<label>Input</label>
<input list='items' name='items[]' />
<datalist id='items'>";
while($row = mysqli_fetch_array($query)) {
$fields .= "<option value='" . $row['name'] . " | " . $row['desc'] . "'> " . $row['desc'] . "</option>";
}
$fields .= "</datalist>";
}
echo $fields;
}
?>
I have tried using relative and fixed locations in the JavaScript, and limiting the results to 500. Limiting the database results works, and it is important to note that the table returns upwards of 170 000 results. This seems to be the issue here.
How do I retrieve the entire dataset? Is there a way to do this more efficiently, to pack all data without lag?
Thanks in advance.

Onchange Select do different mysql query with Multiple Data sending using AJAX

I have a select on which I want it to execute a query onchange.
(I want to get certain price for the product, depending on the size selected)
The problem is that I'm new to Ajax, and I don't know how to send multiple data. The first variable is the value from the select, and the second var, is the ID from the page someone is visiting.
I need to send to the "getprice.php" page the variables $i, which is $_GET["hidden_id_product"] and $q, which is the value from the onchange select.
I'm stuck here, this is my first post, I couldn't find a response for this, hope someone could help me out.
Select code: (product.php)
<select name="size" id="size" class="form-control" onchange="sizeSelected(this.value)">
<?php
$size_query = "SELECT * FROM sizes WHERE id_product=".$_GET["hidden_id_product"];
$size_result= mysqli_query($connection, $size_query);
if($fetch = mysqli_fetch_array($size_result)){
echo "<option selected value='0' disabled> - SELECT A SIZE - </option>";
if($fetch["seven"] > 0){
echo "<option value='7' > 7us </option>";
}else{
// do nothing
}
if($fetch["sevenhalf"] > 0){
echo "<option value='7.5'> 7.5us </option>";
}else{
// do nothing
}
// and so on...
}else{
echo "<option value='0'>SOLD OUT</option>";
}
?>
</select>
Script Used: (product.php)
<script>
function sizeSelected(str) {
var div = document.getElementById("id_product");
var str2 = div.textContent;
if (str == "") {
document.getElementById("price").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("price").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getprice.php?q="+str+"&i="+str2,true);
xmlhttp.send();
}
}
</script>
Get price code: (getprice.php)
<?php
include("connection.php");
$q = intval($_GET['q']);
$i = $_GET['i'];
if($q = 7){
$qt = "seven";
}elseif($q = 7.5){
$qt = "sevenhalf";
}elseif($q = 8){
$qt = "eight";
}elseif($q = 8.5){
$qt = "eighthalf";
}elseif($q = 9){
$qt = "nine";
}elseif($q = 9.5){
$qt = "ninehalf";
}elseif($q = 10){
$qt = "ten";
}elseif($q = 10.5){
$qt = "tenhalf";
}elseif($q = 11){
$qt = "eleven";
}elseif($q = 11.5){
$qt = "elevenhalf";
}elseif($q = 12){
$qt = "twelve";
}elseif($q = 13){
$qt = "thirteen";
}
$sql="SELECT ".$qt." FROM prices WHERE id_product = ".$i;
$result = mysqli_query($connection,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row[$qt];
}
?>
The full page:
<div>
<span><h2><?php echo $row["name"];?></h2></span>
<hr>
<span><h3>"<?php echo $row["nickname"];?>"</h3></span>
<hr>
<span>
<div id="id_product" style="display: none;">
<?php
$id = $_GET["hidden_id_product"];
echo htmlspecialchars($id);
?>
</div>
<h4>
<?php echo $row["id_product"]; ?>
| <?php echo $row["brand"]; ?>
| <?php echo $row["year"] ?>
</h4>
</span><br>
<span>
<select name="size" id="size" class="form-control" onchange="sizeSelected(this.value)">
<?php
$size_query = "SELECT * FROM sizes WHERE id_product=".$_GET["hidden_id_product"];
$size_result= mysqli_query($connection, $size_query);
if($fetch = mysqli_fetch_array($size_result)){
echo "<option selected value='0' disabled> - Seleccione una talla - </option>";
if($fetch["seven"] > 0){
echo "<option value='7' > 7us </option>";
}else{
}
if($fetch["sevenhalf"] > 0){
echo "<option value='7.5'> 7.5us </option>";
}else{
}
}else{
echo "<option value='0'>SOLD OUT</option>";
}
?>
</select><br>
</span>
<div id="price"></div>
</div>
«I really don't know how to pass a PHP var to JS, that's the main question.»
I don't see any attempt to pass a PHP value directly to JS.
But it would theorically be to like this:
<?php
$myPHPvariable = 34;
?>
<script>
var myJSvariable = <?php echo myPHPvariable; ?>;
console.log(myJSvariable);
</script>
Okay, I now assume you correctly build the select elements... And that you need to pass the selected option value and text to get the item price.
So say your produced HTML looks like this:
<select name="size" id="size" class="form-control">
<option selected value='0' disabled> - SELECT A SIZE - </option>
<option value='7' > 7us </option>
<option value='7.5'> 7.5us </option>
<option value='0'>SOLD OUT</option>
</select>
You tagged your question with jQuery...
Since I'm more used to jQuery Ajax than XMLHttpRequest, here is the way I would do it to send the selected value and the selected option text:
First, remove that inline event handler onchange="sizeSelected(this.value)" from the select.
And use a jQuery event handler.
// Change handler
$("#size").on("change",function(){
var SelectedValue = parseFloat($(this).val());
var SelectedText = $(this).find("option").eq( $(this)[0].selectedIndex ).text();
console.log(SelectedValue+" - "+SelectedText);
// Prepare the data to send.
var data = {
q:SelectedValue,
i:SelectedText
};
$.ajax({
url:"getprice.php",
method:"post",
data:data,
cache:false,
success:function(result){
$("#price").html(result); // Display the price in the "price" div.
},
error:function(request,status,error){
console.log(error); // Ajax error, if any, will be shown in console.
}
})
});
I suggest you to use the post method... So in your PHP, change $_GET to $_POST.
Here, q or SelectedValue is an integer and i or SelectedText is a string.
So you should have the price in the <div id="price"></div> after the request.
If there was a PHP error (not an ajax request error, which would be shown in console), it will be displayed there too.
Also add this in case there would be an SQL error in getprice.php, right after $result = mysqli_query($connection,$sql);:
if (!$result) {
printf("Errormessage: %s\n", $mysqli->error);
}
In hope that will help.
;)

changer function is not working working or error involved

I'm kind fresh with Ajax and done some examples they worked, but then they stopped, I believe somewhere is error involved.
mainfile
<button class='chbt' title='Test' value=" . $i . " onclick='changer($(this).val())'></button>
changer function
function changer(val)
{
if (val == null)
{
document.getElementById("dataedit").innerHTML = "";
return;
}
else
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("dataedit").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","testing.php?id="+val,true);
xmlhttp.send();
}
testing.php file
<?php
include_once 'dbconnect.php';
$ged = $_GET['id'];
$query = $DBcon->query("SELECT * FROM review WHERE RID=".$ged);
$RRow=$query->fetch_array();
?>
<html>
<head>
<script src="scripts/jscript.js"></script>
</head>
<body>
<script>
alert("working123!!!");
$('#dataformas').hide();
$('#dataedit').show();
</script>
<form method='post' action='updatereview.php' id='updata' name='updata'>
Vn<input name='rating' id='rating' type='range' min='1' max='5' maxlength='500' value='<?php echo $RRow[4]; ?>' step='1' required />Pt<br><br>
<textarea name='edittext' id='edittext' rows='5' cols='30'><?php echo $RRow[2]; ?></textarea>
<span id='count2'></span>
<script>
//location.hash = ".updata";
var el_t = document.getElementById('edittext');
var length = el_t.getAttribute('maxlength');
var el_c = document.getElementById('count2');
el_c.innerHTML = length;
el_t.onkeyup = function ()
{
document.getElementById('count2').innerHTML = (length - this.value.length)+' left';
};
</script><br>
<input type='hidden' name='idas' id='idas' value="<?php echo $ged; ?>">
<input type='hidden' name='cidas' id='cidas' value="<?php echo $RRow[3]; ?>">
<button type='submit' form='updata' id='send_button' value='Submit'>Update</button>
</form>
</body>
</html>
I as you can see I need to pass one param which is integer generated by loop, so my changer function is not working and throws
Uncaught TypeError: Cannot set property 'innerHTML' of null
at XMLHttpRequest.xmlhttp.onreadystatechange

JavaScript event listener not being added to button

I have a <button> in my code that has the id button_edit_post, and my java script won't add the event listener to it.
document.onload = function(){
document.getElementById('button_edit_post').addEventListener('click', function(){
alert("event listener added");
var data = document.getElementById('edit_post').innerHTML;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert("data added");
};
};
var php = data + "q=" + post_id;
console.log(php);
xhr.open("POST", "edit_post.php?p="+php, true);
xhr.send();
}, false);
};
HTML:
<article>Edit blog post
<section><div id="admin_subtitle">Select the post you want to edit then modify the text</div>
<select name="edit" id='edit' onchange='editPost(value)'>
<option>Please select a post..</option>
<?php
$result = mysql_query("SELECT BlogPostID, BlogPostTitle FROM blogpost ORDER BY BlogPostID DESC");
while ($row = mysql_fetch_array($result)){
$blogvar = array($row ['BlogPostID'], $row ['BlogPostTitle']);
?>
<option value="<?php echo $blogvar[0]; ?>" id='edit_option'><?php echo $blogvar[1]; ?></option>
<?php
};
?>
</select>
<div id='gif_loader'></div>
<div id='text_edit_area' style='display: none;'>
<textarea id='edit_post' rows='30' cols='200'></textarea>
<button id='button_edit_post'>Edit Post</button>
</div>
any help would be great,
Thanks :)
Should be window.onload = function, or really just onload = function, since window is implicit.

Categories

Resources