开发者

POST with Jquery to a php function in wordpress retrieves only empty values

开发者 https://www.devze.com 2023-02-01 21:55 出处:网络
in a \"wordpress\" page I have this code: function d开发者_StackOverflow中文版isplayData(id) { var $j = jQuery.noConflict();

in a "wordpress" page I have this code:

function d开发者_StackOverflow中文版isplayData(id) {
var $j = jQuery.noConflict();
$j.ajax({
          type:'POST',
          data:{rid:id},
          url: "http://www.mywebsite.com/?page_id=123",
          success: function(value) {
            alert('<?php echo($_POST['rid'])  ?>');
          }
        });
}

but the value displayed in alert is empty. How can get 'rid' value?

Thanks, julio


You're attempting to retrieve a POST value via PHP in Javascript. This is erroneous. To do correctly, the PHP/Server-side script returns the value in either raw form, HTML or json. This result is returned as data to jQuery's AJAX method. Notice the variable value in the code below.

  function displayData(id) {
    var $j = jQuery.noConflict();
    $j.ajax({
              type:'POST',
              data:{rid:id},
              url: "http://www.mywebsite.com/?page_id=123",
              success: function(value) {
                //do something with 'value'
                alert(value);
                console.log('The result is ' + value);

              }
            });
    }


the line:

alert('<?php echo($_POST['rid'])  ?>');

will be rendered before the ajax call is made - where is the 'rid' value, in the page where the javascript lives, or the response you get from the ajax call? (ie. mywebsite.com/?page_id=123).

if its from the page you're posting data too, the response from the server would need to return a string or json object (or similar) which contains the data so you can parse it in the success value.

0

精彩评论

暂无评论...
验证码 换一张
取 消