AJAX in WordPress only returns 0 - javascript

I'm trying to utilize WordPress's admin-ajax feature in order to build a dynamic admin panel option-set for a plugin. Essentially, once an option is selected from a dropdown (select/option menu), PHP functions will sort through and display more dropdown menus that fall under the dropdown above it. I began with a simple return that I was hoping to utilize later down the line, but I can't seem to get the text to print out without running into unidentified issues.
The AJAX I set up puts out a 200 status but the response never builds, and I'm left with 0 as my result. Here's the code:
JS/jQuery built into PHP function ajax-action()
$ = jQuery;
$('#platform').change(function(e) {
var data = {
action: 'action_cb',
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
PHP functions and add-actions
add_action('wp_ajax_action_cb','action_cb');
add_action('admin_footer','ajax_action');
function action_cb() { $platform = 'test'; echo json_encode($platform); wp_die(); };
My question is: how can I fix this and prevent it from continuing to happen? I'd like to return the actual results and not 0.

As per the wordpress documentation:
https://codex.wordpress.org/AJAX_in_Plugins (Reference "Error Return Values")
A 0 is returned when the Wordpress action does not match a WordPress hook defined with add_action('wp_ajax_(action)',....)
Things to check:
Where are you defining your add_action('wp_ajax_action_cb','action_cb');?
Specifically, what portion of your plugin code?
Are you logged into wordpress? You mentioned the admin area, so I'm assuming so, but if you are not, you must use add_action('wp_ajax_nopriv_{action}', ....)
Additionally, you didn't share the function this is tied to:
add_action('admin_footer','ajax_action');
And lastly, why are you using "json" as the data type? If you are trying to echo straight HTML, change data type to 'html'. Then you can echo directly on to page (or as a value as you are doing). Currently, you are trying to echo a JSON object as a value in the form...
So your code would look like so:
function action_cb() { $platform = 'test'; echo $platform; p_die(); };
...and your AJAX could be:
<script type = "text/javascript">
jQuery.ajax({
url: ajaxurl,
type: 'post',
data: {'action' : 'action_cb'},
success: function (data) {
if (data != '0' && data != '-1') {
{YOUR SUCCESS CODE}
} else {
{ANY ERROR HANDLING}
}
},
dataType: 'html'
});
</script>
Try This:
<script>
$ = jQuery;
$('#platform').change(function(e) {
var data = {
data: {'action' : 'action_cb'},
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
</script>

Probably you need to add
add_action('wp_ajax_nopriv_action_cb', 'action_cb');
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

just make small change in your AJAX. I am assuming you're logged in as admin.
replace action in data object with data:"action=action_cb",
var data = {
data:"action=action_cb",
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl,data,function(data){
$('#user_id').val(data);
});

To prevent WP adding zero into response i always using die(); insted of wp_die();
and registering function:
add_action( 'wp_ajax_action_cb', 'action_cb_init' );
add_action( 'wp_ajax_nopriv_action_cb', 'action_cb_init' );
function action_cb_init() {
}
When calling to function with AJAX use action: 'action_cb'

Hope this helps. I have already explained standard way of using ajax in wp.
Wordpress: Passing data to a page using Ajax

Ok, I have been recreating your code now in my own project and noticed that the javascript you shared returned the ajax-object and not the results. So what I come up with is a bit rewriting, but is worked fine when I tried it.
$j = jQuery.noConflict();
$j('#platform').change(function(e) {
$j.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'action_cb',
}
}).done(function( data ) {
// When ajax-request is done.
if(data) {
$j('#user_id').val(data);
} else {
// If 0
}
}).fail(function(XMLHttpRequest, textStatus, errorThrown) {
// If ajax failed
console.log(errorThrown);
});
e.preventDefault();
});
I hope the comments explain good enough how it is working. Note how I'm using $j instead of just $ for the jQuery.noConflict mode.

For those by the "Load More" problem.
Normally "0" is used instead of false.
I found such a solution.
So that 0 does not come. Try this code with false.
PHP
ob_start(); // start the buffer to capture the output of the template
get_template_part('contents/content_general');
$getPosts[] = ob_get_contents(); // pass the output to variable
ob_end_clean(); // clear the buffer
if( $read == $articles->found_posts )
$getPosts[] = false;
JS
if( posts[i] == false )
$(".load_more_button").fadeOut();

Related

AJAX POST group of form variables to PHP

I am trying to send a group of form parameters over to a PHP script for processing.
I've previously done something like this using $.post, but now I'm trying to get it done strictly by using $.ajax.
Here is the jQuery click event that is supposed to send all of the variables to the PHP script:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
Here is the PHP script, called railmbs.php:
<?php
if(isset($_POST['searchCriteria']))
{
$value = $_POST['searchCriteria'];
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($value['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($value['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($value['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Not sure what I am doing wrong. If I echo hello before the IF above, the console will output accordingly. But I cannot seem to get anything to echo from inside the IF.
Does anyone see my error?
You are not setting the "searchCriteria" variable.
Change this:
$('.searchSubmit').on('click', function()
{
var searchCriteria = {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: searchCriteria, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
});
to:
$('.searchSubmit').on('click', function()
{
var data = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}
};
$.ajax({
url: 'api/railmbs.php', // process script
type: 'POST',
data: data, // parameter group above
dataType: 'html' // had this set to json, but only got fail
success: function(data, textStatus, jqXHR)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail');
}
});
First of all. Why not to use $("form").serialize()? It would be much cleaner.
Secondary, you transfer data in root object, so to get you values, check $_POST array.
Instead of $value = $_POST['searchCriteria'] use $value = $_POST;.
This PHP code should work:
<?php
if(isset($_POST))
{
$_SESSION['where'] = "";
$import_bill = mysqli_real_escape_string($dbc, trim($_POST['import_bill']));
$import_ramp = mysqli_real_escape_string($dbc, trim($_POST['import_ramp']));
$import_delivery = mysqli_real_escape_string($dbc, trim($_POST['import_delivery']));
echo $import_bill; // just trying to echo anything at this point
}
?>
Or modify your js to send data in searchCriteria object, like this:
var searchCriteria = {
searchCriteria: {
import_bill: $('#import_bill').val(),
import_ramp: $('#import_ramp').val(),
import_delivery: $('#import_delivery').val(),
// few more form parameters
}};
You should check if you actually send post data using your browser developer tools or typing var_dump($_POST); at the beginning of your PHP script.
As far as i can see, you never actually set searchCriteria as post variable.
Currently your $_POST variable should contain the field import_bill, import_ramp and so on. Either change your if statement or your JavaScript object to {searchCriteria: {/*Your data here*/}.

how can I trigger javascript css action?

I have a memory game code, using javascript, php and css.
I would like to register somehow the event when the game is finished by php so that I can save the results in database.
In other words I would like to place php code inside <div id="player_won"> </div> and trigger that winning event properly.
css
#player_won{
display: none;
}
javascript
$(document).ready(function(){
$(document).bind("game_won", gameWon);
}
function gameWon(){
$.getJSON(document.location.href, {won: 1}, notifiedServerWin);
var $game_board = $("#game_board");
var $player_won = $("#player_won");
$game_board.hide();
$player_won.show();
$game_board = $player_won = null;
};
You'll want to create an ajax call that sends some information from the page and tells the php file below if the player has won or lost. After which you can deal with the logic needed for the player inside foo.php and send back Json to the success function inside the ajax call and update your page accordingly.
index
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#SomeId', function () {
//Get the information you wish to send here
var foo = "test";
$.ajax({
url: "/foo.php",
type: 'POST',
cache: false,
data: {Info: foo},
dataType: 'json',
success: function (output, text, error)
{
//here is where you'll receive the son if successfully sent
if(ouput.answer === "yes"){
$("#player_won").show();
} else {
// Do something else
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
});
foo.php
<?php
if(isset($_POST['Info'])){
//figure out if what was sent is correct here.
if($_POST['Info'] === "test"){
$data['answer'] = "yes";
echo json_encode($data);
exit;
} else {
// do something else
}
}
?>

Returning values from a PHP script for an AJAX method: What am I doing wrong here?

From everything I've read on the internet, the way of returning HTML, JSON, etc., from a PHP script is simply by echoing it. I can't get it to work, however.
My JS is
jQuery('#new-member').submit(
function()
{
var formUrl = jQuery(this).attr('action');
var formMethod = jQuery(this).attr('method');
var postData = jQuery(this).serializeArray();
console.log(postData); // test for now
jQuery.ajax(
{
url: formUrl,
type: formMethod,
dataType: 'json',
data: postData,
success: function(retmsg)
{
alert(retmsg); // test for now
},
error: function()
{
alert("error"); // test for now
}
}
);
return false;
}
);
and I've verified that it is correctly calling my PHP script, which as a test is simply
<?php
echo "Yo, dawg.";
?>
but all that does is open "Yo, dawg." in a new page. The expected behavior is for it to alert that message on the same page I was on. What am I missing here?

Undefined index: Error in ajax POST and/or php script?

I'm trying to send an ajax POST to a php file, however the php file sends a notice of "undefined index", and the php file never seems to receive the value i'm trying to send it. I've been searching for the answer to why this isn't working correctly, so hopefully someone can give me some insight.
My javascript function receives a value from the html, and receives the correct value. (it's "1" in this case)
function deleteMediaFromDatabase(val)
{
$.ajax({ url: 'deleteMediaFromDatabase.php',
data: {vals : val},
type: 'post',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
}
Here is part of my php file that should receive the post:
<?php
ini_set("display_errors", "On");
error_reporting(E_ALL);
$val = $_POST["vals"];
// create connection
$con = mysqli_connect(<stuff you don't care about>);
error_log($val . ' is the value', 3, "./error.log");
?>
I am, however getting this error message from php:
Notice: Undefined index: vals in
/xxx/xxx/htdocs/AdminPanel/deleteMediaFromDatabase.php on line 9
And my javascript always outputs the alert in the error: "Error: Could not delete"
I know this question has been asked and answered many times, however unless I'm skipping over something small, my code, to me, looks correct. (but doesn't it always...)
There is error in syntax of jquery.. You missed out syntax of data. This should be like this-
function deleteMediaFromDatabase(val)
{
$.ajax({ url: 'deleteMediaFromDatabase.php',
data: {'vals' : val},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
}
The problem can come from the dataType not being specified or that the dataType specified does not match thus returned by the server.
Explicitely set the dataType, e.g.
dataType:'json'
and make sure that your script returns data that is "encoded" in the data type that you chose, e.g. in PHP:
echo json_encode($something);
Instead of:
$val = $_POST["vals"];
use this:
if (isset($_POST['vals']) {
$val = $_POST['vals'];
}
Change Ajax syntax...
$.ajax({
type: "POST",
url: 'deleteMediaFromDatabase.php',
data: {'vals' : val},//Have u tried this
success: function(output) {
alert(output);
}
error: function(request, status, error){
alert("Error: Could not delete");
}
);
$val = $_POST["vals"];
I got same problem , i tried declaring the variable as global , that solved my problem.
global $val;
$val = $_POST["vals"];
and always check isset($_POST["vals"])

jquery .ajax always returns error - data being added to database

I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});

Categories