Ajax ошибка 400

I am trying to send an Ajax POST request using Jquery but I am having 400 bad request error.

Here is my code:

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: {
    "subject:title":"Test Name",
    "subject:description":"Creating test subject to check POST method API",
    "sub:tags": ["facebook:work", "facebook:likes"],
    "sampleSize" : 10,
    "values": ["science", "machine-learning"]
  },
  error: function(e) {
    console.log(e);
  }
});

It Says: Can not build resource from request.
What am I missing ?

asked Apr 15, 2013 at 13:57

Sachin Jain's user avatar

Sachin JainSachin Jain

21.4k33 gold badges104 silver badges168 bronze badges

4

Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object.
So the correct version is here:

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: JSON.stringify({
    "subject:title":"Test Name",
    "subject:description":"Creating test subject to check POST method API",
    "sub:tags": ["facebook:work", "facebook:likes"],
    "sampleSize" : 10,
    "values": ["science", "machine-learning"]
  }),
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

May be it will help someone else.

answered Apr 17, 2013 at 8:01

Sachin Jain's user avatar

Sachin JainSachin Jain

21.4k33 gold badges104 silver badges168 bronze badges

7

Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.

400 Bad Request

Bad Request. Your browser sent a request that this server could not
understand.

Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.

415 Unsupported Media Type

Try this.

var newData =   {
                  "subject:title":"Test Name",
                  "subject:description":"Creating test subject to check POST method API",
                  "sub:tags": ["facebook:work", "facebook:likes"],
                  "sampleSize" : 10,
                  "values": ["science", "machine-learning"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.

answered May 17, 2018 at 8:05

Du-Lacoste's user avatar

Du-LacosteDu-Lacoste

11.6k2 gold badges71 silver badges51 bronze badges

1

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn’t set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.

answered Mar 30, 2020 at 13:52

Norbert Norbertson's user avatar

The question is a bit old… but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.

You have to get name and value from craft in your template :

<script type="text/javascript">
    window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
    window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>

and pass them in your request

data: window.csrfTokenName+"="+window.csrfTokenValue

answered Jan 21, 2017 at 16:17

Benoît Schiex's user avatar

1

I’m hoping this may be of use to those encountering 400 errors while using AJAX in WordPress going forward. Even though this question is many years old, the solutions provided have all been programmatic, and I’m sure many have stepped through their code to repeatedly find it’s correct, yet continue to find it is not working.

I found dozens of results asking how to resolve «WP AJAX request returning 400 Bad Request» or «WP AJAX request returning 0» and nothing today worked.

Googling «How do I fix 400 bad request on WordPress?» finally resulted in the answer appearing from https://wp-umbrella.com/troubleshooting/400-bad-request-error-on-wordpress/

Clear your Web Browser Cache and Cookies

You may be surprised, but most 400 errors in WordPress can be fixed by clearing your browser’s cache and cookies. Browser caches temporarily store images, scripts, and other parts of websites you visit to speed up your browsing experience.

Clearing both my cache and cookies saw the 400 Bad Request code disappear and results return AJAX results as expected.

answered Jun 23, 2022 at 8:24

Patrick Jackson's user avatar

1

You need to build query from «data» object using the following function

function buildQuery(obj) {
        var Result= '';
        if(typeof(obj)== 'object') {
            jQuery.each(obj, function(key, value) {
                Result+= (Result) ? '&' : '';
                if(typeof(value)== 'object' && value.length) {
                    for(var i=0; i<value.length; i++) {
                        Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
                    }
                } else {
                    Result+= [key, encodeURIComponent(value)].join('=');
                }
            });
        }
        return Result;
    }

and then proceed with

var data= {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work, facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: buildQuery(data),
  error: function(e) {
    console.log(e);
  }
});

answered Apr 15, 2013 at 14:05

Christian Ezeani's user avatar

2

Кароч написал лэндинг, задача реализовать форму обратной связи на PHP используя JQuery AJAX. И причем что сайт идет как тема для WordPress. Сделал все как в доке, использовал admin-ajax.php, Итог: Возвращает ошибку (Bad Request 400). Код снизу. Может кто знает где я про втыкал.

HTML:

<div class="form-block">
						<form action="" id="header-form"  method="post" class="form">
							<label class="title">ЗАМОВТЕ БЕЗКОШТОВНУ КОНСУЛЬТАЦІЮ</label>
							<label ><span>Ім'я *</span><input autocomplete="off" type="text" name="send_name"></label>
							<label><span>Телефон *</span><input autocomplete="off" placeholder="+38(XXX) XX-XX-XXX" type="text" name="send_phone"></label>
							<label><span>Додаткова інформація</span><input autocomplete="off"  type="text" name="send_info"></label>
							<label><input type="submit" name="subm" value="ЗАМОВИТИ ДЗВІНОК"></label>

JS :

$ ('#header-form').on('submit', function (e) {
				e.preventDefault();
				
				var inf = {
					name: $ ('input[name="send_name"]').val(),
					phone: $ ('input[name="send_phone"]').val(),
					info: $ ('input[name="send_phone"]').val()
				};
				
				$.ajax ({
					url: '<?php echo admin_url('admin-ajax.php') ?>',
					type: 'POST',
					data: inf,
					contentType: 'application/json',
					dataType: 'json',
					beforeSend: function () {
						alert('<?php echo admin_url('form-ajax.php'); ?>');
				},
					success: function (err) {
					 $ ('input[name="send_name"]').css('display', 'none');
				},
					error: function (err, rex, ww) {
						alert ('Otladka');
					console.log (err);
					console.log (rex);
					console.log (ww);
				}
				});
			});

PHP (functions.php темы)

add_action ('wp_ajax_sendf', 'sendf');
add_action ('wp_ajax_nopriv_sendf', 'sendf');

function sendf () {
	
	$result = array ();
	
	echo json_encode ($result);
	exit;
}

Ajax 400 (Bad Request): Подробное руководство

Ajax — это техника программирования, которая позволяет обмениваться данными между сервером и клиентом без необходимости загружать страницу снова. Такой способ передачи данных стал незаменимым в интерактивных веб-приложениях и веб-сервисах. Однако, когда вы сталкиваетесь с ошибкой Ajax 400 (Bad Request), это может означать не только неудобство, но и прекращение работы всего приложения. В этой статье мы рассмотрим основные причины ошибки, а также предоставим решения для ее устранения.

Что такое Ajax 400 (Bad Request)?

Ошибка Ajax 400 (Bad Request) возникает, когда сервер не может обработать запрос из-за некорректных данных, которые отправляет клиент. В частности, такие проблемы возникают, когда отправляемые данные превышают допустимый лимит или нарушают требования безопасности сервера.

400 Bad Request может иметь множество причин. Однако, самые распространенные причины включают следующие:

1. Ошибка в коде JavaScript
2. Неправильный формат отправляемых данных
3. Превышение лимита скорости запросов
4. Серверная ошибка

Причины ошибки Ajax 400 (Bad Request) подробно

1. Ошибка в коде JavaScript

Одной из наиболее распространенных причин ошибки Ajax 400 (Bad Request) является ошибка в коде JavaScript. В частности, это может произойти, когда код на стороне клиента некорректно формирует запрос к серверу. К примеру, если вы отправляете пустой запрос или запрос с нулевой длиной, сервер не сможет корректно его обработать.

Другой распространенной причиной ошибки может быть неправильное использование AJAX в коде JavaScript. Например, попытка отправить запрос до того, как страница полностью загружена, может привести к ошибке. Для того, чтобы корректно использовать AJAX, нужно убедиться, что все действия начинаются после того, как страница полностью загружена.

2. Неправильный формат отправляемых данных

Если отправляемые данные не соответствуют формату, необходимому на стороне сервера, это также может спровоцировать ошибку Ajax 400 (Bad Request). Например, если вы отправляете данные в формате JSON, а сервер ожидает формат XML, то это приведет к ошибке. Также, если вы отправляете запрос с некорректными заголовками или параметрами, это может вызвать такую ошибку.

3. Превышение лимита скорости запросов

Третья причина ошибки Ajax 400 (Bad Request) — это превышение лимита скорости запросов. Некоторые серверы ограничивают частоту отправки запросов с помощью специальных алгоритмов, называемых rate limiting. Если браузер отправляет слишком много запросов в определенный промежуток времени, сервер может отклонить запрос с ошибкой. Обычно, для решения этой проблемы, нужно уменьшить количество отправляемых запросов или увеличить время между отправками.

4. Серверная ошибка

Ошибки могут возникать не только на стороне клиента, но и на стороне сервера. Например, если сервер не может обработать запрос из-за превышения лимита максимального размера, то это может вызвать ошибку Ajax 400 (Bad Request). Также, если запрос не соответствует требованиям безопасности сервера, то сервер может отклонить его с ошибкой.

Как исправить ошибку Ajax 400 (Bad Request)

Чтобы устранить ошибку, необходимо определить ее причину. В зависимости от причины, решения могут быть различными. Рассмотрим несколько распространенных случаев.

1. Проверьте код JavaScript

Если ошибка возникает из-за неправильного кода JavaScript, то необходимо тщательно проверить код и исправить возможные ошибки. Убедитесь, что запрос отправляется после того, как страница полностью загружена, и что данные отправляются в корректном формате и с правильными заголовками.

2. Используйте правильный формат данных

Если ошибка связана с неправильным форматом данных, то необходимо убедиться, что вы отправляете данные в правильном формате. Также, убедитесь, что вы используете правильные заголовки и параметры.

Пример кода для отправки данных в формате JSON:

var data = {name: 'John', age: 30};
var json = JSON.stringify(data);

var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
    // Обработка ответа
};
xhr.send(json);

3. Увеличьте интервал между запросами

Если сервер отклоняет запросы из-за превышения лимита скорости, то необходимо уменьшить количество отправляемых запросов или увеличить интервал между ними. Для этого можно использовать метод setTimeout в JavaScript.

Пример кода для увеличения времени между запросами:

function myFunction() {
    // Отправка запроса
    setTimeout(myFunction, 1000);
}

4. Обратитесь к администратору сервера

Если ошибку не удается исправить самостоятельно, то необходимо обратиться к администратору сервера, который может помочь с решением проблемы. Он сможет проанализировать логи сервера и найти причину ошибки.

Заключение

Ajax 400 (Bad Request) — это распространенная ошибка, которая может возникать по многим причинам. Ошибка может быть вызвана неправильным кодом JavaScript, неправильным форматом данных, превышением лимита скорости запросов или ошибкой на стороне сервера. Чтобы устранить ошибку, необходимо определить ее причину и принять соответствующие меры. В большинстве случаев, чтение логов сервера и отладка JavaScript-кода помогут найти и исправить ошибку.

I have been delving into AJAX within WordPress and have followed many tutorials on how to do so, but every single request returns a 400 error.

In my functions.php I have added the following:

Step 1 — Register and add scripts to WordPress

/**
 * Initialize the JavaScript we need for loading more
 *
 * @return void
 */
function ajax_load_more_init()
{
    // Register and enqueue the script we need for load more
    wp_register_script('ajax-load-more-script', get_template_directory_uri() . '/assets/scripts/ajax-load-more.js', array('jquery'));
    wp_enqueue_script('ajax-load-more-script');

    // Localize the script so we can access tthe variables in PHP
    wp_localize_script('ajax-load-more-script', 'ajax_load_more_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
    ));
}

Step 2 — Enqueue the actual script

/**
 * Add AJAX loader to scripts
 */
add_action('wp_enqueue_scripts', 'ajax_load_more_init');

Step 3 — Allow AJAX to be used on the frontend

// AJAX Hook for users
add_action('wp_ajax_ajax_load_more', 'ajax_load_more');
add_action('wp_ajax_nopriv_ajax_load_more', 'ajax_load_more');

Step 4 — A dead simple function for testing

/**
 * The backend PHP to actually load more posts
 *
 * @return void
 */
function ajax_load_more()
{
    echo "TESTING";

    wp_die();
}

In my actual AJAX script I have the following:

jQuery(document).ready(function ($) {

  // Initialize Isotope as $grid
  const $grid = $('#grid').isotope({
    itemSelector: '.grid-item',
    percentagePosition: true,
    animationEngine: 'best-available', //CSS3 if browser supports it, jQuery otherwise
    animationOptions: {
      duration: 800,
    },
    masonry: {
      columnWidth: '.grid-item',
      gutter: 30,
    },
  })


  var has_run = false;
  var init_offset = 0;

  // Hook into click event
  $('button.load-more-posts').click(function (e) {
    e.preventDefault();

    var button = $(this);
    var nonce = $(this).data("nonce");

    console.log('Nonce is: ' + nonce);

    // Disable the button
    button.prop("disabled", true);

    // Check the offset
    if (has_run == false) {
      button.data('offset', $(this).data("offset"));
      init_offset = $(this).data("offset");
    }

    console.log('Initial offset is: ' + init_offset);
    console.log('Initial offset is: ' + button.data('offset'));

    // Perform AJAX request
    $.ajax({
      type: 'POST',
      dataType: 'json',
      url: ajax_load_more_object.ajax_url,
      contentType: 'application/json; charset=utf-8',
      data: {
        action: 'ajax_load_more',
        security: nonce,
        init_offset: init_offset,
        offset: button.data('offset'),
      },
      beforeSend: function (xhr) {
        console.log('Loading more posts...')
        button.text('Loading');
      },
      success: function (response) {
        console.log(response);

        // Undo Button Disable
        button.prop("disabled", false);

        // Set Offset
        button.data("offset", offset + 10);

        // Script has run
        has_run = true;

        return false;
      },
      error: function (xhr, status, error) {
        console.log(xhr.responseText);
      }
    });
  });
});

As you can see in the $ajax call, the url is to admin-ajax and the action is the trailing part of wp_ajax_nopriv_ajax_load_more.

The nonce comes from the button on the front end like so:

<button class="load-more-posts" data-nonce="<?php echo wp_create_nonce('load_more_ajax'); ?>" data-offset="10">Load More Posts</button>

enter image description here

My working code

So, thanks to everyone’s shared input I was able to come up with a solution that I’ll detail below:

In functions.php (should really be in a plugin)

/**
 * Additional thumbnail sizes
 */
add_theme_support('post-thumbnails');
add_image_size('post-thumbnail-square', 300, 300, true);

/**
 * Initialize the JavaScript we need for loading more
 *
 * @return void
 */
function ajax_load_more_init()
{
    // Register and enqueue the script we need for load more
    wp_register_script('ajax-load-more-script', get_template_directory_uri() . '/assets/scripts/ajax-load-more.js', array('jquery'));
    wp_enqueue_script('ajax-load-more-script');

    // Localize the script so we can access tthe variables in PHP
    wp_localize_script('ajax-load-more-script', 'ajax_load_more_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
    ));
}

/**
 * Add AJAX loader to scripts
 */
add_action('wp_enqueue_scripts', 'ajax_load_more_init');

/**
 * Allow AJAX to be used on the front end
 */
add_action('wp_ajax_ajax_load_more_posts', 'ajax_load_more_posts_callback');
add_action('wp_ajax_nopriv_ajax_load_more_posts', 'ajax_load_more_posts_callback');

/**
 * The backend PHP to actually load more posts
 *
 * @return void
 */
function ajax_load_more_posts_callback()
{
    // First check the nonce, if it fails the function will break
    check_ajax_referer('ajax_load_more_posts', 'security');

    // Get the data we have from the load more button
    $offset = $_POST['offset'];
    $init_offset = $_POST['init_offset'];

    // Get posts with given offset
    if ($offset != null && absint($offset) && $init_offset != null && absint($init_offset)) {
        // Finally, we'll set the query arguments and instantiate WP_Query
        $args = array(
            'post_type' => 'post',
            'posts_per_page' =>  $init_offset,
            'offset' => $offset
        );

        $post_list = array();

        $query = new WP_Query($args);

        if ($query->have_posts()) :
            while ($query->have_posts()) : $query->the_post();

                //$categories = get_the_categories();

                $post_list[] = array(
                    'category' => get_the_category(),
                    'title' => get_the_title(),
                    'introduction' => get_field('introduction'),
                    'date' => get_the_date(),
                    'permalink' => get_permalink(),
                    'thumbnail' => get_the_post_thumbnail(),

                );
            endwhile;
        endif;

        echo json_encode($post_list);

        wp_die();
    }
}

In my ajax-loader script

jQuery(document).ready(function ($) {

  var has_run = false;
  var init_offset = 0;

  // Hook into click event
  $('button.load-more-posts').click(function (e) {

    var $grid = $('#grid').isotope({
      itemSelector: '.grid-item',
    });

    e.preventDefault();

    var button = $(this);
    var nonce = $(this).data("nonce");

    // Disable the button
    button.prop("disabled", true);

    // Check the offset
    if (has_run == false) {
      button.data('offset', $(this).data("offset"));
      init_offset = $(this).data("offset");
    }

    // Perform AJAX request
    $.ajax({
      type: 'POST',
      dataType: 'json',
      url: ajax_load_more_object.ajax_url,
      data: {
        action: 'ajax_load_more_posts',
        security: nonce,
        init_offset: init_offset,
        offset: button.data('offset'),
      },
      beforeSend: function (xhr) {
        console.log('Loading more posts...')
        button.text('Loading');
      },
      success: function (response) {
        console.log(response);
        button.text('Load more');

        // An array to store new items added via AJAX
        var new_items = [];

        // Run through JSON
        $.each(response, function (key, value) {

          var $new_item = $(`<div class="grid-item article-post-card ${value.category[0]['slug']}">
                                <a class="article-post-card__anchor" href=" ${value.permalink}" alt="${value.title}">
                                     <div class="article-post-card__featured-image-container">
                                        <div class="article-post-card__overlay"></div>
                                        <div class="article-post-card__featured-image">
                                            ${value.thumbnail}
                                        </div>

                                        <div class="article-post-card__category-label">
                                            ${value.category[0]['name']}
                                        </div>

                                    </div>

                                     <div class="article-post-card__content-wrapper">

                                        <div class="article-post-card__publish-date">
                                            <time class="updated" datetime="">${value.date}</time>
                                        </div>

                                        <div class="article-post-card__title">
                                            ${value.title}
                                        </div>

                                        <div class="article-post-card__excerpt">
                                          ${value.introduction}
                                        </div>

                                    </div>
                                </a>
                            </div>`);

          new_items.push($new_item[0]);
        });

        // Add the new items to the grid
        $grid
          .isotope('insert', new_items)
          .imagesLoaded().progress(function () {
            $grid.isotope('layout');
          });

        // Undo Button Disable
        button.prop("disabled", false);

        // Set Offset
        var offset = button.data("offset");
        button.data("offset", offset + 10);

        // Script has run
        has_run = true;

        return false;
      },
      error: function (xhr, status, error) {
        console.log("There was an error", error);
      }
    });
  });
});

If you guys could critique I think this would be useful for others too.

Reading Time: < 1 minute

I have spent the better part of 2 hours trouble shooting WordPress frontend ajax bad request issue. The wonderful error 400. I’ll show you how I fixed my issue as I didn’t find the WordPress or stack overflow communities particularly helpful.

Resolving the Bad Request Error

//....ENQUEUE YOUR JAVASCRIPT SCRIPT // Todo: edit the location of your javascript file. function rfr_public_enqueue_scripts() { wp_enqueue_script('rfr-ajax-public', plugins_url('public/assets/js/rfr-frontend.js', __FILE__), array('jquery'), NULL, true); wp_localize_script('rfr-ajax-public', 'rfr_ajax', array( 'url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('rfr_ajax_public_nonce'), )); } add_action('wp_enqueue_scripts', 'rfr_public_enqueue_scripts');

Code language: PHP (php)

The next part you need is the handler function. This can include whatever you want. It’s not special – it’s NAME is very special.

//...SET UP YOUR HANDLER FUNCTION function rfr_ajax_public() { if (!wp_verify_nonce($_POST['nonce'], 'rfr_ajax_public_nonce')) { error_log("Invalid or no nonce"); die(); } if (!$_POST['do']) die('No do do in your action.'); switch ($_POST['do']) { case 1: //do fetch echo json_encode(['status' => 'grand']); exit; break; } wp_die(); }

Code language: PHP (php)

In the second argument, you’ll find the name of our handler function.

//... add_action('wp_ajax_rfr_ajax_public', 'rfr_ajax_public'); add_action('wp_ajax_nopriv_rfr_ajax_public', 'rfr_ajax_public');

Code language: JavaScript (javascript)

When you do the javascript part, most articles lead me down a dark path of adding every ajax header, content-type and other attribute going. It seems that was all a waste of time. Thanks internet! You only need what is below

The ACTION must match your handler PHP FUNCTION. Can’t stress this enough. That was the key ingredient I was missing and wasted a large portion of my life resolving.

//... JAVASCRIPT $.ajax({ dataType: "json", type: "POST", url: rfr_ajax.url, data: { nonce: rfr_ajax.nonce, action: 'rfr_ajax_public', //payload: payload, //do: 1, }, success: function (resp) { console.log(resp); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(textStatus+" "+errorThrown); } });

Code language: JavaScript (javascript)

There is more you can do to get build this Ajax example up but hopefully it resolves your WordPress Ajax Bad Request Error

Понравилась статья? Поделить с друзьями:
  • Air susp inactive рендж ровер ошибка
  • Ajax отлов ошибок
  • Al03 ошибка при работе посудомойки
  • Ajax выдает ошибку
  • Air sus хино ошибка 500