Hi everyone i’m new to Ajax,i’m using ajax to get values from my database in form of an object array from a separate PHP file and displaying them in a table,everything works fine,but i want to create a link and append the ID obtained from the array so that i can send a GET request to another PHP file which will act upon that particular row.
code for the PHP File
<?php
include 'Module/Credentials.php';
$sql="SELECT * FROM queries";
$query= mysqli_query($connection, $sql) or die(mysqli_error($connection));
$data = array();
while ($row = mysqli_fetch_object($query))
{
array_push($data, $row);
}
echo json_encode($data);
`
Ajax code
javascript
` var ajax=new XMLHttpRequest();
var method="GET";
var url="getMessages.php";
var asynchronous=true;
ajax.open(method, url,asynchronous);
ajax.send();
ajax.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
var data=JSON.parse(this.responseText);
console.log(data);
var html="";
for(var b=0;b<data.length;b++){
var ID=data[b].ID;
var name=data[b].name;
var email=data[b].email;
var subject=data[b].subject;
var message=data[b].message;
var link = "management.php?delete=";
$(document).ready(function(){
$('.link').attr('href', link+ID);
});
console.log(data.length);
html +="<tr>";
html +="<td>"+"<a class='link' href=''>Delete</a>"+"</td>";
html +="<td>" + name + "</td>";
html +="<td>" + email + "</td>";
html +="<td>" + subject + "</td>";
html +="<td>" + message + "</td>";
html +="</tr>";
}
document.getElementById("messages").innerHTML += html;
}
}`
the ID on the link is not changing its just displaying a single ID=6
Solution
` var ajax=new XMLHttpRequest();
var method="GET";
var url="getMessages.php";
var asynchronous=true;
ajax.open(method, url,asynchronous);
ajax.send();
ajax.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
var data=JSON.parse(this.responseText);
console.log(data);
var html="";
for(var b=0;b<data.length;b++){
var ID=data[b].ID;
var name=data[b].name;
var email=data[b].email;
var subject=data[b].subject;
var message=data[b].message;
var link = `management.php?delete=${ID}`;
html +="<tr>";
html +=`<td><a href='${link}'>Delete</a></td>`;
html +="<td>" + name + "</td>";
html +="<td>" + email + "</td>";
html +="<td>" + subject + "</td>";
html +="<td>" + message + "</td>";
html +="</tr>";
}
document.getElementById("messages").innerHTML += html;
}
}`
but i'm getting error messages in NetBeans IDE 8.0.2 like
Expected an operand but found error
`var link== `management.php?delete=${ID}`;`
Expected an operand but found error
`html +=`<td><a href='${link}'>Delete</a></td>`;`
Expected eof but found error ` }`
2
Answers
Try a Template Literal like so:
And if you want it on the
html
Please note that I’m using the back ticks `
More info here
Before selecting a HTML element you have to create it. After creation you can manipulate.