Javascript function post and call php script

EDIT 2018

Yeah, I am still alive. You can use the fetch API instead of jQuery. It is widely supported except (guess who?…) IE 11 and below but there is a polyfill for that. Enjoy modern coding.

Support for fetch API

OLD ANSWER

You will have to use AJAX.

Javascript alone cannot reach a php script. You will have to make a request, pass the variable to PHP, evaluate it and return a result. If you’are using jQuery sending an ajax request is fairly simple:

$.ajax({
    data: 'orderid=' + your_order_id,
    url: 'url_where_php_is_located.php',
    method: 'POST', // or GET
    success: function(msg) {
        alert(msg);
    }
});

and your php script should get the order id like:

echo $_POST['orderid'];

The output will return as a string to the success function.

EDIT

You can also use the shorthand functions:

$.get('target_url', { key: 'value1', key2: 'value2' }).done(function(data) {
    alert(data);
});

// or eventually $.post instead of $.get

Leave a Comment