I have created a WordPress page that has this simple PHP code:

   $result = array(
       'State'   => 'Done',
       'ID'        => 1

   wp_send_json( $result );

When submitting a form in another page using Ajax(JQuery) it calls this PHP page, then in the JQuery method i try to read the returned value from the PHP page using this code:

$( '#contact_form' ).bootstrapValidator({
    fields: {
        // ...
    submitHandler: function( formInstance ) {
        $.post( "../send-message", $("#contact_form").serialize(), function( result ) { 
            alert( result );            

But it actually returns the whole PHP page with its WordPress theme code used in addition to the passed parameters, as shown here:

enter image description here

My question is: How can i return a PHP value from a WordPress page to a JQuery function?


2 Answers 2


How can i return a PHP value from a WordPress page to a JQuery function?

Use wp_localize_script to create an object and pass it to the JavaScript.

wp_send_json( $result );
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {



The besat way to use ajax requests with wp is to use wp native ajax actions

add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );


so you need to make post request to admin-ajax.php

wp_enqueue_script( 'frontend-js', PATH_TO_JS . '/script.js' );
wp_localize_script( 'frontend-js',
                'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
            ] );

$.post( wpUser.ajaxUrl, { action: 'my_action' } );
  • Just dumping some code is not an answer. Please explain why your code works for what OP wants.
    – cjbj
    Jun 29, 2016 at 8:58
  • @cjbj, the request to the php page will return the whole page with loaded wp, so we need to stop after sending necessary data
    – Dimon Smus
    Jun 29, 2016 at 9:04

Your Answer

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

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