简体   繁体   中英

How to receive AJAX (json) response in a divs with same class name individually?

I've been getting crazier day after day with this, I can't find an answer, I've spent like 100h+ with this... I hope someone could help me out!

UPDATE: So to make myself more clear on this issue and be able to get help from others, I basically have 3 containers named "main-container" they all have 3 containers as childs all with the same class name, and when I submit the button, I trigger an ajax function to load the JSON strings comming from php into the child divs, the problem is that I get the 3 "main_containers" to load the ajax at the same time, I only want to load the ajax if I press the button of each "main_container" individually.

I've been using jquery and vanilla JS as well but seems I just can't get it done!

This is how I currently trigger the button with jquery:

$('.trigger_button_inside_divs').click(my_ajax_function);

And this is how my ajax looks like:

function my_ajax_function(){
$.ajax({
        dataType: "JSON",
        type: 'POST',
        url: test.php,
        success: function(data) {

     $('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
     $('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
     $('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);

        }
    });
}

HTML looks like this:

<div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>



<div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>



<div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>

So in conclusion, each of those 6 "divs" has a button that triggers an function containing my ajax to render inside that particular div. But what I get is that every time I click that triggering button, I get the ajax to render in all of the 6 divs, instead of render on each particular div only when I click its particular button.

Thanks a lot people, I really hope to get this done! Cheers.

PD: This is something a programmer did to achieve what I'm trying to achieve but I just can't figure out what in this code is that is making possible clicking 1 button and affect THAT html element , even though they all have the same class.

(function(){
$("form input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});



var xhr = new XMLHttpRequest();
var el;




function SetDataInTheForm()
{
    var resp = JSON.parse(xhr.response)
    var pt=0
    var ct=0
    var gt=0

    Array.prototype.forEach.call(el.querySelectorAll(".test"),function(e,i){
        e.innerHTML=resp[i].name
    })
    Array.prototype.forEach.call(el.querySelectorAll(".p"),function(e,i){
        e.innerHTML=parseFloat(resp[i].p).toFixed(0)
        pt+=parseFloat(resp[i].p)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".c"),function(e,i){
        e.innerHTML=parseFloat(resp[i].c).toFixed(0)
        ct+=parseFloat(resp[i].c)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".g"),function(e,i){
        e.innerHTML=parseFloat(resp[i].g).toFixed(0)
        gt+=parseFloat(resp[i].g)
    })


    el.querySelector(".wtp").innerHTML=parseFloat(resp[0].total).toFixed(0)+" "+resp[0].unit
    el.querySelector(".wtc").innerHTML=parseFloat(resp[1].total).toFixed(0)+" "+resp[1].unit
    el.querySelector(".wtg").innerHTML=parseFloat(resp[2].total).toFixed(0)+" "+resp[2].unit

    el.querySelector(".pt").innerHTML=pt.toFixed(0)
    el.querySelector(".ct").innerHTML=ct.toFixed(0)
    el.querySelector(".gt").innerHTML=gt.toFixed(0)
}




function HandleSubmit(e)
{
    el=e.currentTarget
    e.preventDefault();
    xhr.open("POST","/url_here.php",true)
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
    xhr.onload=SetDataInTheForm
    var button=e.currentTarget.querySelector("input[type=submit][clicked=true]")
    button.removeAttribute("clicked")
    xhr.send($("#"+e.currentTarget.id).serialize()+"&"+button.getAttribute("name")+"=on")
}



[].forEach.call(document.querySelectorAll("._form_"),function(form){
    form.addEventListener("submit",HandleSubmit,false);
})


})()

Remember that $('.div_container_to_render_JSON') is a new selector that selects all elements with a class div_container_to_render_JSON . What you want to happen is figuring out where that click came from, and find the corresponding div_container_to_render_JSON .

Luckily for you, a jQuery click handler sets the this keyword to the HTMLElement where the click was captured. You can use this to get the parent element.

$('.your-button').on('click', function () {
  const myButton = $(this);

  $.ajax({
    // ...
    success (data) {
      myButton.parent().html(data.PHP_JSON_RECEIVED);

      // or if you need to find a parent further up in the chain
      // myButton.parents('.div_container_to_render_JSON').html(data.PHP_JSON_RECEIVED);
    }
  });
});

The problem is that your class selector is indeed selecting all your divs at the same time.

Solution, set identifiers for your divs as such:

<div class="my_div" id="my_div_1">

and then you can use those id's to fill in the data:

$('#my_div_1').html(data.PHP_JSON_1_RECEIVED);

and repeat for your 6 divs (notice the change from class selector '.' to identifier selector '#')

Thanks for the replies people. I finally figured it out after days of hard work, it was something really simple.. here's the answer:

$('.trigger_button_inside_divs').click(my_ajax_function);


var thisButton = $(this);
var thisDiv = thisButton.closest(".main_container"); 




 function my_ajax_function(){
$.ajax({
        dataType: "JSON",
        type: 'POST',
        url: test.php,
        success: function(data) {

     thisDiv.find('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
     thisDiv.find('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
     thisDiv.find('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);

        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM