Amir Hesari Amir Hesari - 2 months ago 9
Javascript Question

How to use variable in function after load PHP file in jQuery?

How to use variable "hotel" after load

step-02.php
file?

$(function () {
var hotel = [];
$('#forPrice').on('click', function() {
$('select').each(function() {
if($(this).val() > 0 && $(this).val() < 10) {
var room = {};
room["room"] = $(this).attr('room');
room["price"] = $(this).attr('price');
room["val"] = $(this).val();
room["html"] = $(this).parents(".selectRowRoom").html();

hotel.push(room);
}
});
console.log(hotel);
});

$('#forPrice').click(function () {
$('#Step-01').hide();
$('#Step-02').show();
$('.hiddenAndShow').hide();
$( "#Step-02" ).load( 'step_02.php' );
});
})


I need


room["html"] = $(this).parents(".selectRowRoom").html();


to show after loading step-02.php.

step-02.php
:

<div class="thisRoom">
// Insert room["html"] = $(this).parents(".selectRowRoom").html();
</div>

Answer

jQuery load() is a shortcut for $.ajax, which is asynchronous, you have to wait for the result to be able to access it.

Luckily load() has a callback that fires when the content is inserted and ready for accessing

$(function() {
    var hotel = [];
    $('#forPrice').on('click', function() {
        $('select').each(function() {
            if ($(this).val() > 0 && $(this).val() < 10) {
                var room = {};
                room["room"] = $(this).attr('room');
                room["price"] = $(this).attr('price');
                room["val"] = $(this).val();
                room["html"] = $(this).parents(".selectRowRoom").html();

                hotel.push(room);
            }
        });
        console.log(hotel);
    });

    $('#forPrice').click(function() {
        $('#Step-01').hide();
        $('#Step-02').show();
        $('.hiddenAndShow').hide();
        $("#Step-02").load('step_02.php', function() { // callback here
            $("#Step-02").find('.thisRoom').html(JSON.stringify(hotel));
        });
    });
});