• Resolved antonop4u

    (@antonop4u)


    hi I’m trying to send with the POST method some data to a notification page.

    I created a javascript file an ajax php handler page a the notification page.

    here below you find the code I wrote in php for enqueuing the scripts etc.

    
    wp_register_script('user_notifications_js', get_theme_file_uri('/js/notification.js') , array('jquery') , '1.0.1' , true );
    
    if ( is_page('notifications') ){
    	// scripts
    	wp_localize_script( 'user_notifications_js', 'user_notifications_object_js', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    	wp_enqueue_script('user_notifications_js');
    }

    the javascript function I’m using is:

    
    let ntfId = ntf.getAttribute('id');
    jQuery(document).ready(function($) {
    		console.log(user_notifications_object_js.ajaxurl);
    	    $.ajax({
    	        url: user_notifications_object_js.ajaxurl,
    	        method: 'POST',
    	        data: {
    						id : ntfId,
    						status : 'read',
    						action : 'rm_ntfs_handler',
    	        },
    	        error: function( response ) {
    	            console.log(response.statusText);
    	        },
    		succes: function( response ) {
    	            console.log(response.statusText);
    	        },
    	    });
    	});
    }
    

    Now here is the trouble I’ve seen many tutorials online
    and they all use a new page to handle the ajax request, so i prepared a new page correctly included in the function.php.

    inside this page I wrote this code:

    
    add_action( 'wp_ajax_rm_ntfs_handler', 'rm_ntfs_handler' );
    add_action( 'wp_ajax_nopriv_rm_ntfs_handler', 'rm_ntfs_handler' );
    function rm_ntfs_handler(){
    	echo 'inside';
    
    }
    

    and nothing happen not even an error it seems like that the xhr request doesn’t exists, so I moved the above mentioned code (the last part) in the notification page and here at least I get the 400 error bad request.

    what am i doing wrong? any suggestion?

    any help will be very appreciated thank you in advance.

    • This topic was modified 5 years, 7 months ago by antonop4u.
Viewing 10 replies - 1 through 10 (of 10 total)
  • Moderator bcworkz

    (@bcworkz)

    I’m not entirely sure what the real issue is, but .ajax() seems to not send arbitrary data: objects in a way that PHP can handle. It’s fine when you send an instantiated class object like FormData, but not an object like {id : ntfId}. It’s strange, such objects are fine when used in .post() but not .ajax().

    All I can suggest is either send a class object or use .post() instead.

    Thread Starter antonop4u

    (@antonop4u)

    First thanks for the suggestion. Unfortunately even using the .post() I still get the same behaviour I described above.
    Nothing happen in a separate page and in the notification page I still get the same 400 Bad Request.
    here below is the code modified:

    function markNtfAsRead(button){
    	let ntf = button.parentElement.parentElement.parentElement;
    	let ntfId = ntf.getAttribute('id');
    	jQuery(document).ready(function($) {
    		  	$.post({
    	        url: user_notifications_object_js.ajaxurl,
    	        data: {
    						id : ntfId,
    						status : 'read',
    						action : 'rm_ntfs_handler',
    	        },
    	        error: function( response ) {
    	            console.log(response.statusText);
    	        },
    					succes: function( response ) {
    	            console.log(response.statusText);
    	        },
    	    });
    	});
    }

    I’m not sure if this is what you intended.
    Anyway thank you again for you support.

    • This reply was modified 5 years, 7 months ago by antonop4u.
    Moderator bcworkz

    (@bcworkz)

    You use .post() much differently than .ajax(), the parameters passed are handled differently, so you need to rearrange your code. It’s not a drop in replacement. See https://api.jquery.com/jQuery.post/

    Thread Starter antonop4u

    (@antonop4u)

    bcworks, sorry to keep bothering you, but I’m not sure what you mean when you say I shell rearrange my code; do you mean in the javascript side? or in the php?
    I rearranged the jQuery function following the indication of the link you posted, and in my opinion this should be the code:

    
    function markNtfAsRead(button){
    	let ntf = button.parentElement.parentElement.parentElement;
    	let ntfId = ntf.getAttribute('id');
    	jQuery(document).ready(function($) {
    		  	$.post( user_notifications_object_js.ajaxurl, { id : ntfId, status : 'read', action : 'rm_ntfs_handler' } );
    	});
    }
    

    is it correct?
    do I still need to use the action hooks and the function?

    
    add_action( 'wp_ajax_rm_ntfs_handler', 'rm_ntfs_handler' );
    add_action( 'wp_ajax_nopriv_rm_ntfs_handler', 'rm_ntfs_handler' );
    function rm_ntfs_handler(){
    	echo 'inside';
    
    }
    

    because with this configuration I still have the 400 bad request error.

    Moderator bcworkz

    (@bcworkz)

    It’s not a bother, no worries.

    Yeah, that JS script looks right. I did mean rearrange the JS script. Yes, you still need the PHP code as well.

    I placed your latest code on my test site, commenting out the button stuff and making ntfId into a string and setting .ajaxurl to my site’s Ajax URL. Thus it is still a valid Ajax test, only the data sent was changed. I called markNtfAsRead() from an onclick event on one of my custom page templates. My version of your code works fine without errors.

    Thus I think the problem could be in the sending of ntfId or the value of .ajaxurl. They are the only things that are different in my script. Try console logging them to verify that they are the correct string values.

    BTW, your PHP Ajax handler needs to call die; when finished, otherwise the server waits to time out before sending a response.

    Also, with .post(), I suggest adding a third “success” callback argument so you can check the value returned by the server. For example:

    $.post( user_notifications_object_js.ajaxurl,
        { id : ntfId, status : 'read', action : 'rm_ntfs_handler' },
        function( data ) {
            console.log( data );
        }
     );
    Thread Starter antonop4u

    (@antonop4u)

    I checked, and actually the ntfId wasn’t a string, but a number, strange because I’ve got it as an attribute (‘id’) of of a <div> tag, probably JavaScript turn it in to a number.
    I turned it in to a string and now isNaN(ntfId) return true.
    The console.log(user_notifications_object_js.ajaxurl) is https://localhost/mywebsite/wp-admin/admin-ajax.php does it look right?
    Unfortunately I still get the same error 400 (Bad Request).

    the problem is that wordpress for some reason doesn’t call the function rm_ntfs_handler().

    function rm_ntfs_handler(){
    	echo 'inside'; //  I should see this on display if properly called
    	var_dump($_POST);
    	die;
    }

    Since on your installation the code works, I’m going to try now on a new WordPress installation and from there I’ll try to figure it out what’s wrong.

    bcworkz thank you very much for your support.

    Thread Starter antonop4u

    (@antonop4u)

    There is any php or wordpress parameter to set in order to let ajax work?

    I just installed a brand new wordpress website, with the default twentynineteen theme, on which I added three pages all in the theme root:

    test-function.php

    included it in the function.php (the standard twentynineteen function page) using:

    require_once dirname( __FILE__ ) . '/test-functions.php';

    page-test.php //as template
    js-test.js // for javascrip

    And I assigned to the sample page the test template.

    the complete content of the test-function.php is:

    <?php
    wp_register_script('test_js', get_theme_file_uri('/js-test.js') , array('jquery') , '1.0.1' , true );
    wp_localize_script( 'test_js', 'user_ntf_js', array(
    	'ajaxurl' => admin_url( 'admin-ajax.php' )
    ) );
    wp_enqueue_script('test_js');

    the complete content of the page-test.php is:

    
    <?php /* Template Name: Test */
    get_header();
    add_action( 'wp_ajax_rm_ntfs_handler', 'rm_ntfs_handler' );
    add_action( 'wp_ajax_nopriv_rm_ntfs_handler', 'rm_ntfs_handler' );
    function rm_ntfs_handler(){
    	echo 'inside';
    	var_dump($_POST);
    	die;
    }
    ?><button id="btn-text">test</button><?php
    get_footer();
    

    and the complete content of the js-test.js is:

    
    const btn = document.querySelector('#btn-text');
    function markNtfAsRead(button){
    	let ntfId = '35';
    	jQuery(document).ready(function($) {
    		console.log(user_ntf_js.ajaxurl);
    		$.post( user_ntf_js.ajaxurl,
    		    { id : ntfId, status : 'read', action : 'rm_ntfs_handler' },
    		    function( data ) {
    		        console.log( data );
    		    }
    		 );
    	});
    }
    btn.addEventListener('click', function(){markNtfAsRead(this);}, false);
    

    this is the ajaxurl:

    https://localhost/mywebsites/test/wp-admin/admin-ajax.php

    I still get the same 400 bad request error.

    WordPress is running locally on WAMP.

    apache 2.4.37
    php 7.2.14
    mySql 5.7.24

    any suggestion?

    • This reply was modified 5 years, 7 months ago by antonop4u.
    • This reply was modified 5 years, 7 months ago by antonop4u.
    Moderator bcworkz

    (@bcworkz)

    If https://localhost/mywebsite/ (or the /test/ variant) gets your site’s home page or blog listing, then yes, /wp-admin/ajax-admin.php is correct. I assume you are checking the browser console to check for PHP output and are not expecting output to show up in the browser.

    There is an issue with your test scheme. You cannot enqueue scripts directly from functions.php.. They must be enqueued from the “wp_enqueue_scripts” action. Like so:

    add_action('wp_enqueue_scripts','setup_test');
    function setup_test() {
    wp_register_script('test_js', get_theme_file_uri('/js-test.js') , array('jquery') , '1.0.1' , true );
    wp_localize_script( 'test_js', 'user_ntf_js', array(
    	'ajaxurl' => admin_url( 'admin-ajax.php' )
    ) );
    wp_enqueue_script('test_js');
    }

    The real issue is adding Ajax callbacks from the template. Templates are not loaded with Ajax, so the callback is never registered when you request admin-ajax.php, thus WP kicks it out due to no matching action hook. I had added my callback from functions.php, so my version worked fine.

    Thread Starter antonop4u

    (@antonop4u)

    Yes I forgot the enqueue hook, I just copied the part I was interested in and I forgot that all the enqueue declarations should go inside a call back function.
    BTW now Ajax Works thank you very much bcworkz, as you point out in your last post “The real issue is adding Ajax callbacks from the template”. It’s a bit strange because I did already try the same solution before creating its own page included in the function.php, but I wasn’t able to establish the POST connection, I must have done something wrong. Now it doesn’t send back any errors, and I can see the data in the console exactly like it’s supposed to do. One more time thank you very much!

    Moderator bcworkz

    (@bcworkz)

    You’re welcome!

Viewing 10 replies - 1 through 10 (of 10 total)
  • The topic ‘Ajax bad request 400’ is closed to new replies.