javascript waiting php to complete function and re

2020-04-21 05:10发布

I have following case:

  1. I have drop down menu from where I select currency for a website and trigger javascript function changecurrency() using onchange event
  2. With changecurrency() function using jquery I'm trigger php file in order to update session variable based on dropdown selected value
  3. I need to refresh page to calculate correct prices based on selected currency

Everything works fine till last point as page refreshing does not working as expected... I recognized that javascript is refreshing page before php function to update session variables is completed. I tried to use callback function to tell javascript to wait php to complete server work but without success. Code is as follow:

HTML:

<select id='selectcurrency' onchange='changecurrency()'>
    <option value='1' selected >RUB</option>
    <option value='2' >USD</option>
    <option value='3' >EURO</option>
    <option value='4' >GBP</option>
    <option value='5' >TRY</option>
</select>   

echo "<div id='div_session_write'> </div>";

Javascript:

function changecurrency(){
        updatesesion(function() {
        var url      = window.location.href;
        window.location.href = url;
    });    
}

function updatesesion(_callback){
    var myselect = document.getElementById("selectcurrency");
    var x =(myselect.options[myselect.selectedIndex].value);
    jQuery('#div_session_write').load('update_currency.php?val=' + x );
    _callback();    
}

PHP file "update_currency.php" to update session variable

ob_start();
session_name ("Mysite");
session_set_cookie_params (0,"/","mysite.com",false, true);    
session_start();   

if (isset($_GET['val'])) {
    $_SESSION['currency'] = $_GET['val'];
}
session_write_close();
ob_end_flush();

Originally I tried to reload page from the php file using header('location: ..') function but nothing was happening, in this reason I moved to variant to use javascript to refresh page, but still without success. Any ideas what I'm doing wrong? Thanks!

1条回答
可以哭但决不认输i
2楼-- · 2020-04-21 05:43

Pass your callback function as the second parameter:

jQuery('#div_session_write').load('update_currency.php?val=' + x, _callback);

That way, it is automatically called by jQuery when the request finishes loading. See the documentation for more info: http://api.jquery.com/load/

查看更多
登录 后发表回答