So I have an SQL database and table, and a php file calls the 10 results from it like this.
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$password = "";
$database = "c9";
$dbport = 3306;
$con = mysqli_connect($servername, $username, $password, $database, $dbport);
if (!$con) {
die("Error! Check your internet connection and try again!");
}
mysqli_select_db($con, "users");
$query = "SELECT * FROM users LIMIT 10";
$result = mysqli_query($con, $query);
echo "<table>
<tr>
<th>ID</th>
<th>Village</th>
<th>Power</th>
<th>Influence</th>
<th>Economy</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['village'] . "</td>";
echo "<td>" . $row['power'] . "</td>";
echo "<td>" . $row['influence'] . "</td>";
echo "<td>" . $row['economy'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
This is an JQuery ajax script I made but it doesn't seem to work
$(document).ready(function(){
var xmlhttp = new XMLHttpRequest();
if(xmlhttp==null){
alert("Your browser does not support AJAX!");
return false;
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//document.getElementById("divTable").innerHTML=xmlhttp.responseText;
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "/server.php", true);
xmlhttp.send(null);
});
return false;
What would be the best way to display this table from the php file on a separate index.html file. AJAX, JQuery AJAX, and XML are all options but I don't know how I would do this.
I ideally would want to display the result from the PHP file with document.getElementById('leaderboard').innerHTML because it would take all the html code, including the table.
Any help is greatly appreciated.
Use it!
In Ajax code:
var dataString = 'ajax=true';
$.ajax({
type: "GET",
url: "/server.php",
data: dataString,
dataType:'json',
success: function(data){
alert(data);
}
});
In PHP code:
$query = "SELECT * FROM users LIMIT 10";
$result = mysqli_query($con, $query);
echo json_encode($result); exit();
Related
The code is supposed to fetch the query result and display it according to the number written in the text box, i tried (onkeydown and onkeyup) and both didn't work, i have no idea why it is not working and what is my mistake.
HTML code:
<script>
function showRoom(rid) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "getRoomAJAX.php?q="+rid, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
}
</script>
<form>
<input type="text" name="rid" onkeydown="showRoom(this.value)">
</form>
<div id="txtHint">Room...</div>
getRoomAJAX.php code:
<?php
session_start();
ob_start();
$q = $_GET["q"];
$db = new Database();
$dbc = $db->getConnection();
if (!$dbc) {
die('Could not connect: ' . mysql_error());
}
$query = "SELECT * FROM indvProj_room WHERE rid = '".$q."'";
$result = mysqli_query($dbc, $query);
//start creating the table HTML
if ($result) {
echo "<table border='1' align='center' cellspacing = '2' cellpadding = '4' width='100%'>
<tr>
<th><b>Room ID</b></th>
<th><b>Room Description</b></th>
</tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
echo "<tr>";;
echo "<td>" . $_SESSION['adminRoomChoice'] = $row['rid'] . "</td>";
echo "<td>" . $row['roomDesc'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo '<p class="error">Sorry, cannot find the room, are you sure of the entered Room ID?</p>';
echo '<p class = "error">' . mysqli_error($dbc) . '</p>';
}
?>
Does showRoom() get called at all? Put a console.log(rid); inside showRoom() to see if that is getting called and whether the value is being passed in correctly.
If you can determine that it's getting into the showRoom(), then follow the code down and into PHP to see where it's failing. Echo some sample text at the top of the PHP file with return; right below it. That will tell you if the error is in the XMLHttpRequest code or somewhere in the PHP file.
Normally, I don't pass any variables/params with onkeydown type of events. Usually, I call a method like this without params and then retrieve the value based on the element's id. See this answer for more detail on that: https://stackoverflow.com/a/54040431/3103434
UPDATE 19/01/2017 - PROBLEM RESOLVED - Removed 'intval' on get request within get.php file and the value q is now capturing the correct data.
What i'm trying to achieve can be summed up in 2 points:
1.) A dropdown box which dynamically populates according to a MySql table
2.) Depending on whats chosen in the dropdown the textfield below will display a corresponding id via a SQL query.
I've been trying to follow W3Schools guide and modifying it accordingly to match my needs, but i'm getting stuck.
Here is what I currently have:
PHP -
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('core_log');
$sql = "SELECT local_authority FROM ons_code_tbl";
$result = mysql_query($sql);
echo "<tr>";
echo "<td> Local Authority: </td>";
echo "<td>";
echo "<select name='local_authority'onchange='showLocal_authority(this.value)'>";
echo '<option value=""></option>';
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['local_authority'] . "'>" . $row['local_authority'] . "</option>";
}
echo "</select>";
echo "</td>";
echo "</tr>";
?>
Script -
<script>
function showLocal_authority(str) {
if (str == "") {
document.getElementById("txtHint").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("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","get.php?q="+str,true);
xmlhttp.send();
}
}
</script>
get.php -
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','core_log');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ons_code_tbl");
$sql="SELECT ons_code FROM ons_code_tbl WHERE local_authority = '".$q."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$name = $row['ons_code'];
echo "<td>" . $q . "</td>";
mysqli_close($con);
?>
I did a test and simply echoed the value q to see what its outputting, it should be the value of whatever they pick in the dropdown, but instead its displaying 0?
In the screenshot below, it should display 'Amber Valley' with the correct ONS code pulled from the MySQL table.
If anyone can tell me why the value q is not storing 'Amber Valley' for example, that would be great, thanks!
Replace this line:
$q = intval($_GET['q']);
for
$q = $_GET['q'];
Then make a query with prepared statement, to avoid SQL Injection:
mysqli_select_db($con,"ons_code_tbl");
$sql="SELECT ons_code FROM ons_code_tbl WHERE local_authority = ?";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "s", $q);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $ons_code);
mysqli_stmt_fetch($stmt);
Just replace echo "<td>" . $q . "</td>"; for echo "<td>" . $ons_code . "</td>";
I have a table for a sports day where there are 4 columns name, house, event, result. I have no problem creating and displaying the database but i want to be able to search in a bar and to use AJAX to automatically search all 4 columns for whats in the search bar. I am using PHPmyadmin to store the database with mySQLI. i am able to display the database on the page that i want. I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search. I have never used Ajax before so sorry for my bad code as it is all from w3schools site. the DB is called sports_day and the table is called full_results. here is my current code.
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").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("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","results_query.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
and on a page called results_query.php is this code
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql="SELECT * FROM full_results WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
at the moment what happens is none of the table is shown and when i type anything in the search box the whole table appears along with in plain text at the bottom the title and all the contents of the table in a long line.
any suggestion to get my code to work would be greatly appreciated!
thanks!
The solution would be like this:
Keep your HTML search form as it is.
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
... I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search.
See this <div> section here,
<div class="col-sm-12">
...
</div>
You didn't put anything in this <div> section. First of all, you have to display your entire table in this section, which you can later filter out using the AJAX request. Also, assign an id to this <div> section so that it could be easier for you put the AJAX response in this <div> section. So the code for this <div> section would be like this:
<div class="col-sm-12" id="pupil-info">
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</div>
Change your Javascript/AJAX code in the following way,
<script>
function showUser(str){
var str = str.trim();
var xmlhttp;
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("pupil-info").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","results_query.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
</script>
Please note that you should encode the user inputted str value using encodeURIComponent() function before passing it to the results_query.php page.
Finally, on results_query.php page process your AJAX request like this:
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
if(isset($_GET['q']) && !empty($_GET['q'])){
$sql .= " WHERE CONCAT(id, NAME, HOUSE, EVENT, RESULT) LIKE '%".$_GET['q']."%'";
}
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
}else{
echo "<tr>";
echo "<td colspan='4' style='text-align:center;'>No records found</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.
If you use your 'results_query.php' file only for getting the data from database, then you don't need to create a <body> tag. If you use only PHP then you can easily skip any plane HTML. That's just a digression :)
But to the point.
You can change the way you return your data from database. I think, instead of doing a lot of echo's it is better to add result to the variable and echoing the variable at the end.
$data = '<tr>' . '<th>NAME</th>' . '<th>HOUSE</th>' . '<th>EVENT</th>' . '<th>RESULT</th>' . '</tr>';
while($row = mysqli_fetch_array($result)) {
$data .= '<tr>';
$data .= '<td>' . $row['NAME'] . '</td>';
$data .= '<td>' . $row['HOUSE'] . '</td>';
$data .= '<td>' . $row['EVENT'] . '</td>';
$data .= '<td>' . $row['RESULT'] . '</td>';
$data .= '</tr>';
}
$data .= '</table>';
mysqli_close($con);
echo $data;
See if this changes something.
What about showing entire table after the page's loaded, you will have to change both PHP and JavaScript code a little bit.
You can change your JS so it gets everything from your full_results table after page is loaded.
There are several ways to do this and you can read about them here:
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
The easiest way would be to do this this way:
<script>
function showUser(str) {
var url;
var xmlhttp;
if (str == "") { //if empty string - get all data
url = "results_query.php";
} else { //get particular data otherwise
url = "results_query.php?q="+str;
}
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("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
<script>
//calling your function with empty string because we want to get all data
showUser("");
</script>
and in the PHP file you can do something like this:
<?php
$q = 0;
//check if 'q' parameter was passed
if(isset($_GET['q'])) {
$q = intval($_GET['q']);
}
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results";
Now your JavaScript function will be called after loading your page.
It will call your PHP script with AJAX and this script should return all data from your table.
In line ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results"; there is a simple check if $q is different from 0. Our variable will be set to 0 if no argument was passed, so whenever $q is equal to '0', we just want to get all the data from full_results and specific data otherwise.
I also added var xmlhttp because it is only local variable.
You can read more about that in here:
https://stackoverflow.com/a/1471738/7301294
I hope it will help you.
Let me know if you have any other problems and never be afraid to ask.
Good luck!
Basically I am trying to use a $gen variable to match a user query to a string stored in a database describing a genre of music. My problem is that if the genre is Indie/Pop and the user selects Indie as a search query the event will display. If they select Pop the event does not display.
Here is how i am querying the database.
$sql="SELECT * FROM $tab WHERE genre LIKE '$gen%'AND dateForm = '$datepicker'";
Any help appreciated as ever
php script to get info
<?php
$con = mysqli_connect('localhost','root','','python');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax");
$gen = $_GET['gen'];
$gen = mysql_real_escape_string($gen);
$tab = $_GET['tab'];
$tab = mysql_real_escape_string($tab);
$datepicker = $_GET['datepicker'];
$sql="SELECT * FROM $tab WHERE genre LIKE '%$gen%' AND dateForm = '$datepicker'";
$result = mysqli_query($con,$sql);
echo "<table class='table table-hover'><thead>
<tr>
<th><h3>Artist</th>
<th><h3>Location</th>
<th><h3>Date</th>
<th><h3>Genre</th>
<th><h3>Preview</th>
</tr></thead>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['artist'] . "</td>";
echo "<td> <b>Venue: </b>" . $row['venue'] . "<p><b>Location: </b>" . $row['location'] . "</td>";
echo "<td>" . $row['datez'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
echo "<td>" . '<iframe width="100%" height="100" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/' . $row['link'] . '&color=000000&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false"></iframe>' . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
The gen variable is made using AJAX
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var gen = document.getElementById('gen').value;
var datepicker = document.getElementById('datepicker').value;
var tab = document.getElementById('tab').value;
//var datepicker = document.getElementById('datepicker').value;
var queryString = "?gen=" + gen ;
queryString += "&datepicker=" + datepicker +"&tab=" + tab;
ajaxRequest.open("GET", "getuser.php" +
queryString, true);
ajaxRequest.send(null);
}
Okay, some security lessons in here. Bind the parameters $gen (with the wildcards added) and $datepicker in the prepared query. Since you can't bind column or table names, I'd run something like I did below with $tab and the allowed $tables array. This allows you to set a predefined list of tables that the query is allowed to run against and will throw an exception if the table provided is not in the list.
I don't like mysqli or procedural code so I don't use it much but I'm pretty sure everything is in order.
mysqli_select_db($con,"ajax");
// Add wildcards here
$gen = '%'.$_GET['gen'].'%';
$tab = $_GET['tab'];
$datepicker = $_GET['datepicker'];
// Check if $tab is in allowed tables (array $tables)
$tables = ['valid_table1', 'valid_table2', 'valid_table3'];
if (!in_array($tab, $tables)) {
throw new Exception('Hey, get outta here!');
}
$sql="SELECT * FROM $tab WHERE genre LIKE ? AND dateForm = ?";
// Prepare, bind, and execute
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt, 'ss', $gen, $datepicker);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result)) {
...
}
Try adding a % at the beginning of the search value
$sql="SELECT * FROM $tab WHERE genre LIKE '%$gen%'AND dateForm = '$datepicker'";
I have an php generated table/form with checkboxes like this:
if ($query) {
if (!mysqli_num_rows($query)) {
//Empty storage
echo "There are no items in '$storage'.";
exit();
} else {
//form
echo "<form name='send_parts_form' action='../includes/generatetab.php' method='post'>";
//Table header
echo "
<table>
<tr>
<th>Part</th>
<th>PN</th>
<th>Manufactured</th>
<th>Serial</th>
<th>Site</th>
<th>Date replaced</th>
<th>By user</th>
<th>Faulty</th>
<th>Send</th>
<th>Select</th>
</tr>";
//Retrieved data
while ($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['part_type'] . "</td>";
echo "<td>" . $row['pn'] . "</td>";
echo "<td>" . $row['manufactured'] . "</td>";
echo "<td>" . $row['serial'] . "</td>";
echo "<td>" . $row['site_id'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "<td>" . $row['user'] . "</td>";
echo "<td>" . $row['faulty'] . "</td>";
echo "<td><input type='checkbox' name='send_parts[]' class='checkclass' value=" . $row['id'] . "></td>";
echo "</tr>";};
echo "</table>";
echo "</br>";
echo "</br>";
echo "<input type='button' onclick='sendToZG()' value='Send'/>";
echo "</br>";
echo "<input type='submit' name='submit' value='Generate tab' />";
echo "</form>";
exit();
}
} else {
die("Query failed");
}
User then checks option they want and upon submiting (Generate tab) they get tab delimited text with values they selected.
I now want when they click "Send" to have values posted to another php page and results returned on the same page (under SentList div). I have js like this:
//Browser Support Code
function sendToZG(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
var ajaxDisplay = document.getElementById('SentList');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from page and pass it to server script.
var formData = new FormData( document.getElementsByName("send_parts")[0] );
ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxRequest.send("send_parts=" + formData);
}
Edited: ajaxRequest.send("send_part=" + formData); to ajaxRequest.send("send_parts=" + formData);
Now it returns:
Invalid argument supplied for foreach() on line 53 (That is where I fetch my data in sendtozg.php).
I'll add sendtozg.php at the end of the post.
If instead of:
<form name='send_parts_form' action='../includes/generatetab.php' method='post'>
I echo:
<form name='send_parts_form' action='../includes/sendtozg.php' method='post'>
Upon submit, script sendtozg.php gets executed fine but on a different page.
So basically what I'm trying to do is to have 2 options for the php generated form:
Generate tab delimited txt file
Execute sendtozg.php and return results on same page
I already have both scripts (generatetab.php and sendtozg.php) and they work fine.
sendtozg.php:
if (!empty($_POST['send_parts'])){
foreach ($_POST['send_parts'] as $send_parts){
$getchecked = mysqli_query($con, "SELECT * FROM $storage WHERE id=$send_parts");
while ($row = mysqli_fetch_array($getchecked)) {
$copypart = mysqli_query($con, "INSERT INTO sent_parts (part_type, pn, manufactured, serial, site_id, date, user, faulty, log)
SELECT part_type, pn, manufactured, serial, site_id, date, user, faulty, log
FROM $storage WHERE id=$send_parts");
// check to see if it copied
$getserial = mysqli_query($con, "SELECT serial FROM $storage WHERE id=$send_parts");
$getserial_row = mysqli_fetch_array($getserial, MYSQLI_NUM);
$foundserial = $getserial_row[0];
$checkcopy = mysqli_query($con, "SELECT id FROM sent_parts WHERE serial = '$foundserial'");
// add user info and date
$addinfo = mysqli_query($con, "UPDATE sent_parts SET sent2zg='$user', date2zg='$strdate' WHERE serial = '$foundserial'");
if (!$check1_res) {
printf("Error: %s\n", mysqli_error($con));
exit();
};
//delete from storage
if($checkcopy > 0) {
$getpart = mysqli_query($con, "SELECT part_type FROM sent_parts WHERE serial='$foundserial'");
$getpart_row = mysqli_fetch_array($getpart, MYSQLI_NUM);
$deletedpart = $getpart_row[0];
$removepart = mysqli_query($con, "DELETE FROM $storage WHERE id = '$send_parts'");
echo "Part " . $deletedpart . " has been transfered";
} else {
echo "Part " . $row['part_type'] . "was NOT transfered";
};
};
} exit ();
} else {
echo "Nothing was selected, please try again!";
}
Your <form> doesn't have an id attribute on it so you'll either need to add id="send_parts" to the <form> or you'll need to change your code from getElementById to getElementsByName like this:
// Now get the value from page and pass it to server script.
// Serialize the data
var formData = new FormData( document.getElementsByName("send_parts")[0] );
ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.send(formData);
Then inside sendtozg.php you'll need to change the first two lines to:
if (!empty($_POST)){
foreach ($_POST as $send_parts){
This is the final code for the sendtozg.js:
// Get get the value from page and pass it to server script.
var formData = new FormData( document.getElementsByName("send_parts")[0] );
ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
ajaxRequest.send(formData);
}
and sendtozg.php should be:
if (!empty($_POST)){
foreach ($_POST['send_parts'] as $send_parts){
$getchecked = mysqli_query($con, "SELECT * FROM $storage WHERE id=$send_parts");
By the way:
print_r ($some_array)
and
if (!$check1_res) {
printf("Error: %s\n", mysqli_error($con));
exit();
};
Are great tools for troubleshooting.