prithivraj prithivraj - 6 months ago 22
PHP Question

I need to call a javascript or jquery from php

I need to refresh the page and also populate the second drop down according to the value selected in the first drop down.


  1. In PHP I select the drop down value. It calls Javascript function reloadproject() and reloads the page with the current value.

  2. Then I get the value of project id using $_GET.

  3. After reloading I need to call the function getblock(val) using the project id I got using $_GET and populate the second drop down I have.





function reloadproject(val) {
window.location = 'market?id=' + val;
}

function getblock(val) {
$.ajax({
type: "POST",
url: "list_flat_view_dd.php",
data: 'project_id=' + val,
success: function(data) {
$("#block-list").html(data);
}
});
}

function getflat(val) {
$.ajax({
type: "POST",
url: "list_flat_view_dd.php",
data: 'block_id=' + val,
success: function(data) {
$("#flat-list").html(data);
}
});
}

<div class="col-sm-3">
<select name="project" style="width: 100%;" id="project-list" class="form-control select2"
onChange="reloadproject(this.value);">
<option value="all">Select</option>
<?php while ( $project=m ysqli_fetch_array ( $results_project ) ) { ?>
<option value="<?php echo $project[" id "]; ?>"<?php if(isset($_GET[ 'id'])){if($project[ "id"]==$ filter_project_id){ ?>selected="selected"
<?php }} ?>>
<?php echo $project[ "name"]; ?>
</option>
<?php } ?>
</select>
<?php if(isset($_GET[ 'id'])){ ?>
<input type="hidden" name="filter_project_id" id="filter_project_id" value="<?php echo $filter_project_id; ?>">
<?php } ?>
</div>

<div class="col-sm-3">
<select name="block" style="width: 100%;" id="block-list" class="form-control select2" onChange="getflat(this.value);">
<option value="all">Select</option>
</select>
</div>

<div class="col-sm-3">
<select name="flat" style="width: 100%;" id="flat-list" class="form-control select2" onChange="">
<option value="all">Select</option>
</select>
</div>




Answer

Have you tried to use 'document ready' to call your 'getblock' function?:

PHP runs first: print the code in your document, and after that, with jQuery $(document).ready() you know that the document is printed and you already have your hidden input with the GET['id'] value:

<input type="hidden" name="filter_project_id" id="filter_project_id" value="<?php echo $filter_project_id; ?>">

And your script:

$(document).ready(function() {

    if ($('#filter_project_id').val().length) {
         getblock($('#filter_project_id').val());
    }

});
Comments