I try to do an ajax request with wordpress. So I've created a simple js request:
$.ajax({
url: '?',
type: 'POST',
data: {
'pr_post': post,
'pr_rating': rating
},
success: function (response) {
console.log(response);
}
});
Here is my function to handle the request.
function pr_request()
{
if (isset($_REQUEST['pr_post']) && isset($_REQUEST['pr_rating']) && isset($_REQUEST['pr_user'])) {
$post = $_REQUEST['pr_post'];
$rating = ($_REQUEST['pr_rating'] > 5 ? 5 : $_REQUEST['pr_rating']);
$user = get_current_user_id();
if (!pr_has_user_already_voted($user, $post)) {
global $wpdb;
$table = $wpdb->prefix . 'mitmach_ratings';
$wpdb->query($wpdb->prepare("insert into $table values (null, $post, $rating, '$user');"));
wp_send_json(['message' => 'success']);
} else {
wp_send_json(['message' => 'duplicate'], 403);
}
}
}
As you see I call the get_current_user_id() function. This function always returns true even if the user logged in. How can I get the user id in my handler without sending it via ajax?
For a start check docs - WP Ajax.
You need to send action key
Notice how the 'action' key's value 'my_action', defined in our JavaScript above, matches the latter half of the action 'wp_ajax_my_action' in our AJAX handler below. This is because it is used to call the server side PHP function through admin-ajax.php. If an action is not specified, admin-ajax.php will exit, and return 0 in the process.
$.ajax({
url: '?',
type: 'POST',
data: {
action : 'pr_post',
pr_rating : rating
},
success: function (response) {
console.log(response);
}
});
and call like this:
add_action( 'wp_ajax_pr_request', 'pr_request' );
add_action( 'wp_ajax_nopriv_pr_request', 'pr_request' );
function pr_request() {
// Code
}
Related
I am trying to return the parameter of a laravel route to an ajax response. This is my
public function getPermissions(Request $request)
{
//$v = request()->route()->parameters('profile');
$v = request()->route()->parameters();
return var_dump($v);
}
JS:
function getPermissions() {
let data_permissions = '';
$.post({
url: '/permisos',
async: false,
success: (res) => {
console.log(res)
}
});
}
This is my route:
http://base-laravel.test/profiles/1/edit
In the console returns an empty array.
I intend to obtain the 1 that they see on the route. Suggestions?
You have not added the data to send from Laravel to Ajax Controller. You can pass the data inside the object of the data like
$.post({
url: '/permisos',
type: "POST",
data: {
id: '{{$user->id}}' // Suppose you need to pass the user id to the controller
},
async: false,
success: (res) => {
console.log(res)
}
});
When retrieving the id in the AjaxController, you can simply use the Request $request variable.
public function getPermissions(Request $request)
{
//dd($request->all())
//dd can be use to die and dump the all variable values
return $request->id;
}
Viewing in the console, it will display the Ajax Request Id.
You can use this way
$data = $this->route('parameter_to_access');
return $data
This is how i am trying to check json data. If the data inserts correctly i want the mentioned jquery in success code. But if it is not inserted then i want else code to run. But the if else conditions are not working properly.I am including php code and ajax code which i have tried. Am i doing it right?
AJAX
$( "#frm_add" ).on('submit',(function(e) {
e.preventDefault();
var img= new FormData(this);
datas = $("#frm_add").serializeArray();
$.each(datas,function(key,input){
img.append(input.name,input.value);
});
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
//data:new FormData(this),
data:img,
// data: {img:img,datas:datas}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) // A function to be called if request succeeds
{
if(data == true)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
});
}));
php
function insertCategories($params)
{
$fileName = $_FILES['cat_image']['name'];
$name = $params['cat_name'];
$type = $params['cat_type'];
$switch = $params['cat_switch'];
$chk=mysqli_query($this->conn,"select * from categories where cat_name='$name'");
if(mysqli_num_rows($chk)==0)
{
$sql = "INSERT INTO `categories` (cat_name,cat_image, cat_type, cat_switch) VALUES('$name','$fileName', '$type','$switch'); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert Categories data");
if ($result) {
if (file_exists("images/" . $_FILES["cat_image"]["name"])) {
echo $fileName . " <span id='invalid'><b>already exists.</b></span> ";
} else {
$sourcePath = $_FILES['cat_image']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "images/" .$fileName; // Target path where file is to be stored
move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
}
}
echo json_encode($result);
}
}
Add the error command in your ajax call to execute if the command fails or returns no data in general
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:img,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data), // A function to be called if request succeeds
{
if(data)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
error: function (data)
{
$("#namerr".html("<p id='error' style='color:red'>"+data+"</p>");
}
});
I think You have problem with response convention: Sometimes You call die() method (PHP: 12 line), sometimes You call json_endcode() (PHP: 25 line), sometimes echo with plain string.
In this type of actions You should:
Always output JSON from backend script. Mixing response types is really pain in the ass, it's hard to parse and test.
Use response object with uniform structure - that might help with building complex applications and easy to modify
Example pseudocode:
PHP
if($success) {
die(json_encode([
'error' => false,
'message' => 'Thank You',
'data' => $some_extra_data
]));
} else {
die(json_encode([
'error' => true,
'message' => 'Sorry',
'data' => $some_extra_data
]));
}
Then in ajax.success() method, its really easy to handle:
success: function (data) {
try {
var response = JSON.parse(data)
if(response.error == true) {
$('#nameerr').text(response.message)
} else {
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
} catch (err) {
alert('Sorry. Server response is malformed.')
}
}
I have written a php script
cch.php
$stmtcheck = $mysqli->prepare("SELECT id FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id);
$stmtcheck->fetch();
$stmtcheck->close();
And jquery for submitting form is
recover.php
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
success: function()
{
alert("unlocked");
}
});
});
Now what I want to check whether $id has some value or not! How would I fetch the $id variable to my main script?
In cch.php, if you want to pass only an id to the javascript, you can print id
echo $id;
What ever data is received on ajax response will be passed as parameter to the success callback function. Either you have to execute the success actions inside the succes call back OR You have to write a function to be executed on ajax success and call that function and pass the params
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
success: function(responseData)
{
if (responseData == '' )
{
alert("Sorry failed");
}
else
{
alert("Success");
}
}
});
});
I need to validate, on server side, if a person with a given registration number is already on the database. If this person is already registered, then I proceed with the program flow normally. But, if the number is not already registered, then I'd like to show a confirmation dialog asking if the operator wants to register a new person with the number entered and, if the operator answers yes, then the person will be registered with the number informed on the form on it's submission.
I've tried
Server side(PHP):
if (!$exists_person) {
$resp['success'] = false;
$resp['msg'] = 'Do you want to register a new person?';
echo json_encode($resp);
}
Client side:
function submit(){
var data = $('#myForm').serialize();
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
return false;
}
I can't even see the alert, that's where I wanted to put my confirmation dialog, with the message written on server side. Other problem, how do I resubmit the entire form appended with the operator's answer, so the server can check if the answer was yes to register this new person?
EDIT
I was able to solve the problem this way:
Server side(PHP):
$person = find($_POST['regNo']);
if ($_POST['register_new'] === 'false' && !$person) {
$resp['exists'] = false;
$resp['msg'] = 'Do you want to register a new person?';
die(json_encode($resp)); //send response to AJAX request on the client side
} else if ($_POST['register_new'] === 'true' && !$person) {
//register new person
$person = find($_POST['regNo']);
}
if($person){
//proceed normal program flow
}
Client side:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
var ajax1 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function (response) {
if (!response.exists && confirm(response.msg)) {
document.getElementById('register_new').value = 'true'; //hidden input
dados = $('#myForm').serialize(); //reserialize with new data
var ajax2 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function () {
document.getElementById('register_new').value = 'false';
$('#myForm').unbind('submit').submit();
}
});
} else if (response.success) {
alert(response.msg);
$('#myForm').unbind('submit').submit();
}
}
});
}
There doesn't appear to be anything wrong with your PHP.
The problem is (1) You are doing the alert inside of an error callback, and your request isn't failing, so you don't see the alert. (2) You are alerting the string 'response' instead of the variable response.
It is also worth noting that you should be using the .done() and .fail() promise methods (http://api.jquery.com/jquery.ajax/#jqXHR).
Here is the fixed JS:
function submit() {
var data = $('#myForm').serialize();
// Same as before, with the error callback removed
var myAjaxRequest = $.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
});
// The request was successful (200)
myAjaxRequest.done(function(data, textStatus, jqXHR) {
// The data variable will contain your JSON from the server
console.log(data);
// Use a confirmation dialog to ask the user your question
// sent from the server
if (confirm(data.msg)) {
// Perform another AJAX request
}
});
// The request failed (40X)
myAjaxRequest.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
return false;
}
Also, you are setting a 'status' in PHP and checking that in the JS (I presume). What you want to be doing is setting a HTTP status code from the server, as below:
if (!$exists_person)
{
$resp['msg'] = 'Do you want to register a new person?';
// 400 - Bad Request
http_response_code(400);
echo json_enconde($resp);
}
Then, jQuery will determine whether the request failed based on the status code you respond with. 200 is a successful request, and 400 numbers are fail.
Check out this page for a full list: https://httpstatuses.com/
Okay so this is a two part question; I'll try my best to answer both parts:
Part 1: How to detect if success is false and trigger the confirmation popup?
In jQuery.ajax the error handler is triggered based on response code. This is probably not what you want. You can use your success handler and test the value res.success to see if it's true or false. It would be something along the lines of:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
}).done(function(res) {
if (!res.success) {
alert(res.msg);
}
});
}
Part 2: How do I resubmit with a confirmation?
Working off of our previous code we will make some changes that allow for submit() to be passed an argument registerNew. If registerNew is true we will pass it as a param to the ajax handler in the PHP so it knows we want to register a new person. The Javascript will look something like this:
function submit(e, registerNew) {
if (e) e.preventDefault();
var data = $('#myForm').serialize();
var ajax_options = {
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
};
ajax_options.data.register_new = !!registerNew;
$.ajax(ajax_options).done(function(res) {
if (!res.success && confirm(res.msg)) {
submit(null, true);
}
});
}
As you can see here, we are passing a new register_new param in the data in our ajax options. Now we need to detect this on the PHP side, which is easy enough and looks like this (this goes in your php ajax handler):
if ($_POST["register_new"]) {
// new user registration code goes here
} else {
// your existing ajax handler code
}
Add confirm inside submit function
function submit(){
var data = $('#myForm').serialize();
if (confirm('Are you ready?')) {
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
}
return false;
}
I have one AJAX call. I need to pass some parameters to my function. This is my AJAX call.
$.ajax({
url: 'lib/function.php',
data: {
action: 'getStoreSupplyItems',
id: store_id,
indent: 1
},
success: function(output) {
//alert(output);
$('#response').html(output);
}
});
Here is my back end function definition that I am trying to call:
function getStoreSupplyItems($category = '')
{
global $db;
$data = $_REQUEST;
$category = (!empty($category) ? ' AND cim.item_group_code IN ("'.$category.'") ' : '');
if ($data['id'] != "")
{
$store = $data['id'];
}
else
{
$store = $_SESSION['user']['store']['id'];
}
How can I pass some arguments to the function? The parameter that I want to pass is something like '12,5,6'.
You can put a switch statement in your php file and then call the function passing the arguments. Like this
switch($_REQUEST["action"]){
case "getStoreSupplyItems" :
getStoreSupplyItems("2,12,5");
break;
}
In your getStoreSupplyItems function you can get the value as a param and also use other get params by $_REQUEST or $_GET.
I hope this is what you looking for.
To pass your data you have to make a call like this:
$.ajax({
method: "POST",
url: "lib/function.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
then, in your PHP function you have to access to params via $_POST['name'] and $_POST['location']