将Javascript变量插入PHP

I want to paste two variables from javascript to PHP so I tried

$.post("index.php", {myQuery: myFinalSQL, action: "show_all_stories_sorting"}); 

where myFinalSQL is a string in javascript

In index.php, I try to printout the myFinalSQL with

echo $_POST['myQuery'];

But it didn't work. Would you please tell me how to insert javascript variables to PHP?

If you want to add value from PHP to Javascript you can use :

<script>
    var myQuery = "<?php echo $myQuery; ?>;
</script>

But, if you want to add value from Javascript to PHP, you'r not allowed because PHP is server based and javascript is text based.

If you used $.post() :

$.post("index.php", {myQuery: myFinalSQL}, *your_javascript_action* );

in your index.php, you can use this :

if(isset($_POST['myQuery'])){ // checking method
    echo $_POST['myQuery'];
}

You using wrong approach.

It is bad way to interract with server by such method (inserting php variable in <? ?> tags into script tag).

You should use this:

$.post("ajax.php/myGlobalAction", params, callback);

In callback you will do with your data all what you need.

Example:

var params = {
 id: 5
};
$.post( "ajax.php?action=getSqlQueryForSomething", params , function( data ) {
   $( ".sqlQuery" ).html( data.sqlQuery );
});

So you have complex architecture problem if you need to work with php and js like this. Change your architecture before it's too late.