• hi, I want to deliver html value through JS to PHP handling, but I still got error, 400 (Bad Request) .

    This is HTML:

    </div>
                <form class="row g-3" id="my_form">
                  <div class="col-md-12">
                    <label for="url" class="form-label">Input URL</label>
                    <input type="text" class="form-control my_info" id="url" required>
            
                  <div class="col-12">
                    <button class="btn btn-primary submit" type="button">Submit form</button>
                  </div>
                </form>
       </div>

    This is JavaScript:

    function getBaseUrl() {
        var re = new RegExp(/^.*\//);
        var my_local_url = re.exec(window.location.href)[0];
    
        return my_local_url;
    }
    
    console.log(getBaseUrl())
    
    jQuery(document).ready(function($) {
        console.log('test');
        // We'll pass this variable to the PHP function example_ajax_request
        var fruit = 'Banana';
        $('.submit').click(function (){
            // This does the ajax request
            $.ajax({
                url: getBaseUrl() + 'admin-ajax.php',
                data: {
                    'action':'crawler_info',
                    'my_info' : document.getElementById('url').value
                },
                success:function(data) {
                    // This outputs the result of the ajax request
                    console.log(data);
                },
                error: function(errorThrown){
                    console.log(errorThrown);
                }
            }); 
        })
    });

    This is PHP:

    function get_info() {
    
        // The $_REQUEST contains all the data sent via ajax 
        if ( isset($_REQUEST) ) {
    
            $infos = $_REQUEST['my_info'];
    
            // Now we'll return it to the javascript function
            // Anything outputted will be returned in the response
            echo $infos;
    
            // If you're debugging, it might be useful to see what was sent in the $_REQUEST
            print_r($_REQUEST);
    
        }
    
        // Always die in functions echoing ajax content or it will display 0 or another word
       die();
    }
    
    add_action( 'wp_ajax_crawler_info', 'get_info' );
    add_action( 'wp_ajax_nopriv_crawler_info', 'get_info' );

    Does anybody know how to solve my problem,Thanks

Viewing 15 replies - 1 through 15 (of 19 total)
  • Moderator bcworkz

    (@bcworkz)

    The default data type that .ajax() sends isn’t compatible with PHP. Include the arg dataType : 'json', in your .ajax() args list for compatibility.

    Thread Starter nobody123

    (@nobody123)

    @bcworkz
    No matter how do I change my code adding dataType: 'json' in ajax and from $infos = $_POST['my_info']; to $infos = json_encode($_POST['my_info']); in php
    or
    adding dataType: 'html' in ajax
    both get the same “400 (Bad Request)” error.
    How do I change my code to let it work?
    Thanks

    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    Moderator bcworkz

    (@bcworkz)

    Verify url value is correct. I suspect getBaseUrl() is not returning a /wp-admin/ path. Data type JSON has worked for me for similar code, provided everything else is correct.

    Thread Starter nobody123

    (@nobody123)

    Hi @bcworkz ,
    I have changed my code to the following

    JS (app.js):

    jQuery(document).ready(function($) {
        // We'll pass this variable to the PHP function example_ajax_request
        $('.submit').click(function (){
            var my_data = {
                'action':'crawler_info',
                'my_info' : document.getElementById('url').value
            };
            console.log(my_data);
            // This does the ajax request
            $.ajax({
                url: '/wordpress/wp-admin/admin-ajax.php',
                data: my_data,
                dataType: 'json',
                success:function(data) {
                    // This outputs the result of the ajax request
                    console.log(data);
                },
                error: function(errorThrown){
                    console.log(errorThrown);
                }
            }); 
        })
    });

    PHP(index.php):

    <?php
    /**
     * 
     * @package PLUGIN_NAME
     */
    
    function get_info() {
    
        // The $_REQUEST contains all the data sent via ajax 
        if ( isset($_REQUEST) ) {
    
            $infos = json_encode($_REQUEST['my_info']);
    
            // Now we'll return it to the javascript function
            // Anything outputted will be returned in the response
            echo $infos;
    
            // If you're debugging, it might be useful to see what was sent in the $_REQUEST
            print_r($_REQUEST);
    
        }
    
        // Always die in functions echoing ajax content or it will display 0 or another word
       die();
    }
    
    add_action( 'wp_ajax_crawler_info', 'get_info' );
    add_action( 'wp_ajax_nopriv_crawler_info', 'get_info' );

    PHP2(my_plugin_name.php):

    <?php
    /**
     * Plugin Name:       Crawler Plugin
     * Plugin URI:        https://www.google.com/
     * Description:       Crawler for real estate Plugin.
     * Version:           1.0.0
     * Requires at least: 5.8
     * Requires PHP:      7.4
     * Author:            Ming
     * License:           GPL v2 or later
     * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
     * Update URI:        https://www.google.com/
     * Text Domain:       my-basics-plugin
     * Domain Path:       /languages
     * @package CRWLER
     */
    
    defined('ABSPATH') or die('Hello, i/m your world');
    
    if ( !class_exists('Crawler')){
    
        class Crawler
        {        
            function __construct()
            {
    			$this->plugin = plugin_basename( __FILE__ );
                $this->my_menu_url = 'my_crawler';
            }
    
           
            function register(){
                add_action('admin_enqueue_scripts', array( $this , 'enqueue') );
                add_action('admin_menu', array($this, 'add_admin_pages'));
               
                add_filter("plugin_action_links_$this->plugin", array( $this, 'setting_link'));
            }
    
            public function setting_link($links){
                $settings_link = '<a href="options-general.php?page='.$this->my_menu_url.'">Setting</a>';
                array_push($links, $settings_link);
                return $links;
            }
    
            public function add_admin_pages(){
                add_menu_page('Crawler Plugin', 'Crawler1', 'manage_options', $this->my_menu_url, array($this, 'admin_index'), 'dashicons-store', 110);
            }
            
            public function admin_index(){
                require_once plugin_dir_url(__FILE__) . 'src/admin.html';
            }
    
            protected function create_post_type(){
                
                add_action('init', array( $this, 'custom_post_type') );
            }
            
            function custom_post_type(){
                register_post_type('book', ['public' => true, 'label' => 'testtest']);
            }
    
            static function enqueue(){
                wp_deregister_script( 'jquery' );
    
                wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js');
                wp_register_script('bootstrap_js', 'https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js');
                wp_register_style('bootstrap_css','https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css');
                
                wp_enqueue_style('mycrawlerstyle', plugins_url('/crawler/assets/css/app.css'), __FILE__, null);
                wp_enqueue_style('bootstrap_css');
                wp_enqueue_script('mycrawlerscript', plugins_url('/crawler/assets/js/app.js'), __FILE__, null, true);
                wp_enqueue_script('jquery');
                wp_enqueue_script('bootstrap_js');
            }
    
            function activate(){
    			require_once plugin_dir_url(__FILE__) . 'src/activate.php';
            } 
        }
    
        $crawler = new Crawler();
        $crawler -> register();
    
        // activate
        register_deactivation_hook(__FILE__,  array( 'CrawlerActivate', 'activate') );
    
        // deactivate
        require_once plugin_dir_url(__FILE__) . 'src/deactivate.php';
        register_deactivation_hook(__FILE__,  array( 'CrawlerDeactivate', 'deactivate') );
    }

    =============================================

    my file directory:

    my_plugin_name—assets
    | |
    | —js
    | |
    | –app.js
    |
    —src
    | |
    | –admin.html
    |
    —index.php
    |
    —my_plugin_name.php

    Version:
    WordPress 5.8.2
    PHP 7.4.27
    MySQL 5.7.37 Community Server (GPL)

    Finally, I still got that error….

    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    Moderator bcworkz

    (@bcworkz)

    The .ajax() URL should be a full, absolute URL — https://, domain name, everything. Relative URLs don’t work reliably in a WP environment. The URL is usually obtained from PHP’s admin_url( 'admin-ajax.php' ) and passed to jQuery with either wp_localize_script() or wp_add_inline_script().

    Thread Starter nobody123

    (@nobody123)

    I have added the following code to my_plugin_name.php in static function enqueue()

    $variables = array(
     'ajaxurl' => admin_url( 'admin-ajax.php' )
    );
     wp_localize_script('mycrawlerscript', "test", $variables);

    and changed js from url: '/wordpress/wp-admin/admin-ajax.php' to url: test.ajaxurl or url: 'https://127.0.0.1:8080/wordpress/wp-admin/admin-ajax.php'
    both are get 400 error.

    • This reply was modified 2 years, 7 months ago by nobody123.
    Thread Starter nobody123

    (@nobody123)

    @bcworkz Cloud you provide your all of code working to me, Please
    I want to try does it work or not in plugin (admin).
    I found many people had similar problem(400 error) in stack overflow.
    does it be a bug for admin_ not wp_ ?
    Thank you very much

    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    Moderator bcworkz

    (@bcworkz)

    This example code is confirmed to work:

    $.ajax( {
    			method : 'POST',
    			dataType : 'json',
    			url : my_var.ajaxurl,
    			data : {
    				foo : foobar,
    				_wpnonce : my_var.nonce,
    				action : 'my_php_ajax_function'
    			}
    		} )
    		.done(
    			function( data ){
    				console.log(data);				
    			}
    		);

    Not included is code to execute the above on an event, could be $(document).ready(); or whatever.

    Example PHP:

    add_action( 'wp_ajax_nopriv_my_php_ajax_function', 'my_php_ajax_function' );
    add_action( 'wp_ajax_my_php_ajax_function', 'my_php_ajax_function' );
    function my_php_ajax_function(){
    	if ( wp_verify_nonce( $_POST['_wpnonce'], 'wp_rest' ) ){
    			echo json_encode(
    				array(
    					'youSent' => $_POST['foo']
    				)
    			);
    			exit;
    
    	} else {
    		echo 'nonce check failed';
    		exit;
    	}
    }
    
    add_action('wp_enqueue_scripts', 'my_enqueue2');
    function my_enqueue2($hook) {
    	wp_enqueue_script( 'ajax-script',
    		plugins_url( '/js/my-jquery.js', __FILE__ ),
    		array('jquery'),
    		false,
    		true
    	);
    	$rest_nonce = wp_create_nonce( 'wp_rest' );
    	wp_localize_script( 'ajax-script', 'my_var', array(
    		'ajaxurl' => admin_url( 'admin-ajax.php' ),
    		'nonce' => $rest_nonce,
    	));
    }

    Console logs {youSent: 'foobar'}

    • This reply was modified 2 years, 7 months ago by bcworkz. Reason: typo
    Thread Starter nobody123

    (@nobody123)

    @bcworkz Thank you very much!
    1.what is foo : foobar?

    2.I changed your code from add_action('wp_enqueue_scripts', 'my_enqueue2'); to add_action('admin_enqueue_scripts', 'my_enqueue2');, and then the Console logs don’t display anything….
    Could you tell me where you put php and js file ?

    3.Due to modify plugin on background management sys., I have to work on admin_(the frontend of background management sys.) but not wp_ (the frontend of wp)

    4.if I use <form action='XXX.php'>, it will redirect to a new page, not in wordpress frame.

    5.Does admin-ajax.php and the hook of wp_ajax_ is ok or not on the frontend of background management sys.?

    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    • This reply was modified 2 years, 7 months ago by nobody123.
    Moderator bcworkz

    (@bcworkz)

    “foo” and variants thereof are common flll-in values used by document writers for example data. In this case it’s just an arbitrary value to send to the server so it can be sent back, proving the data is making a successful round trip.

    The code sits in a plugin I use to test custom code. The PHP is in the plugin’s main file and jQuery in /js/my-jquery.js. What were you using to trigger the script? If it executes immediately on load its dependencies may not be ready yet. You’d at least need to trigger through $(document).ready() or maybe a click event on the page.

    If you’re loading an admin page, then “admin_enqueue_scripts” action hook is correct.

    If your form is entirely Ajax based, its action attribute value can simply be empty or "#" to prevent a new page request. If you do need to run a script before submitting a form to elsewhere, use preventDefault() to stop the submit. Then execute the script, followed by something like formObj.submit();.

    I’m not sure how background management sys works, but just about anything client side can submit an Ajax request to admin-ajax.php if it’s properly formed. If you’re still having trouble, use your browser’s network developer tool to ensure the request was properly sent. Server side, use error_log() calls at strategic points to learn where the problem lies. You can even temporarily add debug code to admin-ajax.php if that would help.

    Thread Starter nobody123

    (@nobody123)

    @bcworkz Thanks you very much!
    It work when I use your code.
    but I still have some question want to ask
    1.foo : foobar should be change to foo : 'foobar'
    2.How do receive php echo using your code?
    I found adding any code in if ( wp_verify_nonce( $_POST['_wpnonce'], 'wp_rest' ) ), $ajax.do would be unsuccessful.

    Moderator bcworkz

    (@bcworkz)

    Right, quote strings. JS is loosely typed and leads to sloppy coding. Thanks for correcting.

    Server response is received with
    .done( function( data ) { /* do with data as you wish */ });

    Apparently the nonce was not properly assigned somewhere. It’s first established with $rest_nonce = wp_create_nonce( 'wp_rest' );. This has nothing to do with the REST API, but the nonce related code was copied from an example that does. 'wp_rest' is arbitrary, but must be coordinated with the nonce check in the Ajax handler.

    The nonce value is then passed to jQuery with wp_localize_script(), where it’s assigned to my_var.nonce. When it is passed back to the server as data, the nonce check should succeed, helping to ensure the Ajax request came from our own script and not some bad actor.

    Thread Starter nobody123

    (@nobody123)

    @bcworkz Thanks for your explain, but I more want to how to get value in php from ajax not only get value in $ajax.do.
    Do you know how to get?

    Moderator bcworkz

    (@bcworkz)

    Send what ever values you need in the .ajax() data: object. (Not the data in .done()) You surely do not actually need ‘foobar’, send what’s really needed instead. Property name foo: is arbitrary. Add as many properties as you need, named as desired. Coordinate object property names with PHP $_POST element names.

    I don’t know how .do syntax works. I cling to my example because I know it works for me. jQuery is not my forte. My example is always my starting point when I need ajax. I modify it as needed for the specific situation. Then at least the basic mechanics will be working right.

    Thread Starter nobody123

    (@nobody123)

    @bcworkz I know what you said, and thank for your explain.
    but my main problem is how to display echo the vale on the frontend of admin or wp after ajax deliver it.

Viewing 15 replies - 1 through 15 (of 19 total)
  • The topic ‘admin-ajax.php 400 (Bad Request) error’ is closed to new replies.