Ironank Ironank - 4 months ago 14
PHP Question

How to get variable value and pass it on to AJAX url

Here is my code:

function download () {
var val1 = $('#id').val();
var val2 = $('#user').val();
var url = "includes/downloads.php?id=";
$.ajax({
url: url,
type: "POST",
data: { id: val1, user: val2 },
error:function(){
alert('Error!');
}
});


}

The only issue is that I want to pass the "
val1
" value to the URL so I can process it on my downloads.php page because I have multiple items in a loop, so I'm trying to figure out how to pass the ID. For some reason, it keeps passing the first item in my loop only.

This is inside my loop:

echo '<input type="hidden" id="id" value="'.$row['id'].'">';
echo '<input type="hidden" id="user" value="'.$user.'">';
echo '<div class="download" onclick="download()"><a href="'.$row['filename'].'.zip">download</a></div>';


How can I do that?

EDIT:

downloads.php page:

$id = $_POST['id'];
$user = $_POST['user'];

// insert query

Answer

Your all code is fine. Just one thing to change. Note all fields defined in data will be posted to the URL as type u defined. U can choose type either as post or get.Just assign URL in url no need to pass id with it, this will automatically go in data.

  function download (a) {
  var val1 = $('#id'+a).val();
 var val2 = $('#user'+a).val();
 var url = "includes/downloads.php";
  $.ajax({
  url: url, 
  type: "POST", 
  data: { 'id' : val1, 'user' : val2 },
  error:function(){
  alert('Error!');
    }
  });


  echo '<input type="hidden" id="id.$i." value="'.$row['id'].'">';
  echo '<input type="hidden" id="user.$i." value="'.$user.'">';
  echo '<div class="download" onclick="download(.$i.)"><a href="'.$row['filename'].'.zip">download</a></div>';
Comments