ajax sending 400 bad request error in wordpress - javascript

Hi everyone i am trying to use ajax in wordpress and got stuck in something. My code is giving me an error in console as
jquery-3.3.1.js:9600 GET http://localhost/wordpress/wp-admin/admin-ajax.php 400 (Bad Request)
send # jquery-3.3.1.js:9600
ajax # jquery-3.3.1.js:9206
(anonymous) # main.js?ver=1:27
dispatch # jquery-3.3.1.js:5183
elemData.handle # jquery-3.3.1.js:4991
I looked into the source and it is showing me the error on this line
xhr.send( options.hasContent && options.data || null );
This is my jquery
$('#retrieve_users').click(function() {
$.ajax({
type: "GET",
url: scriptData.ajaxurl,
action : 'retrieveUsersData',
dataType: "html", //expect html to be returned
success: function(response)
{
$("#users_data").html(response);
//alert(response);
}
});
});
This is my php code in functions.php file
function retrieveUsersData(){
echo "ajax responding";
}
add_action('wp_ajax_retrieveUsersData','retrieveUsersData');
add_action('wp_ajax_nopriv_retrieveUsersData', 'retrieveUsersData');
and this is my html
<button id="retrieve_users">Watch Users</button>
<div id="users_data"></div>
Please help!! I didnt know how to import jquery src link in wordpress using wp_enque_scripts so i pasted the with jquery src directly in html. I hope its not creating problem
Please help.. i would really appreciate it. Thank you

Change your code to use POST and in the body of the request use the action key :
jQuery.ajax({
url: scriptData.ajaxurl,
type: "POST",
dataType: 'html',
data: {
action: 'retrieveUsersData'
},
...
});
Also you should use wp_die() in the function to prevent the 0 to be echoed.
function retrieveUsersData(){
echo "ajax responding";
wp_die();
}

Related

PUT type request with a file in AJAX arrives without data

I am making a request in a Laravel form (Blade).
To create the object I use a POST type request but to modify it I use a PUT type request.
I have to use AJAX and I have to send a file in the same request.
I have searched for information and with the POST type, it works correctly, but with the PUT type the request is empty.
I have been researching and testing and I have realized that the problem comes from this line of code within my "processData: false," request.
The problem is that if I don't put this line I get the error "Uncaught (in promise) TypeError: Illegal invocation".
That it was the same error that appeared in the POST request, so searching the internet I solved it like this.
Could someone help me to make the PUT request with the attached file?
My code:
const type_request = 'PUT';
const url_request = '{{ route('put_update_login', ['client' => $client, 'id' => $login->id]) }}';
let data_form = new FormData(document.getElementById(id_form));
$.ajax({
type: type_request,
url: url_request,
data: data_form,
dataType: "json",
processData: false,
contentType: false,
success: function(response) {
if (response.hasOwnProperty("route")) {
window.open(response['route'], "_self").focus();
} else {
$('#alert_error').removeAttr('hidden');
$("#alert_error").fadeTo(20000, 500000);
let errors = response['errors'];
$.each(errors, function (index, value) {
$("#alert_error").last().html(value);
});
$(':button').prop('disabled', false);
$('#spinner_form').prop('hidden', true);
}
}
});
The differences between the POST and PUT version is the "type_request" and the "url_request".
Thanks in advance

Ajax and PHP, post request not working

So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});

jQuery AJAX call to Slim Framework

I am trying to use Slim in my project and I am having trouble getting the AJAX call set up correctly:
$.ajax({
url: "/api/addresses/",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: {QID: QID, departmentID: departmentID}
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
...
My Slim File looks like so:
require_once('Slim3.php');
function loadEndpoint()
{
global $app;
//fetch
$app->post('/addresses', function($request, $response, $args){
$objDB = new DB;
$json = $objDB
-> setStoredProc("canvas_fetch_module_department_addresses")
-> setParam("QID", $args['QID'])
-> setParam("departmentID", $args['departmentID'])
-> execStoredProc()
-> parseXML();
return $response->write($xml);
});
}
I don't even see the AJAX call being made in my console so I assume that is where the problem is. Anything noticeable with the setup?
I've faced same problem using AJAX and SLIM:
Remove '/' from calling URL "/api/addresses"
If there is no error in API I hope this will fix your issue?
Read this for more detail: http://help.slimframework.com/discussions/problems/7071-optional-route-parameters-force-either-or-no-in-urls

ajax data sent wont work

below is an ajax but it wont work, what seems be the problem? assume that I have requestparser.php and inside it i have "echo "yes ajax work!";".
$(document).ready(function(){
// start ajax form submission
$.ajax({
url: "requestparser.php",
type:"POST",
data: ({ "pulldata" : "oy" }),
success:function(e){
if(($.trim(e)=="success")){
alert("yes");
}else{
alert("no");
}
},error:function(){
alert("error");
}
});
});
as above ajax function ,the process should be, on load it will send first a post request to requestparser.php with a post name of "pulldata" and post content of "oy" and when the requestparser receive that post request from the ajax so then respond with "yes ajax work!" and since the respond from requestparser.php is not equal to success then it should display "no".
any help would be greatly appreciated
I tried to debug your code and it worked fine for me. So can you try this code and say what error it shows ?
$(document).ready(function () {
$.ajax({
url: "test.php",
type: "POST",
data: ({
"pulldata": "oy"
}),
success: function (e) {
console.log(e);
},
error: function (e) {
console.error(e);
}
});
});
test.php
<?php
var_dump($_POST);
One more thing, just for confirmation, you have included jQuery in your page before using ajax right ?

Jquery Ajax in Laravel 4 - NotFoundHttpException

.Hello y'all. I'm trying to learn ajax and am currently trying to have an input in a form be sent via a route to a controller and then echoed in a div.
For some reason I am getting a NotFoundHttpException error when I press the submit button for the form and am having trouble seeing what is wrong with my route.
If anyone can point out where I'm going wrong it would be greatly appreciated! Thank you!
View:
<form id="edit_price_form" method="POST" action="">
<input name="new_price" id="new_price"/>
<input type='submit' class='button tiny radius' id='edit_price_button'/>
</form>
Ajax request:
$(document).ready(function(){
$("#edit_price_form").submit(function(e) {
e.preventDefault();
//form_data
var form_data = $('#edit_price_form').serializeArray();
$.ajax({
url: 'edit_prices',
type: "POST",
dataType: "html",
data: form_data,
success: function(data){
$("#edit_results").html(data);
$("#edit_results").addClass('panel callout radius');
},
error: function(xhr, status, error){
console.log(xhr);
console.log(status);
console.log(error);
}
});
});
});
Route:
/*Ajax Edit Price on Price Page*/
Route::post('edit_prices', array(
'as' => 'edit_prices',
'uses' => 'PriceController#edit_prices'
));
Controller:
public function edit_prices(){
$new_price = Input::get('new_price');
echo $new_price;
}
Thanks again!
The problem lies in your HTTP method. You're AJAX request looks like this:
$.ajax({
url: 'edit_prices',
type: "PUT",
...
But your route looks like this:
Route::post('edit_prices', array(
'as' => 'edit_prices',
'uses' => 'PriceController#edit_prices'
));
In short, you'll need to change your AJAX request from PUT to POST - Laravel is rejecting the PUT request because it's expecting POST.

Categories