Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

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');
share|improve this answer
    
This part I know ;) –  Derfder Sep 6 '13 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 '13 at 15:30
    
Hmm, I tried it and I get in alert undefined. Shoulc I use echo before json_encode? –  Derfder Sep 6 '13 at 15:43
    
No. Can you edit your question and post the full code you are trying? –  cybmeta Sep 6 '13 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 '13 at 15:55
show 15 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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