WordPress - wp_ajax_ 400 bad request - javascript

I'm having a bat time trying to make work wp ajax.
I have added this action inside my plugin code construct
add_action('wp_ajax_submit_support_ticket', [$this, 'submit_support_ticket']);
and to manage the ajax call I have created this method
public function submit_support_ticket()
{
$request_type = sanitize_text_field( $_POST['reqType'] );
$request_issuer = sanitize_email( $_POST['issuerEmail'] );
$request_message = sanitize_textarea_field( $_POST['reqMessage'] );
var_dump( $request_type, $request_issuer, $request_message );
switch( $request_type ){
case '1':
$subject = '...';
break;
case '2':
$subject = '...';
break;
case '3':
$subject = '...';
break;
case '4':
$subject = '...';
break;
}
//wp_mail( $to:string|array, $subject:string, $message:string, $headers:string|array, $attachments:string|array )
$to = 'user#example.com';
$headers[] = 'From: Sistema Ticketing WordPress <no-reply#example.com>';
$headers[] = 'Cc: User <user#example.com>';
$headers[] = 'Cc: User <user#example.com>';
$headers[] = 'Cc: User <user#example.com>';
if( wp_mail( $to, $subject, $request_message, $headers ) ){
return [
'status' => 'success',
'message' => '...'
];
} else {
return [
'status' => 'error',
'message' => '...'
];
}
}
I've also created a dedicated javascript file that will hold the logics to send the ajax post request
const siteURL = window.location.origin
const requestType = document.getElementById('request-type');
const issuerEmail = document.getElementById('issuer-email');
const requestMessage = document.getElementById('request-message');
const submitButton = document.getElementById('submit-button');
const successMessage = document.getElementById('form-wrapper-success');
const errorMessage = document.getElementById('form-wrapper-error');
//
submitButton.addEventListener('click', (e) => {
e.preventDefault();
console.log(siteURL, requestType.value, issuerEmail.value, requestMessage.value);
fetch(ajaxurl, {
method: 'POST',
body: {
action: 'submit_support_ticket',
reqType: requestType.value,
issuerEmail: issuerEmail.value,
reqMessage: requestMessage.value
}
}).then( (res) => {
console.log(res)
}).catch( e => console.log(e) )
});
I've done some test but everytime I will get a 400 bad request error from the server.
How I can fix this?

Related

How to reload window after success case

I'm using ReactJS with Laravel API and I don't know why the window won't reload, and I didn't get the success message. even the status is correct
this my frontend code :
const addUnit = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('unit_name', unit_name);
formData.append('building_id', building_id);
formData.append('floor_id', floor_id);
formData.append('type_id', type_id);
formData.append('user_id', user_id);
formData.append('unit_status', unit_status);
formData.append('unit_roomnumber', unit_roomnumber);
formData.append('unit_added_date', unit_added_date);
formData.append('unit_rent_per_month', unit_rent_per_month);
formData.append('frais_percent', frais_percent);
for (let i = 0; i < unit_pictures.length; i++) {
formData.append('unit_pictures[]', unit_pictures[i])
}
axios.post(`${API_ENDPOINT}/api/addUnite`, formData).then(response => {
if (response.data.status === 200) {
window.location.reload();
}
else if (response.data.status == 400) {
new Swal("warning", response.data.errors, "Warning");
}
})}
this is backend code :
public function addUnite(Request $request)
{
$validator = Validator::make($request->all(), [
'unit_name' => 'required|max:191',
'unit_status' => 'required',
'unit_roomnumber' => 'required',
'unit_added_date' => 'required',
'unit_rent_per_month' =>'required'
]);
if ($validator->fails()) {
return response()->json([
'status' => 422,
'errors' => "All Fields Are required !",
]);
}
else {
$exist = Unite::where('type_id', '=', Input::get('type_id'))
->where('unit_roomnumber', '=', Input::get('unit_roomnumber'))
->where('building_id', '=', Input::get('building_id'))
->exists();
if ($exist) {
return response()->json([
'status' => 400,
'errors' => "This Unit already exist !",
]);
}
else {
$unit = new Unite();
$unit->unit_name = $request->input('unit_name');
$unit->building_id = $request->input('building_id');
$unit->unit_id = $request->input('unit_id');
$unit->user_id = $request->input('user_id');
$unit->frais_percent = $request->input('frais_percent');
$unit->floor_id = $request->input('floor_id');
$unit->type_id = $request->input('type_id');
$unit->unit_status = $request->input('unit_status');
$unit->unit_roomnumber = $request->input('unit_roomnumber');
$unit->unit_added_date = $request->input('unit_added_date');
$unit->unit_rent_per_month = $request->input('unit_rent_per_month');
// $unit->unit_pictures = $request->file('unit_pictures');
$allUploadApiReponse = array();
foreach ($unit->unit_pictures = $request->file('unit_pictures') as $imagefile) {
$uploadedFileUrl = cloudinary()->upload(
($imagefile)->getRealPath(),
[
'folder' => 'Units',
'discard_original_filename' => true,
]
)->getSecurePath();
array_push($allUploadApiReponse, $uploadedFileUrl);
}
// To check content
print_r($allUploadApiReponse);
$unit->unit_pictures = $allUploadApiReponse;
if($unit->save()){
return response()->json([
'message' => "Unit Added Successfully",
'status' => 200,
]);}
}
PS: the unit is added successfully but I didn't get the success message
I think maybe issue from your react-router when trying routing from browser.
Not sure but you can try:
history.go(0);
or
window.location.href = window.location.href;

When I add the name attribute, the form action no longer works

I would like the form, in addition to sending leads to the network with general_api, to save the data on a sheet.
Without writing sheet data, the wf_general_api form action works fine. If I add "name =" on the form, it saves the sheet data correctly but the wf_general_api file no longer works.
<form method="post" accept-charset="utf-8" role="form" name="gsheet" action="general_api.php">
This is general_api.php for send lead to the network:
<?php
function clean_phone_number($value){
if(substr($value,0,4) == '0039')
$value = substr($value,4);
$value = preg_replace('~\D~', '', $value);
$value = preg_replace('/\s+/', '', $value);
if(strlen($value)>10 && substr($value, 0, 2) == '39' && substr($value, 2, 1) == '3')
$value = substr($value,2);
return $value;
}
function clean_zipcode($value){
$value = preg_replace('~\D~', '', $value);
$value = preg_replace('/\s+/', '', $value);
return $value;
}
$post_data = [
'source_id' => SOURCE_ID,
'aff_sub1' => '',
'aff_sub2' => '',
'name' => $_POST['name'],
'phone' => clean_phone_number($_POST['phone']),
'quantity' => $_POST['quantity'],
'address' => $_POST['address'],
'city' => $_POST['city'],
'zipcode' => clean_zipcode($_POST['zipcode']),
'notes' => $_POST['notes'],
'doubleCheck' => 1
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => SEND_URL,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => http_build_query($post_data),
CURLOPT_HTTPHEADER => array(
'Content-Type: application/x-www-form-urlencoded'
)
));
$response = curl_exec($curl);
curl_close($curl);
$json = json_decode($response,true);
$status = $json['status'];
if($status == 'double')
$redirection_url = $json['check_url'];
else
$redirection_url = THANKYOU_URL;
//header('Location: '.$redirection_url);
echo "<script>top.location.href='$redirection_url';</script>";
And this is the gsheet for saving data:
const scriptURL = 'https://script.google.com/macros/s/xxxxx/exec'
const form = document.forms['gsheet']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
})
If I add the name attribute, the form action no longer works. If I remove it, it resumes working but does not save the data on the sheet. How can I solve?
Once you added the name and the javascript started working, the e.preventDefault() prevented the default action for the form. You need to submit the form from within the javascript. I've changed it to the fetch so that it should submit once the fetch is done. Note that this is not tested, but should work:
const form = document.forms['gsheet']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)}).then( () => {
form.submit();
}
)
})

node.js add array of images into corresponding array

I'm new in node.js and I'm getting some data from database (actions). Every action has a number of images registered in another table so that I can get them by action id.
I'm trying to add an array of these images to the correponding action so that I can loop through them in the frontend.
In php I use to do like this:
$return = array();
$images = array();
$image = array();
$select = "SELECT id, title, description FROM actions WHERE id = ? order by id DESC";
$stmt = $mysqli->prepare($select);
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $title, $description);
while ($stmt->fetch()) {
$registers = array(
"id" => $id, "title" => $title, "description" => $description, "images" => $image
);
$selectImages = mysqli_query($mysqli, "SELECT id, image FROM action_images WHERE action_id = '" . $id . "' ");
while ($row = $selectImages->fetch_array(MYSQLI_BOTH)) {
$images = array("imageID" => $row['id'], "image" => $row['image']);
array_push($registers["images"], $images);
}
$return[] = $registers;
}
Is there something similar in javscript/node.js? I tried some things described in the code below but nothing worked as expected.
This is my controller:
async selectActions(req, res) {
let actionData = [];
conn.execute('SELECT * FROM actions',
function (err, results, fields) {
// console.log(err);
// console.log(results);
if (err == null) {
results.forEach(action => {
conn.execute('SELECT * FROM actions_images WHERE actionID = ?',
[action.id],
function (imagesError, imagesResults, ImagesFields) {
// I've tried some things like:
actionData = [results, imagesResults];
// and
actionData = [...results, ...imagesResults]
// and
results.push(imagesResults)
// but nothing had the expected results displayed in the image below
console.log(actionData);
}
);
});
return res.json(results);
} else {
return res.json('error fetching actions from database: ' + err);
}
});
},
Action images array must be another item in each action item:
Try this...
Promise.all(results.map((action, index) => {
return Promise(resolve => {
conn.execute('SELECT * FROM actions_images WHERE actionID = ?',
[action.id],
function(imagesError, imagesResults, ImagesFields) {
results[index].action_images = imagesResults;
resolve(true);
}
);
})
}))
console.log(results);

Instagram API with a link in the application

I created a personal website and I created a login button "ACCOUNT". This allows you to use the instagram API to retrieve basic information about the user who wants to create one. The API works fine, but when a new user wants to associate his Instagram account to my site from his smartphone (from the application instagram with a link to my site from my account instagram.com/maximekahn_), it indicates an error of page loading.
Have you ever had this problem?
Do you have trouble loading the API page of my site from the Instagram app?
Does the loading error come from instagram or me?
Website: maximekahn.com
[PHP, HTML and Javascript have been used for development]
Thank you in advance for your answers!
/*Instagram*/
class Instagram
{
public function __construct ()
{
if(isset($_GET["code"]) && !empty($_GET["code"]))
{
$code = htmlspecialchars(addslashes($_GET["code"]));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.instagram.com/oauth/access_token");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, "client_id=[client_code]&client_secret=[secret_code]&grant_type=authorization_code&redirect_uri=https://maximekahn.com/api/instagram/&code=".$code);
$curl = curl_exec($curl);
$json = json_decode($curl);
curl_close($curl);
sleep(2);
$firstname = explode(" ", $json->user->full_name)[0];
$lastname = explode(" ", $json->user->full_name)[1];
$array = array(
"id" => "NULL",
"user" => $json->user->id,
"firstname" => $firstname,
"lastname" => $lastname,
"name" => $json->user->username,
"biography" => $json->user->bio,
"email" => "",
"password" => "",
"image" => $json->user->profile_picture,
"birthday" => "1999-03-16",
"gender" => "",
"website" => $json->user->website,
"datetime" => "NOW()",
);
$arrayupdate = array(
"firstname" => $firstname,
"lastname" => $lastname,
"name" => $json->user->username,
"biography" => $json->user->bio,
"email" => "",
"password" => "",
"image" => $json->user->profile_picture,
"birthday" => "1999-03-16",
"gender" => "",
"website" => $json->user->website,
"datetime" => "NOW()",
);
$criterion = array(
"user" => $json->user->id
);
$isset = array(
"name" => $json->user->username,
);
if($json->user->id){
$database = new database();
if($database->isset("maximekahn.accounts", $isset, "and") == true){
if($database->update("maximekahn.accounts", $arrayupdate, $criterion)){
$_SESSION["id"] = $json->user->id;
$_SESSION["name"] = $json->user->username;
$_SESSION["picture"] = $json->user->profile_picture;
$_SESSION["full"] = $json->user->full_name;
$_SESSION["biography"] = $json->user->bio;
$_SESSION["website"] = $json->user->website;
$_SESSION["business"] = $json->user->is_business;
$_SESSION["api/instagram"] = true;
header("Location: https://maximekahn.com");
}else{
$_SESSION["id"] = "";
$_SESSION["name"] = "";
$_SESSION["picture"] = "";
$_SESSION["fullname"] = "";
$_SESSION["biography"] = "";
$_SESSION["website"] = "";
$_SESSION["business"] = "";
$_SESSION["api/instagram"] = true;
header("Location: https://maximekahn.com");
}
}else{
if($database->add("maximekahn.accounts", $array)){
$_SESSION["id"] = $json->user->id;
$_SESSION["name"] = $json->user->username;
$_SESSION["picture"] = $json->user->profile_picture;
$_SESSION["full"] = $json->user->full_name;
$_SESSION["biography"] = $json->user->bio;
$_SESSION["website"] = $json->user->website;
$_SESSION["business"] = $json->user->is_business;
$_SESSION["api/instagram"] = true;
header("Location: https://maximekahn.com");
}else{
$_SESSION["id"] = "";
$_SESSION["name"] = "";
$_SESSION["picture"] = "";
$_SESSION["fullname"] = "";
$_SESSION["biography"] = "";
$_SESSION["website"] = "";
$_SESSION["business"] = "";
$_SESSION["api/instagram"] = true;
header("Location: https://maximekahn.com");
}
}
}
}else if(!$_GET)
{
header("Location: https://www.instagram.com/oauth/authorize/?client_id=[client_id]&redirect_uri=https://maximekahn.com/api/instagram/&response_type=code&scope=basic");
}
}
};

Laravel - Validation errors

I want to return the $validator->errors() and include another element "message" to hold the status of the project.
for example:
if ($validator->fails()) {
$response = array('data' => $validator->errors());
$status = 'failed';
// I tried this but it didn't work
// $response = array('data' => $response, 'status' => 'failed')
} else {
$status = (Phone::create($post_data)) ? "success" : 'failed';
$response = array('status' => $status);
}
return Response::json($response);
So in javascript side I would load something like:
if (data.status == 'success') { console.log('success'); }
else {
$.each(data, function(index, value) {
message += '<div class="text-warning"> <span class="glyphicon glyphicon-exclamation-sign"></span> ' + (data[index]) + '</div>';
});
}
The method errors() returns a MessageBag instance, you need to retrieve an array:
if ($validator->fails())
{
$response = array(
'data' => $validator->errors()->all(),
'status' => 'failed'
);
}
else
{
$status = (Phone::create($post_data)) ? "success" : 'failed';
$response = array('status' => $status);
}
return Response::json($response);

Categories

Resources