Cannot retrieve value from post request with ajax - javascript

I just wrote my first Ajax request but it doesn't work. It needs to update when a new value in the drop-down list is selected.
This is my javascript code:
$(document).ready(function() {
function ajaxLoaded(response) {
$('#performanceResults').html(response);
}
function doRequest() {
$.ajax({
url: "results.php",
type: 'POST',
success: ajaxLoaded
});
}
$('#performance').change(doRequest);
});
and this is how I retrieve the q part (which doesn't work):
public function getResults() {
$intCase = intval ( $_POST ['q'] );
var_dump ( $intCase );
if ($intCase == 1 or $intCase == 2 ) {
if ($intCase == 1) {
$strSql = 'select bidder_id, won, lost, fillrate, costs, cost_auction from result_bidder where tagload = ( select max(tagload) from result_bidder) order by cost_auction asc limit 1';
}
if ($intCase == 2) {
$strSql = 'select bidder_id, won, lost, fillrate, costs, cost_auction from result_bidder where tagload = ( select max( tagload ) from result_bidder ) order by fillrate asc limit 1';
}
$arrBestPerformer = $objDatabase->queryresult ( $strSql );
echo "<table border='1'>
<tr>
<th>bidder_id</th>
<th>won</th>
<th>lost</th>
<th>fillrate</th>
<th>costs</th>
<th>cost_auction</th>
</tr>";
while ( $row = mysqli_fetch_array ( $arrBestPerformer ) ) {
echo "<tr>";
echo "<td>" . $row ['bidder_id'] . "</td>";
echo "<td>" . $row ['won'] . "</td>";
echo "<td>" . $row ['lost'] . "</td>";
echo "<td>" . $row ['fillrate'] . "</td>";
echo "<td>" . $row ['costs'] . "</td>";
echo "<td>" . $row ['cost_auction'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
}
My Form:
public function SelectPerformanceIndicator() {
$this->getResults ();
$str = '<form >';
$str .= 'Select your performance indicator<br>';
$str .= '<select id = "performance">';
$str .= '<option value = "">Select Performance Indicator</option>';
$str .= '<option value = "1">Cost per auction </option>';
$str .= '<option value = "2">Fillrate </option>';
$str .= '</select>';
$str .= '</form>';
$str .= '<br>';
$str .= '<div id="performanceResults">';
return $str;
}

Your problem is that your POST data string is invalid.
xmlhttp.send("q ="+ str);
Should be
xmlhttp.send("q="+ str);
Without the space between q and =.
And you missed to send the header to tell PHP that it should map the Data sent with the request to the $_POST var.
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
So your correct function would be:
function showUser(str) {
if (str=="") {
document.getElementById("performance").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("performance").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","results.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+ str);
}
But again: use jQuery to make your AJAX requests. If you use jQuery you don't have to struggle with errors like this anymore.

You have added space in query string, "q =" this is not behaving as q key in $_POST variable,
remove space between key and =
xmlhttp.send("q ="+ str);
to
xmlhttp.send("q="+ str);
Update Answer: AJax POST will be worked when request have Content-type: application/x-www-form-urlencoded header.
please add Header before send method
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
OR
you can send request by GET method without header

Related

How can I access the values of a checkbox outside of the form action that it is declared in?

I successfully created a script that will delete the rows of a table if a checkbox is checked on that row (the checkbox holds the rowID). The checkboxes and button to delete these rows are inside of the same form tags. Now I want to create another button that uses the value of the checkboxes to do a different update statement, but the values of the checkboxes are not appearing in $_POST on this separate page.
Does anyone know how to make the checkbox values accessible outside of the form action it is inside of? Here is my reduced code for the delete that works:
The function below is called on PickTicket.php to display a table.
Function DisplayPickTicket() {
$conn = getDBConnection();
$sql = "SELECT * FROM dbo.BK_NotesRecord WHERE StatusID = 1 ";
$stmt = sqlsrv_query( $conn, $sql );
if ( $stmt === false ) {
die( print_r( sqlsrv_errors(), true) );
}
echo '<form action="updatepickstatus.php" method="post">';
// Delete Checkbox header.
echo '<th class="table-header" style="width:5px;">';
echo 'Delete';
echo '</th>';
// Inventory number header.
echo '<th class="table-header" style="width:90px;">';
echo 'Inventory #';
echo '</th>';
//InventoryID Header
echo '<th class="table-header" style="width:40px;">';
echo 'InventoryID';
echo '</th>';
if (sqlsrv_has_rows($stmt)) {
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
echo '<tr>';
//Delete checkbox
echo '<td class="cell"><div class="cell">';
echo '<input type = "checkbox" name="chkbox[]" value= "' .$row['InventoryID'].
'">';
echo '</td>';
// Inventory#
echo '<td class="cell"><div class="cell">';
echo $row["InventoryNumber"];
echo '</td>';
// InventoryID.
echo '<td class="cell"><div class="cell">';
echo $row["InventoryID"];
echo '</td>';
}
}
echo "<tr>";
echo "<td>";
echo "<input type='submit' name='submit' Value='Remove'>";
echo '</form>';
echo "</td>";
echo "</tr>";
This is updatepickstatus.php:
<?php
$serverName = "(local)";
$connectionOptions = array("Database"=>"Powerlink");
$conn = sqlsrv_connect( $serverName, $connectionOptions);
if( $conn === false ) {
echo "Connection failed!<br>";
die( print_r( sqlsrv_errors(), true));
}
if (isset($_POST['chkbox'])) {
foreach($_POST['chkbox'] as $Update) {
$sql = "UPDATE BK_NotesRecord set StatusID = '2' WHERE InventoryID LIKE '".$Update."'";
$stmt = sqlsrv_query( $conn, $sql );
//echo '$ids';
}
}
print_r($_POST);
?>
^^I want to accomplish this same basic task, but outside of updatepickstatus.php. When applying similar logic to check the values of the selected checkboxes on a different I get an empty array. Any thoughts?
Try declaring a variable and passing the value you want to use to it then use sessions to move it where ever you want.

Updating mySQL table with user interface - PHP

[Sample Look]
I'm trying to make an interface where you can edit/add/remove fields of a mySQL database. This is how it looks visually, and I have all the functionality on the client side working.
My question is: How can I pass any edits/adds/removals to the server side? I'll include a link for my JSFiddle.
And the code below will show how I currently great the table.
<?php
$servername = "localhost";
$username = "lalalal";
$password = "lalalal";
$link = mysqli_connect("localhost", "lalala", "lalala", "lalala");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlStart = "SELECT `Name`, `EXT`, `Returning Time`, `Returning Date`, `Out`, `Reset`, `Booked` FROM `lalala`";
if($result = mysqli_query($link, $sqlStart)){
if(mysqli_num_rows($result) > 0){
echo "<table id = contactTable>";
echo "<tr id = row1>";
echo "<th id = sortTable onclick=sortTable(0)>Name ↕</th>";
echo "<th style = width:100px;>EXT</th>";
echo "<th style = width:300px;>Returning Time</th>";
echo "<th style = width:300px;>Returning Date</th>";
echo "<th style = width:70px;>Out</th>";
echo "<th style = width:100px;>Reset</th>";
echo "<th style = width:600px;>Booked</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
$currentCheck = $row['Out'];
if ($currentCheck == 0) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
if ($currentTime == 0) {
echo "<td> <form> <input type = 'time', id = 'timePickChange'> </form> </td>";
} else {
echo "<td> <form> <input type = 'time', id = 'timePickChange' value =" . $currentTime . "> </form> </td>";
}
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = 'datePickChange' value =" . $currentDate . "> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)'> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
} else if ($currentCheck == 1) {
echo "<tr style = 'background-color: #E2E9FD'>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
echo "<td> <form> <input type = 'time', id = timePickChange disabled> </form> </td>";
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = datePickChange disabled> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)' checked> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
}
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sqlStart. " . mysqli_error($link);
}
?>
Depending on your data validation model, you might want to control the inputs value client side before posting them to your back-end.
AFAIK, you're already adding/editing/removing your contacts on the client side, so If I understand correctly, when your user should click on Edit/Remove & confirm , it would be a confirmation of what the user has done in the browser, this doesn't really change much apart from the fact that otherwise you might need dedicated buttons/row (or any other bindable events).
For these operations what you could do is proceed to bulk delete / edit, and this could be easily done by filtering out in your JS all the modified/deleted data and sending it to your back end PHP with Ajax/jQuery in the form of a stringified array.
As for insertion operation you'd submit them at the same time you add them to your table, by executing a POST operation.
And it could be done with something like this :
$.ajax({
method: "PUT",
url: "some.php",
data: JSON.stringify(myUpdatedDataInAnArray)
// you might need to stringify your array to ensure format ?
})
.done(function( msg ) {
alert( "Data Updated: " + msg );
});
In your back end php, you'd listen for POST/PUT/DELETE methods with something like that :
if (isset($_POST['add'])){
do your thing
}
if (isset($_PUT['updated'])){
//Since you're sending a stringified array, you must parse it with
$myArray = json_decode($_PUT['updated']);
do your thing
}
if (isset($_DELETE['deleted'])){
do your thing
}
I say Ajax because using a traditional POST/PUT/DELETE form would result in refreshing the page.
Here are some useful refs :
JS JSON Stringify and JSON Parse
PHP : JSON DECODE and JSON Encode
Ajax docs
Ajax Examples

AJAX request displaying content to user but not on the source of the page

On the body of the document, lets call it "form.php" we have the following:
On the head we have a JavaScript 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", "getchauffeur.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
We query to database and populate a dropdown. We switch content using (showUser):
<div>
<?
$result = $mysqli -> query("select id, nomchauffeur from chauffeurs");
echo "<select name='id' onchange='showUser(this.value)'>";
while ($row = $result -> fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['nomchauffeur'];
echo '<option value="'.$id.
'">'.$name.
'</option>';
}
?>
Here we are still in body. We put the content of AJAX into div.
<div id="txtHint"><b>chauffeur info will be listed here...</b> </div>
</div>
Here is our script that populate form fields with the content of AJAX request:
<script>
var table = document.getElementById('table');
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
//rIndex = this.rowIndex;
document.getElementById("nomchauffeur").value = this.cells[0].innerHTML;
document.getElementById("prenomchauffeur").value = this.cells[1].innerHTML;
document.getElementById("agechauffeur").value = this.cells[2].innerHTML;
document.getElementById("cinchauffeur").value = this.cells[3].innerHTML;
};
}
</script>
Now here is our getchauffeur.php:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','nouveau');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax");
$sql="SELECT * FROM chauffeurs WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>nom</th>
<th>prenom</th>
<th>age</th>
<th>adresse</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['nomchauffeur'] . "</td>";
echo "<td>" . $row['prenomchauffeur'] . "</td>";
echo "<td>" . $row['agechauffeur'] . "</td>";
echo "<td>" . $row['adressechauffeur'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The Problem: Everything works fine if the table is on the same page. But here the AJAX request constraints us to put the table in other php page(chauffeur.php).
What we need is populating the form fields automatically by clicking on the row displayed from dropdown Change actions. It appears that the row inserted into table inside 'chauffeur.php' is not printed on the html DOM. When we click on page view source, it displays only:
<div id="txtHint"><b>chauffeur info will be listed here...</b> </div>
And not the content of the following fields:
nomchauffeur prenomchauffeur agechauffeur adressechauffeur
How could we grab the content of row and fill automatically the form and where is it?
This whole javascript AJAX should be after your HTML div #txtHint.
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
Also you can return only row instead of whole table. On main page create table as id 'txtHint' and insert that row in response.

Calling a POST variable in PHP-function

I have a PHP-file with multiple php functions in it.
I am sending a Javascript Variable with an AJAX-call, POST method to that PHP-file.`
Now the variable IS accessible in my PHP-file but not in that specific function where I want it...
$("#dropdown").change(function () {
var value = $("#dropdown").val();
console.log(value);
$.ajax({
type: "POST",
dataType: 'text',
url: "PhpFunctions.php",
data: {id:$("#dropdown").val()},
success: function (data) {
console.log(data);
$("div.geselecteerdVliegtuig").fadeIn("slow", function () {
console.log("Vliegtuigdetail faded in");
});
/*
$("div.vliegtuigenEnabled2").hide();
console.log("vliegtuigEnabled ID's hidden");
*/
},
error: function (err) {
alert('error: ' + err);
}
}); //END AJAX CALL`
//I CAN ACCESS DATABASE AND ID IS ACCESSIBLE HERE
//Connect to server
$connect = mysql_connect("localhost", "root", "root") or die(mysql_error());
//Connect to database
$select_db = mysql_select_db("Luchthaven") or die("Could not find database");
$id = $_POST['id'];
echo $id; //WORKS
//NEED TO ACCESS IS HERE
function GeselecteerdVliegtuig() {
makeConnection();
//Query the database
$id = $_POST['id'];
//$query = "SELECT * FROM vliegtuig WHERE vliegtuig_ID = 'PEG431';";
//echo "SELECT * FROM vliegtuig WHERE vliegtuig_ID = 'PEG431';<br/>";
$query = "SELECT * FROM vliegtuig WHERE vliegtuig_ID = '" . $id . "';";
echo "SELECT * FROM vliegtuig WHERE vliegtuig_ID = '" . $id . "';<br/>";
$fetch = mysql_query($query) or die("could not fetch data");
while ($row = mysql_fetch_assoc($fetch)) {
echo "<tr id=" . $row['vliegtuig_ID'] . ">";
echo "<td>" . $row['vliegtuig_ID'] . "</td>";
echo "<td>" . $row['maatschappij'] . "</td>";
echo "<td>" . $row['lengte'] . "</td>";
echo "<td>" . $row['breedte'] . "</td>";
echo "<td>" . $row['kilometerstand'] . "</td>";
echo "<td>" . $row['bouwjaar'] . "</td>";
echo "<td>" . $row['bereik'] . "</td>";
echo "<td>" . $row['aantalMotoren'] . "</td>";
echo "</tr>";
} // END WHILE
mysql_close(); //Make sure to close out the database connection
echo "<b>Connection closed<b><br/><br/>";
}
You can pass the $_POST['id'] variable to that function GeselecteerdVliegtuig($id) and call the function with GeselecteerdVliegtuig($_POST['id'])
Get rid of this line:
$id = $_POST['id'];
as you might want to use your functionality even if your value is not located in your $_POST["id"]. Modify your function header from
function GeselecteerdVliegtuig() {
to
function GeselecteerdVliegtuig($id) {
Call your function this way:
if (isset($_POST['id'])) {
GeselecteerdVliegtuig($_POST['id']);
}
and call your function from the page where you posted the value, make sure that the page where you posted exists, works and responds.
Finally, when everything is working change the way you are working with the database, because your current approach has a security leak due to SQL injection possibilities. What if I visit your page and execute the following in the console:
$("#dropdown").val("0'; delete from vliegtuig where '' = '");
and then trigger the post? It will remove every single record from your table unless you are making sure that these attempts fail.

Can jQuery/JS check what changed the input?

can jQuery or plain JavaScript check how the value of input field was changed? Maybe something similar to that:
$('input').change(function(e){
e.preventDefault();
console.log(e.changedFunction.name);
});
I know given code doesn't work and doesn't do what I want. But is this even possible somehow?
Why do I need that? I have a dialog box where I have multiple forms (each form changes one thing). When I submit form, the value resets back to value which was there previously. e.g. In the form there's a word 'Hello', when I change it to 'Hello, World!', it successfully sends the data to $.post, but then resets the value to 'Hello'. I can't seem to find any function, neither php, nor javascript that changes the input. That's why I need to check what or who changes my input value back.
EDIT:
Including sample code.
editblock.php
} else if ($_POST['what'] == 'email') {
$sql = mysql_query("SELECT id, email, loggedin FROM users WHERE id = " . mres($_POST['id']) . " LIMIT 1");
$edit = mysql_fetch_array($sql);
$output .= '<div id="block-' . $_POST['what'] . '"><form method="post" id="form-' . $_POST['what'] . '">';
$output .= '<input type="hidden" name="id" value="' . mres($_POST['id']) .'" />';
$output .= '<input type="text" name="value" value="' . $edit['email'] .'" /> ';
$output .= '<input type="hidden" name="what" value="' . mres($_POST['what']) .'" />';
$output .= '<input type="submit" name="submit" value="OK" />';
$output .= '</form></div>';
$output .= '<script>
$("#form-' . $_POST['what'] . '").submit(function(event) {
event.preventDefault();
var $form = $( this ),
doval = $form.find( "input[name=\"value\"]" ).val(),
doid = $form.find( "input[name=\"id\"]" ).val(),
dowhat = $form.find( "input[name=\"what\"]" ).val();
$.post("/pages/profilis/doedit.php", { do: doval, id: doid, what: dowhat },
function( data ) {
$("#block-' . $_POST['what'] . '").empty().append( data );
$form.find("input[name=\"value\"]").val(doval);
}
);
});
</script>
';
}
doedit.php
else if ($_POST['what'] == 'email') {
if (empty($_POST['do'])) {
$error[] = 'err';
} else {
if ( ! preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i", $_POST['do'])) {
$error[] = "err";
}
$sql = mysql_query("SELECT `id` FROM `users` WHERE `email` = '" . mres($_POST['do']) . "' LIMIT 1");
if (mysql_num_rows($sql) == 1) {
$error[] = "err";
}
if ($edit['loggedin'] > 0) {
$error[] = "err";
}
if (sizeof($error) >= 1) {
echo join($error, '<br/>');
} else {
$sql = mysql_query("UPDATE users SET
email = '" . mres($_POST['do']) . "'
WHERE id = " .(int)$edit['id'] . "
LIMIT 1");
if ($sql) {
echo 'OK';
$logmsg = 'Changed email';
} else {
echo 'Error';
}
}
}
}
PHP function mres() escapes all the characters (for database injection protection - not really important here).
According to the situation which you explained. I would prefer you to use jqueryajax
in this Once the Post function is done you can change the value with the changed value
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg ); // portion where you can change the field value to the updated one.
});
Thanks and Regards,
Philemon Philip Kunjumon

Categories

Resources