Forum Moderators: coopster

Message Too Old, No Replies

Passing multiple variable to AJAX

         

SeanF

12:54 pm on Oct 12, 2020 (gmt 0)

5+ Year Member Top Contributors Of The Month



I have a php file which I now have passing a variable to an Ajax script which will then execute a MySQL call based on the variable passed. The call to the Ajax script is triggered when a change is made to a <select> field. When a change is made the value of the <select> field is passed to Ajax which gets the data record from the database, displays it on the screen, makes an arbitrary change to a data field and updates the record. So far, it's just a proof of concept to show that I can manipulate the database through Ajax... and it works.

Now, I am trying to figure out how to pass two (or more) variables to Ajax so I can update the record determined by a record_id (passed from the <select> field), with another value determined by the script.

What I have so far:
In the main script:
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
...
echo "
<form>
<select name='users' onchange='showUser(this.value)'>
<option value=''>Select a person:</option>
";
$sql = "select *
from companies
order by company_name";
$result = query($sql,$conn) or die(mysql_error());

while($newArray = fetch_array($result)){
$company_id = $newArray['company_id'];
$company_name = stripslashes($newArray['company_name']);
echo "<option value='$company_id'>$company_name</option>";
}
echo "
</select>
</form>
";


getuser.php:

$sql="SELECT * FROM companies WHERE company_id = '".$q."'";
$result = query($sql,$conn) or die(mysql_error());

echo "<table>
<tr>
<th>Company</th>
<th>State</th>
</tr>";
// while($newArray = fetch_array($result)){
while($row = fetch_array($result)) {

echo "<tr>";
echo "<td>" . $row['company_name'] . "</td>";
echo "<td>" . $row['company_state'] . "</td>";
echo "</tr>";
}
echo "</table>";
$new_name = "aaaa_". $company_name;
$sql="UPDATE pbs_companies SET company_name = '$new_name' WHERE company_id = '".$q."'";
echo "SQL: $sql<br/>";
$result = query($sql,$conn) or die(mysql_error());


This all works as expected. What I am wondering about is: how do I pass a variable (or multiple variables) to manipulate the data, i.e. instead of the hard-coded "aaaa_"

Thanks

NickMNS

4:02 pm on Oct 12, 2020 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have a php file which I now have passing a variable to an Ajax script

Typically it is not a good practice to pass variable directly from php to javascript. Bassically your javascript script should be free of any php code. This makes it easier to maintain and it allows you to keep the js in a separate file that be easily be cached.

So how do you do it? There are various means, you can "hide" the data in hidden form fields. Ideally you can add the data to a relevant element on the page, possibly as the value of the id attribute or you can also use "data-" attribute, that you can name to meet your needs, eg: data-user="seanF".

Once the data is on the page, the rest is straight forward. Get the data by selecting the elements and then add all the data to FormData object. Initiate all this using onChange event.


const mySelect = document.querySelector('#mySelect');
mySelect.addEventListener('change', function(event) {
const selection = event.target.value;
const user = document.querySelector('#someDiv').getAttribute('data-user');
const other = document.querySelector('#otherDiv').id;
const formData = new FormData;
formData.append('selection', selection);
formData.append('user', user);
formData.append('otherInfo', other);
// AJAX POST request here...
// note: I use es6 const syntax, this can be replaced with var.
}


Note with the above I changed your example from a Get request to a Post request which is need to submit a form. Post is more secure and is the http method intended to be used for submitting data. That said you can submit a Get request but the instead of submitting a form the data would need to be serialized into query paramters.

Other note: above I say "hide" the data in a hidden form field, hide in this case means it does not appear on the page, but it is not actually hidden in a secure fashion, actually it is not hidden at all, the field and it's value appear in plain text in the code of the page, anyone can see by clicking view-source.