Wordpress update_user_meta onclick with Ajax - javascript

I'm attempting to update_user_meta via Ajax call in Wordpress.
I keep getting a 'success!' console log, but no data is returned and the user meta field is not being updated.
general.js on a button click:
var newViewPreference = jQuery(this).attr('id');
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: {
'action':'update_view_pref',
'viewPref' : newViewPreference
},
success:function(data) {
console.log(data);
console.log("success!");
},
error: function(errorThrown){
console.log(errorThrown);
console.log("fail");
}
});
functions.php
add_action( 'wp_ajax_update_view_pref', 'update_view_pref');
function update_view_pref() {
if(empty($_POST) || !isset($_POST)) {
ajaxStatus('error', 'Nothing to update.');
} else {
try {
$user = wp_get_current_user();
$viewPref = $_POST['viewPref'];
if ($viewPref == 'toggle-grid') {
update_user_meta( $user->ID, 'wpcf-shop-view-preference', 'grid' );
} elseif ($viewPref == 'toggle-list') {
update_user_meta( $user->ID, 'wpcf-shop-view-preference', 'list' );
}
die();
} catch (Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
}
Anyone able to pinpoint where I'm going wrong? Thanks.

Changing $_POST to $_REQUEST worked.
Can anyone explain why $_POST didn't work but $_REQUEST did?
I was submitting the data to the ajax request via a button click (not a form).

Related

JavaScript with Ajax call to the WordPress API

I'm making a Wordpress plugin named "customposttype" that makes a custom post type with 3 custom fields. The plugin also must do an Ajax call to the WordPress API and gets all the data from those posts in JSON format, to show them in a specific template called "shoplist.php".
My CPT is called "tienda", it has this url for the REST API: ...wp-json/wp/v2/tiendas.
I'm sure that I have several errors because it's my first time using an API and I'm very bad at Javascript.
I'm stuck just right here, I don't know how to continue developing it.
JS shows "Hello world!" at the console, but nothing else.
PHP
add_action("wp_ajax_nopriv_get_shop_data", "get_shop_data");
add_action("wp_ajax_get_shop_data", "get_shop_data");
function get_shop_data() {
$api_url = "https://pezquefuma.es/wp-json/wp/v2/tiendas";
$request = wp_remote_get($api_url);
$body = wp_remote_retrieve_body($request);
$output = json_encode($body, true);
echo $output;
die();
}
function my_enqueue() {
if ( get_page_template_slug() == 'shoplist.php' ) {
wp_enqueue_script( 'ajax-script', plugins_url('customposttype/js/filename.js'), array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('my-nonce')
)
);
}
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
JS
jQuery( document ).ready(function() {
console.log("Hello world!");
jQuery.ajax({
type : "GET",
dataType : "JSON",
url : my_ajax_object.ajax_url,
data : {
action: "get_shop_data",
},
error: function(response, error) {
console.log("wrong");
},
success : function(response) {
if(response.type === "success") {
console.log("Success");
}
}
});
});
There are two ways to check response data.
one is to use browser's network devtool and another is to use console.log
success : function(response) {
console.log(response);
}

My AJAX function keeps getting error as result

I'm new using AJAX or jQuery and I'm trying to insert some data in a table whitout loading another page, I can't tho.
Here is my AJAX func:
Edit:
function SumbitAction(act_id) {
$.ajax({
dataType: 'json',
type: "POST",
url: 'Accion.php',
data: {Action:act_id},
success: function (obj, textstatus) {
if(obj.status==='FAIL') {
console.log(obj.message);
}
else {
console.log("ok");
}
}
});
}
And in my PHP I'm giving no arguments at the moment to test a full null insert query: Edit:
$consultaAcciones= "INSERT INTO acciones VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
$ejecAcciones = mysqli_query($conn, $consultaAcciones);
if($ejecAcciones===false){
$response = [
'status' => 'FAIL',
'message' => 'Accion no registrada correctamente'
];
}
else {
$response = [
'status' => 'OK',
'message'=> 'Accion registrada'
];
}
header("Content-type: application/json");
echo json_encode($response);
I am getting "Error" in the console logs and I don't know what's wrong. Edit: No longer
Edit:
Now it doesn't display any error, it's okay, but also doesn't show my console logs for when everything's okay, also am getting a warning message:"Cross-Origin Read Blocking (CORB) blocked cross-origin response"
and a log: XHR finished loading: POST "http://url...".
may it be is not correct to specify the callers of my function this way?
function addListener(id,num)
{
var target= document.getElementById(id);
if(target){
target.addEventListener("click",SumbitAction(num),false);
}
else{
//console.log("Nel",id);
}
}
There are 2 problems in the code.
First, if(('error')) { will always evaluate as true. 'error' is just a string, and that is truthy.
You probably meant to compare that string against something, maybe (also removing doubled parentheses):
if (textstatus === 'error') {
Next, textstatus is the status of the request, not of your code. It will be error when, for eg, there is a 404, or a 500 response from the server. If your INSERT fails, the http request will still be successful, and textstatus will not be error.
You might want to check textstatus in an error() callback, if you want to add one. But within the success() callback, you probably want to be checking what your code returned. In this case, that is obj.
But looking at the PHP, it does not return anything predictable that the JS can use. It returns nothing if the query works. If it fails, it returns a string that begins with Error but then shows a MySQL error, which we won't know ahead of time, so you can't test for it in JS.
It would be better to simply return some true/false, OK/fail type msg, for eg:
// ... rest of your code
$result = mysqli_query($conn, $consultaAcciones);
if ($result === false) {
echo "FAIL";
} else {
echo "OK";
}
And in your JS:
if (obj === 'FAIL') {
// ... etc
If you actually want to pass a message back from the PHP, you should have it echo out a JSON object, eg:
$result = mysqli_query($conn, $consultaAcciones);
if ($result === false) {
$response = [
'status' => 'FAIL',
// You shouldn't reveal internal details about errors
// so don't return mysqli_error(). Maybe log it, and
// display something generic to your users.
'message' => 'There was a problem'
];
} else {
$response = [
'status' => 'OK',
'message'=> ''
];
}
header("Content-type: application/json");
echo json_encode($response);
In your JS:
$.ajax({
// ...
// specify we will get a JSON response
dataType: 'json'
// ...
success: function (obj, textstatus) {
if (obj.status === 'FAIL') {
alert(obj.message);
} else {
// all ok ...
}
});

How to use ajax for request the WHMCS hooks function and get my required return data?

I read the WHMCS demo code for developing a provisioning module:
the frontend code, overview.tpl.
the backend code, provisioningmodule.php.
but my code follow by the upper I want to use ajax for request, so the whole page will not re-render.
My frontend ajax code:
jQuery.ajax({
url: url,
type: "POST",
data: {
...
qn_action: "bmc"
},
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data, textStatus){
console.log('ldl:',data) // pay attention I want to console.log the return data. I wish it be the PHP return data's `templateVariables`.
jQuery('.powercontrol').removeClass('disabled');
jQuery(i_id).css('display', 'none');
jQuery('#powerstatus-spinner').css('display', 'none'); // Status loading
},
error: function(jqXHR, e) {
var msg = '';
if(jqXHR.status==0){
msg = 'You are offline!!\n Please Check Your Network.';
}else if(jqXHR.status==404){
msg = 'Requested URL not found.';
}else if(jqXHR.status==500){
msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
}else if(e=='parsererror'){
msg = 'Error: Parsing JSON Request failed.';
}else if(e=='timeout'){
msg = 'Request Time out.';
}else {
msg = 'Unknow Error.<br/>'+x.responseText;
}
console.log('error: '+jqXHR.responseText); // I wil get the error logs
console.log('Error msg: '+msg);
}
})
in my backend PHP code:
function qidicatedserver_ClientArea(array $params)
{
// Determine the requested action and set service call parameters based on
// the action.
$qn_action = isset($_REQUEST['qn_action']) ? $_REQUEST['qn_action'] : '';
$tblclients_id = isset($_REQUEST['tblclients_id']) ? $_REQUEST['tblclients_id'] : '';
$bmc_action = "";
$server_name = "";
$templateFile = 'templates/overview.tpl';
$bmc_result = "";
if($qn_action == "bmc"){
$resp = array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => array(
"status"=>200,
"data"=>"my test return data"
)
);
return $resp;
}
try {
// Call the service's function based on the request action, using the
// values provided by WHMCS in `$params`.
return array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => array(
'data' => array(
"status"=>"200",
"data" => array(
"bmc_result" => null
)
),
),
);
} catch (Exception $e) {
//echo $e;
// Record the error in WHMCS's module log.
logModuleCall(
'qidedicatedserver',
__FUNCTION__,
$params,
$e->getMessage(),
$e->getTraceAsString()
);
// In an error condition, display an error page.
return array(
'tabOverviewReplacementTemplate' => 'templates/error.tpl',
'templateVariables' => array(
'usefulErrorHelper' => $e->getMessage(),
),
);
}
}
when the ajax request executed, there will get error, execute the below code:
console.log('error: '+jqXHR.responseText); // I wil get the console log: `error: <!DOCTYPE html> \n<html lang="en">\n<head>\n <meta char) ....` the html is the whole page's HTML
console.log('Error msg: '+msg); // the console log: `Error msg: Error: Parsing JSON Request failed.`
So, there must be issue in there, my problem is how to use ajax for HTTP request in WHMCS custom provisioning module, but I try get failed like upper. (I tried use form request PHP, there can get correct data, but there will re-fresh the whole page, its not my desired, I don't what the page to be refresh)
Who can tell me how to use ajax for request WHMCS hook function and return correct data as my wish?
You can find more introduction of WHMCS provisioningmodulethere.
EDIT-01
I tried change the return PHP code like this:
if($qn_action == "bmc"){
$resp = array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => json_encode(array(
"status"=>200,
"data"=>"dasdas"
))
);
return $resp;
}
but still this error.
Put your Ajax/PHP code in separated file, not in _ClientArea method, suppose your module called 'mail_service', then create a file in:
\modules\servers\mail_service\for_json.php
for_json.php
<?php
#define("ADMINAREA", true);
define("CLIENTAREA", true);
#define("SHOPPING_CART", true);
require_once(__DIR__ . '/../../../init.php');
require_once(ROOTDIR . '/includes/dbfunctions.php');
#require(ROOTDIR . "/includes/orderfunctions.php");
#require(ROOTDIR . "/includes/domainfunctions.php");
#require(ROOTDIR . "/includes/configoptionsfunctions.php");
#require(ROOTDIR . "/includes/customfieldfunctions.php");
#require(ROOTDIR . "/includes/clientfunctions.php");
#require(ROOTDIR . "/includes/invoicefunctions.php");
#require(ROOTDIR . "/includes/processinvoices.php");
#require(ROOTDIR . "/includes/gatewayfunctions.php");
#require(ROOTDIR . "/includes/modulefunctions.php");
#require(ROOTDIR . "/includes/ccfunctions.php");
#require(ROOTDIR . "/includes/cartfunctions.php");
#include_once(ROOTDIR . '/includes/clientareafunctions.php');
#use WHMCS\ClientArea;
#use WHMCS\Database\Capsule;
#use WHMCS\Smarty ;
file_put_contents("C:/xampp_my/htdocs/my/sss.txt",var_export($_POST,true));
if(isset($_POST['qn_action']) && $_POST['qn_action']=="bmc")
{
// do your job
//header('Content-type: application/json; charset=utf-8');
header("Content-Type: application/json", true);
header('HTTP/1.0 200 OK');
echo '{"menu": {"id": "file","value": "File","popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"},{"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}';
}
?>
and use the follwing JS code:
jQuery.ajax({
url: "/modules/servers/mail_service/for_json.php",
type: 'POST',
data: {qn_action: 'bmc'},
cache: false,
dataType: 'json',
success: function (data, textStatus){console.log('ldl:',data)},
error: function(jqXHR, e){
var msg = '';
if(jqXHR.status==0){
msg = 'You are offline!!\n Please Check Your Network.';
}else if(jqXHR.status==404){
msg = 'Requested URL not found.';
}else if(jqXHR.status==500){
msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
}else if(e=='parsererror'){
msg = 'Error: Parsing JSON Request failed.';
}else if(e=='timeout'){
msg = 'Request Time out.';
}else {
msg = 'Unknow Error.<br/>'+x.responseText;
}
console.log('error: '+jqXHR.responseText); // I wil get the error logs
console.log('Error msg: '+msg);
}
})

Wordpress jQuery send value to database

I am trying to send a value to my wordpress database (wp_usermeta table) when a button is clicked.
Here is what I know so far, I know I need to post the value using AJAX, I also know that wordpress has a function for updating the wp_usermeta table, that is:
update_user_meta( $user_id, 'dashboard_onboarding_status', 'myValue' );
The good news is that myValue isn't a variable - I just want to send the word "complete" to the db. It's also an admin side script - I'm not sure if that makes a difference on how to call the ajax url.
Here is what I have codewise:
In my main js file, I have the following AJAX script:
$('.skizzar_onabording_dashboard #next.step5').click(ajaxSubmit);
function ajaxSubmit(){
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: {
"value" : "completed"
},
success:function(data){
console.log(data);
}
});
return false;
}
So when a user clicks on .skizzar_onabording_dashboard #next.step5 that should trigger the AJAX function.
Then in my main plugin php file I have the following:
function myFunction(){
global $wpdb;
$user_id = get_current_user_id();
$completed = $_POST['value'];
update_user_meta( $user_id, 'onboarding_status', $completed );
die();
}
add_action('wp_ajax_myFunction', 'myFunction');
I think needless to say this doesn't work, but I'm very new to using AJAX and I ca't figure out why. Seems like it should be simple though - essentially I just want to press a button and add "completed" to the key "onboarding_status" in the usermeta table.
Almost all you need is located here.
First you'll need to localize your admin-ajax.php, beause calling it like url: "/wp-admin/admin-ajax.php" is not a good practice.
wp_localize_script( 'some_handle', 'ajax_post_to_db', array(
'ajaxurl' => admin_url( 'admin-ajax.php'),
));
Then your ajax script to call:
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb;
$user_id = get_current_user_id();
$completed = $_POST['value'];
update_user_meta( $user_id, 'onboarding_status', $completed );
die();
}
And finally the ajax in your js file
$('.skizzar_onabording_dashboard #next.step5').on('click', function(){
ajaxSubmit();
});
function ajaxSubmit(){
jQuery.ajax({
type:'POST',
dataType: 'html',
url: ajax_post_to_db.ajaxurl,
data: {
action: 'my_action_callback'
},
success: function(data){
console.log(data);
},
error : function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR + ' :: ' + textStatus + ' :: ' + errorThrown);
},
});
return false;
}
This should be it.
DISCLAIMER
I'm never 100% sure if it's
data: {
action: 'my_action_callback'
},
or
data: {
'action': 'my_action_callback'
},
But try it and see which one will give you your function callback. I'm pretty sure it should be the first one.
Also you can check the return of the ajax call in your inspector. Just go to 'Network' tab and select XHR and you should see admin-ajax.php and when you click on it you can see all the relevant data it sends (headers, response etc.).
add your ajax function as the action
function ajaxSubmit(){
var data = {
'action': 'myFunction',
'value' : 'completed'
};
jQuery.post("/wp-admin/admin-ajax.php", data, function(response) {
console.log(response);
});
}

AJAX form not submitting that gives error

I have my AJAX code here
$("#add-student").click(function(e) {
e.preventDefault();
formData = $("#student-form").serialize();
if (cleanFormInput()) {
sendTheInfo(formData);
} else {
shakeForm();
}
});
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
Always without fail outputs this error:
Connection error:
SyntaxError: Unexpected end of input : parsererror
But still gives the complete message: Everything complete
Update, PHP code here:
require '../../core/init.php';
require '../../classes/Config.php';
header('Content-Type: application/json');
if (!empty($_POST)) {
$id = $_POST["sid"];
$first = $_POST["first"];
$last = $_POST["last"];
$fav = "0";
$sql = "INSERT INTO `students` (`id`, `first`, `last`, `active`) VALUES ('{$id}', '{$first}', '{$last}', '{$fav}')";
$link = mysql_connect(Config::get('mysql/host'),Config::get('mysql/username'),Config::get('mysql/password')) or die("could not connect");;
mysql_select_db(Config::get('mysql/db'), $link);
$result = mysql_query($sql, $link);
if ($result) {
header('Content-Type: application/json');
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
}
}
I'm a bit confused, am I doing my ajax set up wrong? Or is it something else in by backend code wrong? I'm using MySQL and jQuery 2.0.3
Updated code here: here
I have had a look at your code. I saw that from the PHP side you are sending a JSON object. but you didn't specified the return dataType for the response. Try to add the dataType in the ajax call. Maybe that will solve the problem
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
dataType : 'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
It should be noted that the Ajax COMPLETE method will fire even if the back end does not return a result.
complete: function() {
console.log("Everything complete");
}
will thus show the log'ed entry every time an ajax call is 'finished executing', even if the submit failed.
I would also suggest NOT having 2 headers or the same declaration (you have one up top, and one in the if(result) call.
In a comment thread, you pointed out that you're working on the server but not locally, And thus that implies you have some pathing issues. Check your
../
relative path style urls and make sure that you have the same basepoints.
removed my old answer. I don't think it is an ajax/javascript error. it's definitely a PHP error. It's this lines:
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
You $student_data is not an array, it's just a string. You need to pass an array into the json_encode function

Categories

Resources