0

I have this in my JavaScript part:

$.post(
    WPaAjax.ajaxurl,
    {
        action : 'my_php_action_to_do',
    },
    function( response ) {
        alert( response.mycode );
    }
);

and this in my my_php_action_to_do php function:

function my_php_action_to_do() {

    $send_to_response['mycode'] = '1234';
    echo json_encode( $send_to_response );
    exit();

}

I can execute the php code in the php function and run the result post javascirpt code, but the problem I am facing is how to send the variable from the php function back to response and alert it or use in whatever way.

Now I am getting undefined in a popup window as a result.

How to do that in WordPress?

1 Answer 1

3

You need to send the var through your ajax request:

$.post(
//be suer that this var is pointing to wp-admin/admin-ajax.php
WPaAjax.ajaxurl,
{
    action              : 'my_php_action_to_do',
    //here your var and its value
    my_var              : 'the_value'
},
function( response ) {
    response = jQuery.parseJSON(response);
    alert(response.message);
}
);

In your my_php_action_to_do function:

function my_php_action_to_do(){
    $var['message'] = $_POST['my_var'];
    //Send back the $var value in json format. You can send it in other format if you want
    echo json_encode( $var );
    exit();
}

//Don't forget to add your my_php_action_to_do function to wp_ajax_* action hook.

add_action('wp_ajax_my_php_action_to_do', 'my_php_action_to_do');
//or this if you want it to work in the frontend
add_action('wp_ajax_nopriv_my_php_action_to_do', 'my_php_action_to_do');
20
  • This part I know ;)
    – Derfder
    Sep 6, 2013 at 15:29
  • But I want to get the value of php variable back after the script in the function is done and send it back to javascript, so I can alert it in the response. how to do taht?
    – Derfder
    Sep 6, 2013 at 15:30
  • Hmm, I tried it and I get in alert undefined. Shoulc I use echo before json_encode?
    – Derfder
    Sep 6, 2013 at 15:43
  • No. Can you edit your question and post the full code you are trying?
    – cybmeta
    Sep 6, 2013 at 15:50
  • function( response ) { alert( response.mycode ); } in JS and in PHP I have this: $send_to_response['mycode'] = '1234'; echo json_encode( $send_to_response ); and I am gettign undefined in the popup ;(
    – Derfder
    Sep 6, 2013 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.