1

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

<?php
   $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
  • What does first page have apart from the object? Commented Jun 28, 2016 at 9:51
  • to make the AJAX answer, make it like in the page : codex.wordpress.org/AJAX_in_Plugins Commented Jun 28, 2016 at 10:23

2 Answers 2

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.

1
  • 1
    Your solution is right, thanks a lot. But i have problems using 'wp_localize_script' so i have asked a related question to this here: wordpress.stackexchange.com/q/231415/97480 Commented Jul 4, 2016 at 16:52
1
wp_send_json( $result );
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {

        wp_die();
}

UPD

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' );

https://codex.wordpress.org/AJAX_in_Plugins

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',
            'wpUser',
            [
                'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
            ] );

$.post( wpUser.ajaxUrl, { action: 'my_action' } );
2
  • Just dumping some code is not an answer. Please explain why your code works for what OP wants. Commented 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 Commented 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.