get post data in a php page called by ajax - javascript

I have called the page search.php from ajax:
function search(){
var title=$("#search").val();
if(title!=""){
$.ajax({
type:"post",
url:"search.php",
data:"title="+title+"&idTratta="+<?php echo $idTratta ?>,
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
}
}
Now in search.php I get the result of a query in a html table and I created radio buttons in a form that when each form is submitted I get the value of the radio button's clicked and update a row in the db:
$title = $_POST["title"];
$idTratta = $_POST["idTratta"];
$SimpleUsers = new SimpleUsers();
$users = $SimpleUsers -> searchUser($title, $idTratta);
foreach ($users as $user) :
echo "<tr>
<td>" . $user["nome"] . "</td>
<td>" . $user["role"] . "</td>
<td class='right'><form action='' method='post'><label>
<input type='radio' name=" . $user["nome"] . " id='c' value='1' ";
if ($user["role"] == 'configuratore')
echo "checked='checked' />C</label>";
else
echo "/>C</label>";
echo "<label>
<input type='radio' name=" . $user["nome"] . " id='va' value='2' ";
if ($user["role"] == 'visualizzatore avanzato')
echo "checked='checked' />VA</label>";
else
echo "/>VA</label>";
echo "<label>
<input type='radio' name=" . $user["nome"] . " id='v' value='3' ";
if ($user["role"] == 'visualizzatore')
echo "checked='checked' />V </label>";
else
echo "/>V </label>";
echo "<input type= 'submit' name='sub_" . $user["nome"] . "'value='Cambia'/></form></td>
</tr>";
$sub = 'sub_';
if ($_POST[$sub . '' . $user["nome"]]) {
$permission = $_POST[$user["nome"]];
$SimpleUsers -> updateUserPermission($user["nome"], $idTratta, $permission);
}
endforeach;
The problem is that in search.php I am unable to catch POST variables, how I can get it?
EDIT
This is the piece of code which doesn't work:
if ($_POST[$sub . '' . $user["nome"]]) {
$permission = $_POST[$user["nome"]];
$SimpleUsers -> updateUserPermission($user["nome"], $idTratta, $permission);
}

The data shouldn't be parsed as text but instead as an js array like this:
data: {title: title, idTratta : <?php echo $idTratta ?>},
EDIT:
A example for sending the form data would be:
var formData = JSON.stringify($("#myForm").serializeArray());
formData['idTratta'] = <?php echo $idTratta ?>;
$.ajax({
type:"post",
url:"search.php",
data:formData,
success:function(data){
$("#result").html(data);
$("#search").val("");
}
});
And than using json_decode in your php form to turn it into a PHP array again. Its kind of dirty but it should work

Try this method
$.post("`search.php`", { title : title , idTratta : '<?php echo $idTratta ?>'},
function (data) {
$("`#result`").html(data);
$("`#search`").val("");
});

Related

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

Using AJAX to pass variable from dynamic html table to php updating query

I want to add a value in the input text valor and assign this value to the row where it is, for this I need pass to the update query ID and the valor.
What am I doing wrong?
Table
<?php
$IDTipoEquipamento = $_POST['Car'];
$result = mysqli_query($conn,"SELECT tipocaracteristicas.IDTipoCaracteristicas,tipoequipamento.TipoEquipamento, caracteristicas.Caracteristica, Valor FROM `tipocaracteristicas` LEFT JOIN tipoequipamento on tipoequipamento.IDTipoEquipamento= tipocaracteristicas.IDTipoEquipamento LEFT JOIN caracteristicas on caracteristicas.IDCaracteristicas=tipocaracteristicas.IDCaraterisiticas WHERE tipocaracteristicas.IDTipoEquipamento= '$IDTipoEquipamento';");
echo "<table width='100% class='sortable' id='datatables-example'>
<tr>
</tr>
<tr>
<td class='pure-table'></td>
<td class='pure-table'><b>Tipo de Equipamento</b></td>
<td class='pure-table'><b>Caracteristica</b></td>
<td class='pure-table'><b>Valor</b></td>
<td class='pure-table'><b>Atribuir</b></td>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tbody data-link='row' class='rowlink'>";
echo "<tr>";
echo "<td><input type='text' name='IDTipoCaracteristicas' id='IDTipoCaracteristicas' value='". $row['IDTipoCaracteristicas'] . "'></td>";
echo "<td>" . $row['TipoEquipamento'] . "</td>";
echo "<td>" . $row['Caracteristica'] . "</td>";
echo "<td><input type='text' name='valor' id='valor' value=''></td>";
echo "<td><a href='' onclick='UpdateTable()'><img id='img' src='save_icon.gif'/></a></td>";
echo "</tr>";
echo "</tbody>";
}
echo"<br>";
echo "</table>";
mysqli_close($conn);
}
?>
Jquery + Ajax
<script type="text/javascript">
function UpdateTable() {
$("#valor").on('input', function() {
var valor = $(this).val();
$.ajax({
url: 'insertCharacteristicsEquipment.php',
type: "POST",
cache:false,
data:{valor:valor},
async: false,
dataType:'html',
success:function(data) {
$("#valor").html(data);
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
$("#IDTipoCaracteristicas").on('input', function(){
var IDTipoCaracteristicas = $(this).val();
$.ajax({
url: 'insertCharacteristicsEquipment.php',
type: "POST",
cache:false,
data:{IDTipoCaracteristicas:IDTipoCaracteristicas},
async: false,
dataType:'html',
success:function(data) {
$("#IDTipoCaracteristicas").html(data);
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
}
</script>
PHP UPDATE QUERY PAGE
<?php
include ('conetar.php');
if(isset($_POST['valor'], $_POST['IDTipoCaracteristicas'])){
$valor = $_POST['valor'];
$IDTipoCaracteristicas= $_POST['IDTipoCaracteristicas'];
$sql = "UPDATE `tipocaracteristicas` SET `Valor`='$valor' WHERE `IDTipoCaracteristicas`= '$IDTipoCaracteristicas'";
if(mysqli_query($conn,$sql)){
} else{
echo "ERROR: Could not able to execute $sql. ";
}
mysqli_close($conn)
}
?>
See the below two statements here,
echo "<td><input type='text' name='IDTipoCaracteristicas' id='IDTipoCaracteristicas' value='". $row['IDTipoCaracteristicas'] . "'></td>";
^^^^^^^^^^^^^^^^^^^^^^^^^
and
echo "<td><input type='text' name='valor' id='valor' value=''></td>";
^^^^^^^^^ ^^^^^^^^
You're assigning the same id for all of your table rows, use class instead. Assign class to each of your IDTipoCaracteristicas, Valor input elements as well as to the update table hyperlinks. Furthermore, you didn't assign any value in Valor input element. Also, make the anchor tags non-linkable using javascript:void(0);, otherwise you'll get redirected every time you click on a link. So your while() loop should be like this:
while($row = mysqli_fetch_array($result)) {
echo "<tbody data-link='row' class='rowlink'>";
echo "<tr>";
echo "<td><input type='text' name='IDTipoCaracteristicas' class='IDTipoCaracteristicas' value='". $row['IDTipoCaracteristicas'] . "'></td>";
echo "<td>" . $row['TipoEquipamento'] . "</td>";
echo "<td>" . $row['Caracteristica'] . "</td>";
echo "<td><input type='text' name='valor' class='valor' value='". $row['Valor'] ."'></td>";
echo "<td><a href='javascript:void(0);' class='updateTable'><img id='img' src='save_icon.gif'/></a></td>";
echo "</tr>";
echo "</tbody>";
}
Subsequently, your jQuery/AJAX code should be like this:
<script>
$(document).ready(function(){
$(document).on('click', '.updateTable', function(){
var IDTipoCaracteristicas = $(this).parents('tr').find('.IDTipoCaracteristicas').val();
var valor = $(this).parents('tr').find('.valor').val();
$.ajax({
url: 'insertCharacteristicsEquipment.php',
type: "POST",
cache:false,
data:{valor:valor, IDTipoCaracteristicas: IDTipoCaracteristicas},
async: false,
success:function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
</script>

Not receiving dynamically generated form data

i am creating a form through php html and ajax that is specific for each row of a database table. I send the form data through ajax to another page which then takes that form data and uses it to pull data from another database based upon the results given and displays them.
I am fairly sure the problem is either with my select statement on the recipedisplay.php page or my syntax is wrong on how to echo out a returned variable.
select.php
<?php <script>
$('.button').click(function (e){
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'pages/recipes/recipedisplay.php',
data: $('#f'+id).serialize(),
success: function(d){
$('#infodisplay').html(d);
}
});
});
</script>
<div id=\"a".$row['id']."\">
<form id=\"f" . $row['id'] . "\">
<input type=\"hidden\" name=\"recipeid\" id=\"recipeid\" value=\"" . $row['id'] . "\">
<div id=\"reciperesultbutton\" class=\"button\"><div id=\"centering\">" . $row['name'] ." </div></div>
<div id=\"reciperesulttext\"> " . $row['id'] ." " . $row['longdesc'] ."</div>
</form>
<br>
</div>
";
}
?>
recipedisplay.php
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$id = mysqli_real_escape_string($con, $_POST['recipeid']);
$sql= "SELECT * FROM recipes WHERE 'id' ='".$id."'";
$row = mysqli_fetch_array($sql);
$name = $row['name'];
$longdesc = $row['longdesc'];
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
echo " fail ";
echo " . $name . ";
};
echo " . $id . ";
echo " work ";
echo " . $longdesc . ";
echo "$row[name]";
mysqli_close($con);
?>
The problem is in :
$row = mysqli_fetch_array($sql);
because mysqli_fetch_array() takes mysqli_query() result not your $sql query
So try to run your query first by this code :
mysqli_query($con,$sql);
$row = mysqli_fetch_array($mysqli_query);
Also you can use mysqli_fetch_assoc() that takes mysqli_query() too as a parameter

How do I post a radio button and menu selection with ajax and json

I've found several articles on this but nothing that fits my circumstance. I have these radio buttons and drop down menu from which I need to post a selection using ajax in json dataType. Simply put, what do I put in the "WHAT GOES HERE" spot?
Thanks in advance!
<script>
$(function() {
$('#driver').click(function(){
$.ajax({
url:'_resources/_helpers/grader-test.php',
type: "POST",
data:{ /*WHAT GOES HERE?????*/ },//<---WHAT GOES HERE??
dataType: "json",
success: function(result){
$('#jsonstuff').html(result);
console.log(result[0].AVG);
$('#grade').html(result[0].AVG);
}
});
});
});
</script>
<td>
Select:
<select id="extension">
<option value="empty"></option>
<? foreach ($sql as $row){
echo '<option value = "' . $row['extension'] . '">' . $row["tech_fname"] . ' ' . $row["tech_lname"] . ' - ' . $row['extension'] . '</option>';
?>
</select>
</td>
<td>
As Reviewer<input type="radio" class="as_type" name="as_type" value="reviewer"/><br />
As Reviewed<input type="radio" class="as_type" name="as_type" value="reviewed"/>
<input type="button" id="driver" value="Submit" />
</td>
<td id="grade"></td>
And here is grader-test.php:
$ext = $_POST['extension'];// 2752;//
$type = $_POST['as_type'];// "reviewer";//
switch($type){
case "reviewer":
$dbh = new PDO('mysql:host=;dbname=', '', '');
$sql = "SELECT AVG(grade_average) AS AVG from call_reviews WHERE reviewer_ext = :ext";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ext',$ext);
$stmt->execute();
$average = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($average);
break;
case "reviewed":
$dbh = new PDO('mysql:host=;dbname=', '', '');
$sql = "SELECT AVG(grade_average) AS AVG from call_reviews WHERE reviewed_ext = :ext";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ext',$ext);
$stmt->execute();
$average = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($average);
break;
default:
echo "select something";
}

update_multiple_rows using ajax and php

please in need help in updating multiple rows based on dynamic data fetched from mysql database. I have implemented this using $_Post to udate.php file, but how can i do this using ajax.
//THIS SCRIPT FETCH FROM DATABASE
<body>
<?php
mysql_connect("localhost","root","");
mysql_select_db("student") or die("Unable to select database");
$sql = "SELECT * FROM students ORDER BY id";
$result = mysql_query($sql) or die($sql."<br/><br/>".mysql_error());
$i = 0;
echo '<table width="50%">';
echo '<tr>';
echo '<td>ID</td>';
echo '<td>Name</td>';
echo '<td>Address</td>';
echo '</tr>';
echo "<form name='form_update' method='post' action='update.php'>\n";
while ($students = mysql_fetch_array($result)) {
echo '<tr>';
echo "<td>{$students['id']}<input type='hidden' name='id[$i]'value='{$students['id']}' /></td>";
echo "<td>{$students['name']}</td>";
echo "<td><input type='text' size='40' name='address[$i]' value='{$students['address']}' /></td>";
echo '</tr>';
++$i;
}
echo '<tr>';
echo "<td><input type='submit' value='submit' /></td>";
echo '</tr>';
echo "</form>";
echo '</table>';
echo $i; ?>
</body>
// HERE IS THE UPDATE SCRIPT
// On clicking submit all rows are updated but i still cant achieve dis with ajax.
UPDATE.PHP
$size = count($_POST['address']);
$i = 0;
while ($i < $size) {
$address= $_POST['address'][$i];
$id = $_POST['id'][$i];
$query = "UPDATE students SET address = '$address' WHERE id = '$id' LIMIT 1";
mysql_query($query) or die ("Error in query: $query");
echo "$address<br /><br /><em>Updated!</em><br /><br />";
++$i;
}
?>
HERE IS WHAT I HAVE TRIED ON AJAX
function update(){
var j=0;
while(j< <?php echo $i ; ?>){
var id=$("#id" + j);
var address=$("#address" + j);
$.ajax(
{
url:"update.php",
type:"post",
data:{id:id.val(),address:address.val()},
success:function(response)
{
}
});
}
ANY HELP WILL BE APPRECIATED
You shouldn't need to loop and execute multiple POSTs. Simply serialize the form data and send it to the script, e.g.:
$.ajax({
url: 'update.php',
type: 'post',
data: $('#your-form-id').serialize(),
success:function(response){
// do something
}
});
Also, you should consider revising your PHP to prevent SQL injection: How can I prevent SQL injection in PHP?

Categories

Resources