PHP, AJAX, and server-client frustrations - javascript

I have a table that's generated from php. The way I've done this is probably not the most efficient way to do it since I wrote it all myself and I'm not an expert.
Everything starts when the user pastes part numbers into a search box on a previous page, which is then sent here to return.php under the variable lines.
return.php
$c = $_POST['c'];
if (!$_SESSION['lines']) {
$_SESSION['lines'] = $_POST['lines'];
}
$partNumber = array(); //define $partNumber as array
$x = -1;
$supplierQuery = "SELECT distinct supplier, quotePartNumber FROM allparts WHERE quotePartNumber = '$q'" ;
$supplierResult = mysqli_query($con, $supplierQuery);
foreach ($_SESSION['lines'] as $q) {
$x = $x + 1; // each time we loop through this, x++
while ($row = mysqli_fetch_array($supplierResult)) {
$partNumber[] = $row['quotePartNumber'];
$customerQuery = "SELECT DISTINCT quoteCustomer FROM $supplier where quotePartNumber = '$q'";
if (!$c) { // $c becomes set once a user types in an end customer - without that, we want ALL generic info to be returned.
$costQuery = "SELECT * FROM $supplier where quotePartNumber = '$partNumber[$x]' ORDER BY quoteCost ASC LIMIT 1" ;
} else {
$costQuery = "SELECT * FROM $supplier where quotePartNumber = '$partNumber[$x]' and quoteCustomer = '$c' ORDER BY quoteCost ASC LIMIT 1" ;
}
$getCustomer = mysqli_query($con, $customerQuery);
}
later on in my table, I have this:
<td><?= $partNumber[$x] ?></td>
<td><?= $cost ?></td>
<td>
<select class="btn btn-danger" onChange="selectCustomerCMR(this.value)">
<option value="" disabled selected><?php if($c) { print $c; } else { print "Select Purchasing Customer";} ?></option>
<?php
while ($row = mysqli_fetch_array($getCustomer)) {
$customerName = $row['quoteCustomer'];
?>
<option><?= $customerName ?></option>
<?php
}
?>
</select>
</td>
Any change to the dropdown will launch this script:
<script>
function selectCustomerCMR(str) {
var id = str;
$.ajax({
type: 'POST',
url: 'return.php',
data: {'c':id,'lines':lines},
success:function(data){
$("#info").html(data);
}
});
}
</script>
What I'm trying to do
Let's say my generated table has 3 rows, with part numbers
There is a drop-down to allow the user to select a specific customer. When the user clicks on this, the script takes that value and uses AJAX to send it back to the same page (return.php), which then grabs it using the $c = $_POST['c']; code.
My Issue
When return.php loads a "second time" with a value for $c, I don't know how to make it so that the line that the user selected gets changed. Right now, anytime I select a customer from a line's drop-down, return.php reloads, and it assigns that customer to the FIRST row, ignoring all the other rows.
I specifically created $partNumber as an array and used $x so I could increase the value of x each time the foreach loop iterated. This worked, so of the three lines in the above table, the first one is $partNumber[0] and the second one is $partNumber[1], etc... But I don't know how to get that information into the javascript function and send it back to the page when it reloads, so that I can then change my SQL query to ONLY action when the condition is right for that line...
Thanks for reading, and thanks for any help!

Consider changing your <select> code to this:
<select class="btn btn-danger" data-x="<?= $x ?>" onChange="selectCustomerCMR(this)">
Then, your Ajax code can be changed to this:
function selectCustomerCMR(select) {
var id = select.value, x = select.getAttribute("data-x");
$.ajax({
type: 'POST',
url: 'return.php',
data: { c: id, lines: lines, x: x },
success: function(data){
// Update!
}
});
}
That way, your PHP can get both c and x.

Related

Search form using ajax, php and json

i'm currently learning javascript through my school and I'm completely stuck on trying to make a search form work.
The problem I have is that I can't get it to show all results from the sql query.
The code looks like this:
$(document).ready(function(){
var searchfield = document.getElementById("searchfield");
var searchresult = document.getElementById("searchresult");
$(searchfield).on("keyup", function(){
var q = this.value;
console.log(q +"'This value'");
var str = "";
var url = "searchscript.php?q="+q;
$.ajax({
url:url,
type:'post',
dataType: 'json',
success: function(resultat){
console.log("resultatet är:" + resultat.ProduktNamn);
for(var i = 0; i < resultat.ProduktNamn.length; i++) {
str += resultat.ProduktNamn + "<br>";
}
searchresult.innerHTML = str;
}
})
});
});
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
while ($row = $resultat->fetch_assoc()) {
echo json_encode($row);
}
}
?>
As soon as the result of the query has more than 1 property, no matter how I do it it won't show any results, only when I narrow down the search so that only one product is found it shows it.
I'm new to javascript, but I'm pretty sure this has to do with the fact that the way I'm doing it on the PHP side makes it so it returns every product as a single object, not within an array or anything, so when I get the data back on the javascript side I have trouble looping through it.
So basically, say I have these products
"Banana Chiquita"
"Banana Chichi"
"Banana"
I will only get a result on the javascript side once I've written atleast "Banana chiq" in the search field so the php side only returns 1 object.
Sorry for my terrible explaination :/
Well, first you should make a 2D array and then encode it to JSON. Currently, you are writing out each record as a JSON string which will work for a single record but not for multiple records. See the corrected PHP code.
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
$rows = array();
while ($row = $resultat->fetch_assoc()) {
array_push($rows,$row);
}
echo json_encode($rows);
}
?>

On successful ajax, create a dropdown select from another table with preselected option value

For an ‘Edit’ modal, I initiate an ajax call to the php script named getSelectedMember.php that bring the information from the table items (Table 2).
<?php
require_once 'db_connect.php';
$memberId = $_POST['member_id'];
$sql = "SELECT * FROM items WHERE itemID = $memberId";
$query = $connect->query($sql);
$result = $query->fetch_assoc();
echo json_encode($result);
?>
This formulation_fk is in the table items a value of a select option from another table named formulation (Table 1).
This is code of 'edit.php' :
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text"><br>
</div>
<div>
<label>Formulation</label>
<select id="editFormulation">
</select>
</div>
<button type = "submit">Save changes</button>
</form>
My question is while updating a single item, how can I pass the select options from the formulation table in my edit form where the select option value will be the formulation_fk from the table items?
And this is my ajax call:
$.ajax({
url: 'getSelectedMember.php',
type: 'post',
data: {
member_id: itemID
},
dataType: 'json',
success: function(response) {
$("#editName").val(response.name);
$("#editFormulation").val(response.formulation_fk);
$(".editMemberModal").append( ? ? ? ? ? ? )
}
});
For clarification of my question, let's think that to edit Water, the action flow would be like this:
Click the edit button for ‘Water’.
Ajax call to getSelectedMember.php to get the name (Water) and
formulation_fk (1).
On response, Name field will output ‘Water’
and Formulation filed will output a dropdown select from
formulation table where option value = “1”
Something like this image below.
I have been trying to solve it for a while but I'll really appreciate any suggestion or expert help. Thanks in advance.
The PHP code needs to return an array of all the formulations, in addition to the formulation_fk from the items table.
$memberId = $_POST['member_id'];
$sql = "SELECT * FROM items WHERE itemID = $memberId";
$query = $connect->query($sql);
$result = $query->fetch_assoc();
$sql = "SELECT * FROM formulation";
$query = $connect->query($sql);
$formulations = array();
while ($row = $query->fetch_assoc()) {
$formulations[] = $row;
}
$result['formulations'] = $formulations;
echo json_encode($result);
Then the AJAX code can fill in the <select> before setting its value.
success: function(response) {
$("#editFormulation").empty(); // Clear out previous value
$.each(response.formulations, function() {
$("#editFormulation").append($("<option>", {
value: this.formulationID,
text: this.formulation_name
}));
});
$("#editFormulation").val(response.valuation_fk);
$("#editName").val(response.name);
}

Load More from Php Array

How is it possible to make load more from array if you scroll to the bottom of the page.
So there are only the first 5 "items" shown and if you scroll to the bottom the next 5 are shown so the browser doesnt chrashes.
My Array:
$statement = $pdo->prepare("SELECT * FROM actvt");
$statement->execute();
$users = $statement->fetchAll();
foreach($users as $row) {
echo $row("username");
}
php
function callMore(){
$last_appt = $_POST['last_result'];
$statement = $pdo->prepare("SELECT * FROM actvt WHERE date = ".$last_appt." limit = X "); //not sure your table structure , X is how many you want to load
foreach($statement as $val){
//Set your gathered results here
}
return X //return the results to your ajax call
}
js / ajax call
$.ajax({
type: 'POST',
data: {
action: 'callMore',
lastPost : XXXX //Put your last post here
},
success : function(msg){
//Do something with returned data append where ever
},
datatype: 'json',
});
From here you will need to detect when you have reached the last post... I recommend doing a detection of when you are at the bottom of the page, if you are using jquery use scrollTop on the last post, to find its Y value, and then window offset with scroll to trigger if you are close to reaching the bottom.. ONce you have reached the bottom, run your ajax function and retrieve the next results.
so you may create sth like a load.php:
$start=$_GET["page"]*100;//100 entries
$statement = $pdo->prepare("SELECT * FROM actvt ");
$statement->execute();
$users = $statement->fetchAll();
$counter=0;
foreach($users as $row) {
$counter++;
if($counter>$start && $counter <=$start+100){//100 entries
echo $row("username");
}
}
if($counter<$row.length){
echo "<a href='?page=".($page+1)."'>Next Page</a>";
}
Now you can call "http://yourpage?page=10"...
The js part is enough to fill another answer...

Change PHP variable with HTMLs <select> <option> OnChange and execute mysql query

Hi I currently have 2 < select>
The first one is filled from a button action from the page before and a database query. Depending on what you choose in the first < select>, the second < select> should get filled from a database query with the value of the first < select>. (I am using PDO prepare so I only need to change the parameter to whatever value the selected has)
I already know how I can get the values into javascript but I don't know how I can then write it into the php variable and execute the mysql query. As javascript is a client-side language, I don't think it's possible to execute the query there so I would need to get it to php somehow?
Select 1:
<select name = "select1" class = "select" size = "10" onChange = "function()">
<?php
while ($result1 = $query1->fetch(PDO::FETCH_OBJ)) {
?>
<option value = "
<?php
echo $result1->id;
?>">
<?php
echo $result1->text;
?>
</option>
<?php } ?>
</select>
Select 2:
<select name = "select2" class = "select" size = "10" onChange = "function(this.options[this.selectedIndex].value)">
<?php
while ($result2 = $query2->fetch(PDO::FETCH_OBJ)) { ?>
<option value = "
<?php
echo $result2->id . ";" . $result2->text . ";" . $result2->text2 . ";" . $result2->text3;
?>">
<?php
echo $result2->text;
?>
</option>
<?php } ?>
</select>
If you are curious, function is just displaying some divs and writing the values into some textboxes:
var str = select.split(";");
document.getElementById("div1").className = "";
document.getElementById("div2").className = "div";
document.getElementById("div3").className = "div";
document.getElementById("div4").className = "div";
document.getElementById("txt1").value = str[0];
document.getElementById("txt2").value = str[1];
document.getElementById("txt3").value = str[2];
document.getElementById("txt4").value = str[3];
php database query to fill select 1:
try {
$query1 = $db->prepare('SELECT id, text FROM tbl1 INNER JOIN tbl0 USING(id) WHERE id = ?');
$query1->execute(array($_POST['id']));
} catch(PDOException $ex) {
log_error($ex);
$arrError[] = "Error SQL 1";
}
php database query to fill select 2:
try {
$query2 = $db->prepare('SELECT id, text, text2, text3 FROM tbl1 INNER JOIN tbl2 USING(id) WHERE id = ?');
$query2->execute(array($IDFROMSELECT1));
} catch(PDOException $ex) {
log_error($ex);
$arrError[] = "Error SQL 2";
}
How can I get the id (option value) from select 1 into the $IDFROMSELECT1 variable in php mysql query 2?
Any tips are much appreciated!
You will have to use AJAX to send the value of the select box to a PHP script which will run the query and send back the result. AJAX is easiest done with the jQuery library.
The javascript to run in onchange() would be something like this:
var selectedValue = $(this).val();
$.ajax({url: "getData.php",
type: "POST",
dataType: "json",
data: {id: selectedValue},
success: function(returnedData) {
//do something here with returned data
}
});
In the PHP script (getData.php), you would execute your select like normal, put the results into an array, then return that array as JSON (Javascript Object Notation). This will put the results of the query into a format that you can work with in javascript (in this case, adding the returned results to another select box)
$json = json_encode($returnArray);
echo $json;

Pass PHP variable to ajax and run PHP function based on that variable

I have Database records which are loop echoes out, so it lists down in Divs each records info.
I'm trying to make a delete button, to delete the specific record from this page view. The loop number tracker variable $i also corresponds to the record ID, so loop 3 outputs a div containing the info of record ID 3.
So I just need to on click pass $i to a PHP function to then run the sql to drop the record with ID $i.
I'd like to do this all on the same page so I'm assuming I need ajax but thats where I get stumped. Also so I can have an alert "Are you sure" I've done ajax with jquery to ajax to php, but never this way.
PHP:
$webserver = 'localhost';
$administrator = 'root';
$password = '';
$db_name = 'cdb';
$db = mysqli_connect($webserver, $administrator, $password, $db_name)
or die('Error connecting');
if( isset($_REQUEST['page']))
{
$_SESSION['page'] = $_REQUEST['page'];
}
else
{
$_SESSION['page'] = 1;
}
$records_per_page = 8;
$query = " SELECT *
FROM cars, users
WHERE cars.dealerID = users.dealerID
AND users.username = '".$_GET['username']."'";
$result = mysqli_query($db, $query)
or die("Error in query: '$query'");
$row = mysqli_fetch_assoc($result);
$i = 1;
$start = ($_SESSION['page'] - 1) * $records_per_page;
$end = ($_SESSION['page']) * $records_per_page;
while($row = mysqli_fetch_assoc($result) and $i < $end)
{
$i++;
if( $i > $start )
{
<div>
delete
</div>
<div of magic n' fairies>
echo $row['informationandstuff'];
</div>
}
}
Delete function:
function deleteCar()
{
$delete = "DELETE FROM cars
WHERE carindex = '".$i"'";
}
I could post $i to another file and do it bt would prefer to keep to same page and allow for an are you sure js pop up.
If I'm understanding you correctly, one way to do this would be to store the $i variable in either an html data attribute, or an id (as you suggested). Then, use jquery to collect that id and pass it to the data property in the ajax call.
Sample list item (I'm assuming a heredoc here):
<div class="list-item" data-record-id="{$yourId}">your output</div>
Now, collect the id that the user clicked:
$('.list-item').click(function(){
//get item id
var recordId = $(this).data('record-id');
deleteRecord(recordId);
});
function deleteRecord(recordId) {
var recordData = 'recordId=' + recordId;
var request = $.ajax({
type: "post",
url: "the-php-page-you-use-for-async-calls",
data: recordData,
success: function(resp){
//show some validation that the record has been deleted
}
});
}

Categories