Call Ajax function from PHP foreach with form

2019-06-08 17:47发布

问题:

i have a little Problem here. I want to call an Ajax function from a PHP foreach Loop Here is my code:

Ajax:

 function ajaxFunction(){
 var ajaxRequest;  // The variable that makes Ajax possible!

 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
 // Create a function that will receive data 
 // sent from the server and will update
 // div section in the same page.
 ajaxRequest.onreadystatechange = function(){
   if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('ajaxDiv');
      ajaxDisplay.innerHTML = ajaxRequest.responseText;
   }
 }
 // Now get the value from user and pass it to
 // server script.
 var bla = document.getElementById('bla').value;
 var queryString = "?bla=" + bla;
 ajaxRequest.open("GET", "ajax-example.php" + 
                              queryString, true);
 ajaxRequest.send(null); 
}

And the php code:

foreach ($data AS $key => $value){
    <form name="myForm">
    <input type="text" id="bla" name="bla" value="<?php echo $value['bla']; ?>">
    <input type="button" onclick="ajaxFunction(<?php echo $value['id']; ?>)" value="Speichern">
    </form>
}

The Problem: when I click the several buttons generated in the foreach loop only the first result of the foreach loop appears in the output.. I think I have to commit the individual ID from the foreach loop (from database) to the Ajax function but I dont know how to do this.

Maybe call the function like this? function ajaxFunction(id) ?!

回答1:

Within your PHP foreach loop, you're assigning the same ID to each of your text inputs. When you call getElementById(), it will always return the first element with that ID within the DOM and the variable "bla" will be assigned the value attribute of that first element.

It looks like you may have been trying to pass in an ID into the ajaxFunction call within the onclick attribute, so perhaps you could do the following:

1) Place the same echo statement within the text input's id attribute.

<input type="text" id="<?php echo $value['id']; ?>" name="bla" value="<?php echo $value['bla']; ?>">

2) Add a parameter to the ajaxFunction definition.

function ajaxFunction(requestedID){

3) And pass that variable into the getElementById call.

var bla = document.getElementById(requestedID).value;