jQuery AJAX request returns NULL from PHP - php

Here is the code I am working on for my Wordpress site:
jQuery:
jQuery(document).ready(function($)
{
var actionValue;
$(".tabRow li").on('click', function(event)
{
event.preventDefault(); //override default behaviour
var clicked = $(this); //caches click so we don't scan DOM again
if(clicked.attr('id')=="tabAddData") //tab1 clicked
{
actionValue = "tab1Clicked";
}
$("li").removeClass("selected");
clicked.addClass("selected");
alert ('starting ajax call');
$.ajax(
ajaxObject.ajaxurl, //request gets sent to this url
{ //start of [options]
type: 'POST',
dataType: 'json', //type of data expected back from server
//data to send to server (JSON format)
data:
{
action: 'ajaxAction',
nonce: ajaxObject.nonce,
actionName: actionValue
}
} //end of [options]
) //end ajax(), the other fuctions are chained to it (.done .fail .always)
.done (function(data)
{
alert ('success function');
if(actionValue == "tab1Clicked") //tab1 clicked
{
$('#dataSection').empty();
$('#dataSection').append(data);
}
}) //end of done (success) function
.fail (function(xhr, desc, err)
{
alert ('error function');
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}) //end of fail (error) function
}); //end of onclick
});
PHP:
<?php
$my_action='ajaxAction';
if(defined('DOING_AJAX') && DOING_AJAX)//check if AJAX is loaded and working
{
//for logged in users
add_action('wp_ajax_'.$my_action, 'ajaxResponse');
}
function ajaxResponse()
{
if(wp_verify_nonce($_POST['nonce'], 'ajaxAction'))
{
if($_POST['actionName'] == "tab1Clicked")
{
$addDataSection = getAddDataSection();
$response=array(
'status' => 'success',
'addDataSection' => $addDataSection
);
header('Content-type:application/json;charset=utf-8');
echo json_encode($response);//encodes the jQuery array into json format
die;
}
}
}
function getAddDataSection()
{
//lots of echo statements which builds the html code
}
?>
When I first load my page, my PHP function getAddDataSection() generates the HTML inside my <div id='dataSection>. This works fine.
When I click on tab1, my jQuery AJAX call is supposed to reuse the same PHP function to generate my HTML. This is not working fine.
After I click on tab1, the jQuery fail function is triggered.
When I check Firebug, the response data contains the html generated by my PHP function getDataSection(), followed by a JSON string
{"status":"success","addDataSection":null}
When replying, keep in mind I'm a newbie. Thanks :)
Updated to include Console error:
Details: parsererror
Error:SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data

I think I found a solution.
In my jQuery, I changed the dataType from json to html.
Then in my PHP, I changed this:
if($_POST['actionName'] == "tab1Clicked")
{
$addDataSection = getAddDataSection();
$response=array(
'status' => 'success',
'addDataSection' => $addDataSection
);
header('Content-type:application/json;charset=utf-8');//still works without this line
echo json_encode($response);//encodes the jQuery array into json format
die;
}
to this:
if($_POST['actionName'] == "tab1Clicked")
{
$addDataSection = getAddDataSection();
echo $addDataSection;
die;
}

Related

why WP Ajax data printed in the console instead of the page

this the first function of the Ajax call runs on focusout woocommerce input fields with check_country_fees action and url '<?php echo admin_url('admin-ajax.php'); ?>' so how to pass the returned data and passing them as arguments normally?
function addEvtListenerToCheckoutPage()
{
?>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", (event) => {
$(document).ready(function() {
document.getElementById('billing_first_name').addEventListener("focusout", function() {
alert("Hello World!");
if (document.getElementById('billing_first_name') !== "") {
var billing_first_name = document.getElementById("billing_first_name").value;
alert("testajax");
var data = {
action: 'check_country_fees',
billing_first_name: document.getElementById("billing_first_name").value
};
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function(response) {
if (response.success == true) {
// Handle Success
// let resp = JSON.parse(response.data.json_response);
if (response.success) {
alert(response);
console.log(response);
alert(response);
alert("Sucess");
// Hanle Success Response
}
} else {
console.log(response);
console.log(data);
alert("Sucess");
}
}).fail(function(response) {
// Handle Error
console.log("failing");
console.log(response);
alert("FAIl");
});
}
});
});
});
// document.getElementById("#billing_first_name").addEventListener("input", myFunction);
</script>
<?php
?>
<script language="javascript">
alert("sended addevent");
</script>
<?php
}
when I run the action call function add_action('wp_ajax_check_country_fees', 'testing_ajax_action'); the result printed in the browser console like that
</script>
<script>
alert("sended datasuccess");
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
testing ajaaaaxnullArray
(
[action] => check_country_fees
[billing_first_name] => Stevea
)
Stevea</br>
<script>
alert("test ajaxbilling name");
</script>
SteveaArray
(
)
Receiving data function
function testing_ajax_action()
{
echo "testing ajaaaax";
if (isset($_POST['billing_first_name'])) {
$billing_first_name = $_POST['billing_first_name'];
$billing_first_name = json_decode($billing_first_name);
extract($_POST);
print_r($_POST);
$billing_first_name2 = json_decode($_POST['billing_first_name_post']);
//testingajax($billing_first_name);
testingajax($billing_first_name);
} else {
return 0;
}
}
You need to send the data back from the backend to the frontend.
Here is a crude basic diagram of an ajax request:
Event → JS request → PHP Processing → PHP Response → JS Handling
If you're not sending any data with your PHP response then you can't handle it on the front end.
You can use wp_send_json_success() and wp_send_json_error() to send the appropriate response success/error status and attach to it any relevant data you want to handle on the front end.
By convention, the PHP Processing function is usually anonymous.
From a security standpoint you should implement a nonce system too. You can refer to the following answer about using Ajax the right way in WordPress.
Coming back to your problem, you can pass an array through wp_send_json_success.
<?php
add_action( 'wp_ajax_{$action}', function () {
if ( check_ajax_referer( '_ajax_nonce' ) ) {
//...
$data = array(
'timestamp' => time(),
'key' => 'value',
//...
);
wp_send_json_success( $data );
} else {
wp_send_json_error();
};
} );
On the javascript handling side, you would intercept it and do something with it:
$.ajax({
//...
success: ( response ) => {
console.log( response.data );
//...
},
//...
});

my ajax call is getting correct response but isn't doing anything

I'm trying to make a like/dislike button in ajax. The ajax is sending my data to a separate file where it is saved in a database and that file sends back the successful response {"status":"success","message":"Like has been saved.","data":{"like":"1"}} that I got from the chrome network response window. However the code in $ajax(...).done isn't working
I have console.logged and var.dumped every bit of code i possibly could. my data IS being sent to my database which should mean that the SQL and the like class is correct. I've also tried simply console.log 'ging the response "res" and putting the rest in comments, but that again gives me nothing
<div>
Like
Dislike
<span class='likes' data-id="<?php echo $post->id ?>"><?php echo $post->getLikes(); ?></span> people like this
</div>
$("a.like, a.dislike").on("click",function(e){
var postId = $(this).data("id");
if($("a.like")){
var type = 1;
}else if($("a.dislike")){
var type = 0;
}
var elLikes = $(this).siblings(".likes");
var likes=elLikes.html();
$.ajax({
method: "POST",
url: "ajax/postlike.php",
data: {postId: postId, type:type},
dataType: "json",
})
.done(function( res ) {
console.log(res);
if(res.status=="succes"){
console.log(res);
if(res.data.like=="1"){
likes++;
elLikes=html(likes);
$("a.like").css("display","none");
$("a.dislike").css("display","inline-block");
} else if(res.data.like=="0"){
likes--;
elLikes=html(likes);
$("a.dislike").css("display","none");
$("a.like").css("display","inline-block");
}
}
});
e.preventDefault();
});
if(!empty($_POST)){
try {
$postId=$_POST['postId'];
$type=htmlspecialchars($_POST['type']);
$userId=$_SESSION['user_id'];
$l = new Like();
$l->setPostId($postId);
$l->setUserId($userId);
$l->setType($type);
$l->save();
$res = [
"status" => "success",
"message" => "Like has been saved.",
"data" =>[
"like" => $type
]
];
}catch (trowable $t) {
$res = [
'status' => 'failed',
'message' => $t->getMessage()
];
}
echo json_encode($res);
var_dump($res);
}
what I expected to happen was that Ajax sent the JSON data to the php code, that put it in a database, which works. Then gives a successful response to the Ajax, also works. The Ajax would then switch out the like/dislike buttons whilst adding or taking 1 like from the span "likes". It however does absolutely nothing
I'm almost 100% certain that the problem is something stupid that I'm overlooking, but i really can't find it.
Typo in 'success' in on line: if(res.status=="succes"){
you can try with this:
error: function(xhr, status, error) {
console.log(error)
},
success: function(response) {
console.log(response)
}
in your Ajax function, to know what happen in the server side with the response.
If you specify a return data type for the ajax request to expect, and the actual returned value isn't what you specified, then your error/fail function will be triggered if you have one. This is because adding dataType: "json" causes you're ajax try and parse your return value as json and when it fails, it triggers your error handler. It's best to omit the dataTaype and then add a try catch with JSON.parse in your done function, to get around this.
E.G
.done(function (string_res) {
console.log(string_res);
try {
var json_obj = JSON.parse(string_res);
console.log(json_obj);
} catch (e) {
console.log('failed to parse');
}
// do work/operations with json_obj not string_res
})
.fail(function (jqXHR, textStatus) {
console.log('failed')
});

Why the static message is not coming from ajax file if no data found in mysql database?

I have a very strange problem and couldn't figure it out. I am working with AJAX/PHP and fetching the data from mysql database on user interaction by ajax call. Everything is working very fine and no problem at all. But only one issue which is persisting is when the data is not found in mysql database, then a user-friendly message is not returned from the server ajax file - the one part works and other doesn't. Here is my code -
This is my first file where the form reside (full code is not there; only js code) -
<script type="text/javascript">
$(document).ready(function(){
$("#selcustomer").change(function(){
var customers_id = $(this).val();
if(customers_id > 0)
{
$.ajax({
beforeSend: startRequest,
url: "ajax/ajax.php",
cache: false,
data: "customers_id="+customers_id,
type: "POST",
dataType: "json",
success: function(data){
if(data != "No result found.")
{
$("#img_preloader").hide();
$("#error").html('');
// $("#txtfname").val(data.fname);
// $("#txtlname").val(data.lname);
for(var key in data)
{
document.getElementById("txt"+key).value = data[key];
}
}
else
{
$("#img_preloader").hide();
$("#error").html(data);
$("input").each(function(){
$(this).val('');
});
}
}
});
}
else
{
$("#error").html('');
$("input").each(function(){
$(this).val('');
});
}
});
});
function startRequest()
{
$("#img_preloader").show();
}
</script>
And this is my server-side ajax file (php file) which interacts with database -
<?php
include("../includes/db-config.php");
if(isset($_POST["customers_id"]))
{
$customers_id = $_POST["customers_id"];
$query = "SELECT * FROM `tb_customers` WHERE `customers_id` = '$customers_id'";
$rs = mysql_query($query);
if(mysql_num_rows($rs) > 0)
{
$row = mysql_fetch_array($rs);
$customers_first_name = $row['customers_first_name'];
$customers_last_name = $row['customers_last_name'];
$customers_email_id = $row['customers_email_id'];
$customers_phone_no = $row['customers_phone_no'];
$customers_address_line_1 = $row['customers_address_line_1'];
$customers_address_line_2 = $row['customers_address_line_2'];
$customers_country = $row['customers_country'];
$data = array('fname' => $customers_first_name, 'lname' => $customers_last_name, 'emailid' => $customers_email_id, 'phoneno' => $customers_phone_no, 'addressline1' => $customers_address_line_1, 'addressline2' => $customers_address_line_2, 'country' => $customers_country);
echo json_encode($data);
}
else
{
echo "No result found.";
}
}
?>
The if part is working fine but when no data is found in database the else part is not sending the data back to jQuery code. I checked in browser console and saw the else part is returning the response but the jquery code in success: part of $.ajax is not running - neither within if, nor in else and also not outside of if/else. I mean to say that a simple alert is not fired with data under success when no data is found in mysql database. But when i remove all the data in ajax/php file and say simply write 123 then alert comes with 123 but not when the actual code is there. Can you plz tell me what is the issue behind this strange problem?
Your datatype is set to JSON in your AJAX call, so the return value must be a valid JSON.
When you are encountering the else condition, you are returning something that is not JSON.
Try this -
else
{
echo json_encode("No result found.");
}
Or something more flexible-
else{
echo json_encode(Array("err"=>"No result found."));
}
EDIT-
...But when i remove all the data in ajax/php file and say simply write
123 then alert comes with 123...
That is because a 123 (number) is valid JSON. Instead of 123, try writing No result and an error would be thrown, because No result (a string) needs quotes(which is taken care when you use json_encode).

Pass data from JQuery to database via Javascript/AJAX/JSON/PHP

I am attempting to add data to my database from my HTML code via the use of JQuery, AJAX/JSON and PHP using an MVC model. Below is a small sample of what I am looking to achieve.
In my front end I have a checkbox with different options and a button named 'Add'. The selected elements from here are picked up by a Javascript function, which I have tested properly, once this is done I call another Javascript function to do the AJAX/JSON . What I am still fresh on is the actual AJAX/JSON process that sends the data to PHP.
My Javascript function:
function add_fruits(fruit_name, fruit_type){
var success = "Fruit added";
var error = "Fruit not added";
var params = {
'fruit_name' : fruit_name,
'fruit_type' : fruit_type
};
$.ajax({
type: "POST",
url: "add_fruits.php",
async: false,
data: params,
success: function(success){
alert(success);
},
error: function(error){
alert(error);
}
});
}
My PHP function:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
require_once 'lib/connection_files.php';
if($_SERVER['REQUEST_METHOD'] =='POST')
{
$fruit_name = no_sql_injection($_POST['fruit_name']);
$fruit_type = no_sql_injection($_POST['fruit_type']);
$fruits = new fruits();
$result = $fruits->add_fruits($fruit_name, $fruit_type);
$tmp = mysql_num_rows($result);
if($result == 1)
{//RESULT must return 1 to verify successful insertion to database
//send confirmation to front end
}
else
{
//send error message to front end
}
}
else{
//tell front end there was error sending data via AJAX
}
?>
Note that the add_fruits() function takes care of doing the Queries to the database, I did not include it here because it is irrelevant to my issue.
Just do echo in your PHP:
PHP
else {
//send error message to front end
echo "Error Adding Fruits";
}
JS
success: function(data) {
if (data == "1") {
//data added to db
}
else {
alert(data);
}
}

Associative array from PHP to Javascript using JSON

I'm trying to send an associative array from PHP to Javascript. But, for some reason, the output is Undefined. Here's the code:
PHP (Suppositional array):
$validationErrors = array("unregisteredName" => NULL,
"unregisteredEmail" => "Invalid e-mail", "unregisteredUsername" => NULL,
"unregisteredPassword" => NULL);
$log = array("errors" => $validationErrors);
echo json_encode($log);
Javascript:
var addUserCallback = function(data) {
if(data.errors && data.errors.length) {
$.each(data.errors, function(index, error) {
console.log(error);
$("#"+index).attr("placeholder", error);
});
}
else {
window.location="/users/success/";
}
};
var errorCallback = function(xhr, status, error) {
console.log(arguments);
};
self.addUser = function() {
var data = {
unregisteredName: $("#unregisteredName").val(),
unregisteredEmail: $("#unregisteredEmail").val(),
unregisteredUsername: $("#unregisteredUsername").val(),
unregisteredPassword: $("#unregisteredPassword").val()
};
$.post(addUserUrl, data).success(addUserCallback)
.error(errorCallback);
}
And here is what I get from Chrome's Inspector:
data: "↵{"errors":{"unregisteredName":null,"unregisteredEmail":"Invalid e-mail.","unregisteredUsername":null,"unregisteredPassword":null}}"
data.errors: Undefined
So, what's happening is that, even getting data on "data" variable, because of the fact that it is unformatted it always redirects to the "success" page.
Any ideas?
You need to tell jQuery to parse the JSON string.
$.post(addUserUrl, data, 'json').success(addUserCallback).error(errorCallback);
Though I usually pass the success callback to $.post
$.post(addUserUrl, data, addUserCallback, 'json').error(errorCallback);

Categories