Return a value from php to $.get - php

Now I am upgrading my website user experience, so I'm trying modify my form from form action to ajax.
Coding now work fine, server side can update the database, but I don't know how to return the custom message to my user.
My html coding.
<form method="post" id="jnfarm_pop">
blablabla...
<button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn" onclick="login();">submit</button>
</form>
My php file plugin.php
<?php
//coding.....
$final = 'custom wording';
return json_encode(['final' => $final]);
?>
My jQuery
<script>
function login() {
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
alert($final); //it doesn't work
}).fail(result => {
alert('fail');
});
event.preventDefault();
}
</script>
Now the alert doesn't work, I am also try like
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
result = JSON.parse(result); alert(result.final); //not working also
}
and
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result = JSON.parse(result)) => {
alert(result.final); //this show alert unidentified
}
Can someone correct my coding?

Change
return json_encode(['final' => $final]);
to
echo json_encode(['final' => $final]);
return is really only useful when you're inside a PHP function. If you want to output something back to the caller of the script then you need to use echo, as always.

To make your example work do the following:
change your PHP code from
<?php
//coding.....
$final = 'custom wording';
return json_encode(['final' => $final]);
?>
to:
<?php
//coding.....
$final = 'custom wording';
echo json_encode(['final' => $final]);
?>
and your jQuery code from this:
<script>
function login() {
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
alert($final); //it doesn't work
}).fail(result => {
alert('fail');
});
event.preventDefault();
}
</script>
to this:
<script>
function login() {
jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
alert(result);
}).fail(result => {
alert('fail');
});
event.preventDefault();
}
</script>
PHP can return something to an ajax call by either printing or echoing. And ajax can't use variables you defined in PHP. The echo'ed value in your PHP script will be the result value in your ajax call.

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 );
//...
},
//...
});

Wordpress Ajax Request returns 0 in chrome, works fine in FF

I have a front-end Ajax call set up to randomize an image whenever a button is pressed. I set it up as follows:
Functions.php
define("AJAX_URL", admin_url('admin-ajax.php'));
add_action("wp_enqueue_scripts", "enqueue_eyewebz_scripts");
function enqueue_eyewebz_scripts()
{
wp_enqueue_script("jquery");
...
wp_enqueue_script("root-js", JS_URL . "/root.js", array("jquery"));
$script_params = array(
'ajax_url' => AJAX_URL
);
wp_localize_script('root-js', 'theme_vars', $script_params);
}
root.js
function parallax_randomize(e)
{
var data = {
'action': 'randomize_parallax',
'dataType': 'json'
};
console.log(theme_vars.ajax_url);
jQuery.post(theme_vars.ajax_url, data, function(response) {
console.log(response);
var dynb = JSON.parse(response);
jQuery('#front-location span').html(dynb.location);
jQuery('.parallax-slider').fadeOut('fast', function () {
jQuery('.parallax-slider').attr('src', dynb.url);
jQuery('.parallax-slider').fadeIn('fast');
});
});
}
Dynamic background callback
class Dynb
{
function Dynb()
{
...
$this->set_up_ajax();
...
}
public function set_up_ajax()
{
add_action('wp_ajax_randomize_parallax', array($this, 'randomize_parallax'));
}
public function randomize_parallax()
{
$data = set_dynamic_background(true);
echo json_encode($data);
wp_die();
}
}
new Dynb();
In Firefox, this works just fine, but in Chrome, my JS Ajax call returns 0. I can't for the life of me figure out what the problem is. Anyone?
just add exit() in randomize_parallax() function,i think it will fix your issue
When sending an ajax request from the front-end, you need to include an action that has wp_ajax_nopriv_ ... (shown below) if you want this to work. If you don't add that action, users that are not logged in will not be able to call for the ajax function.
add_action('wp_ajax_nopriv_randomize_parallax', array($this, 'randomize_parallax'));

Inserting Option via AJAX using Settings API

I am making a plugin and need to insert a value using the 'add_option()' function - or something that achieves the same result.
This is what I use to call my AJAX:
// localize script
wp_localize_script('button-js', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
And what launches the PHP function:
add_action('wp_ajax_process_form', array($this, 'process_ajax'));
I need to run add_option() in the function called after my AJAX runs (my AJAX code below):
function post(num) {
var data = {
action : 'process_form',
form_number : num
};
$.post(the_ajax_script.ajaxurl, data).error(
function() {
alert('error');
}).success(function() {
console.log(data);
});
return false;
}
And here is the function that is run by AJAX:
public function process_ajax() {
$num = $_POST['form_number'];
if(isset($num)) {
add_option('form-num', $num);
}
die();
}
My AJAX code runs successfully, and the correct values are logged to the console - however upon using
<?php echo get_option('form_num'); ?>
The value is blank.

jQuery AJAX request returns NULL from 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;
}

Redirecting in codeigniter

I have an issue redirecting to another page in codeigniter, this is my js:
<script type="text/javascript">
$(document).ready(function () {
var url = $('#baseurl').val();
var form = $('#customerinfo');
$('#next').click(function (e) {
if ($("form")[0].checkValidity()) {
// Prevent submit.
e.preventDefault();
//Start loading
var checkbox = $('#Accept');
if (checkbox[0].checked == true)
{
$.post(url + 'customerinfo/next', form.serialize(), function(response) {window.location.href=url + 'paymentinfo';});
}
else
{
$("#errmsg .msg").text("You need to read and accept the terms and conditions before you can continue!");
$("#errmsg").css("display", "block");
}
$(".loading-add-ticket").css("display", "block");
// Send request.
}
else console.log ( "invalid form" );
});
});
</script>
What it does:
When the next button is clicked it submits the form via ajax, the form is then processed on the server and upon completion the user is redirected using the following block of code:
<?php
class CustomerInfo extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
// Write to $title
$this->template->write('title', 'Customer Info');
// Write to $content
$this->template->write_view('content', 'tickets/customerinfo');
// Write to $sidebar
$this->template->write_view('sidebar', 'sidebar');
// Render the template
$this->template->render();
}
function next()
{
if ($_POST) {
if (isset($_POST['Accept']))
{
$data[0] = array(
'TravelInsurance' => $_POST['TravelInsurance'],
'LuggagePayment' => $_POST['LuggagePayment'],
'Donations' => $_POST['Donations'],
'FirstName' => $_POST['FirstName'],
'LastName' => $_POST['LastName'],
'CityTown' => $_POST['CityTown'],
'ContactNo' => $_POST['ContactNo'],
'Address' => $_POST['Address'],
'Accept' => $_POST['Accept']
);
$this->session->set_userdata('customerinfo', $data);
redirect(site_url('paymentinfo'));
}
}
}
}
?>
The problem:
The redirect never happens, when i check the post response using firebug in my browser i notice that the target page has been returned :
What i want: I need the page to be redirected to the target page, i am new to codeigniter so i do not know what i am doing wrong.
current fix:
In the success function on my ajax function i am using javascript to redirect to the next page but i do not want the redirects to be handled on the client side.
Somtimes with forms i prefer to use
header("Location: /Controller/method/value");
i know that's a dirty method but sometimes is helpful

Categories