I created a custom post type called 'visitor'. and I have an input in the front end. when the user saves input, I want to grab that data and post it as 'title' in my 'visitor' post type.
in functions.php-
$secureInfo= array(
'site_url' => get_site_url(),
'nonce' => wp_create_nonce("wp_rest")
);
wp_localize_script( "main-js", "data", $secureInfo);
in main.js-
sendUserInfo(){
var grabbingInfo = {
"title" : this.alertBoxInput.val() //my targeted input
}
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader("X-WP-Nonce", data.nonce);
},
url: data.site_url + "/wp-json/wp/v2/visitor", //custom post type
data: grabbingInfo,
type: "POST",
success: (res) => {
console.log("success");
console.log(res);
},
error: (res) => {
console.log("sorry");
console.log(res);
}
});
}
however, this code works for logged in user and says unauthorized for public users. but I don't care if a user is logged in or not. any suggestion?
Related
I am using laravel 9. I am trying to make a ajax crud operation using alax. It respond well in get request. but when I sending the post request it shows:
http://127.0.0.1:8000/add/teacher 500 (Internal Server Error) in the console. I used meta in the head and ajax csrf header according to documentation. Still showing error. here my ajax code example bellow:
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function() {
$(".add_teacher").on('click', function(event) {
event.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var position = $("#position").val();
var phone = $("#phone").val();
var password = $("#password").val();
$.ajax({
method: "post",
url: "{{route('store')}}",
data: {
name: name,
email: email,
position: position,
phone: phone,
password: password
},
success: function(res) {
if (res.status == 'success') {
$("#exampleModal").modal('hide');
$("#modalform")[0].reset();
$(".table").load(location.href + ' .table');
}
},
error: function(err) {
let error = err.responseJSON;
$.each(error.errors, function(index, value) {
$(".errorMessage").append('<span class="text-
danger">' + value +'</span><br>');
});
}
});
});
});
</script>
Here is my route:
Route::post('/add/teacher', [TeacherController::class,'store'])->name('store');
and my controller code is:
public function store(Request $request)
{
$request->validate(
[
"name" => "required",
"email" => "requied|unique:teachers",
"position" => "requied",
"phone" => "requied|unique:tachers",
"password" => "requied",
],
[
"name.required" => "Name is required",
"email.required" => "Email is required",
"email.unique" => "Email already exists",
"position.required" => "Postion is required",
"phone.required" => "Phone is required",
"phone.unique" => "Phone already exixts",
"password.required" => "password is required",
]
);
$teacher = new Teacher();
$teacher->name = $request->name;
$teacher->email = $request->email;
$teacher->position = $request->position;
$teacher->phone = $request->phone;
$teacher->password = $request->password;
$teacher->save();
return response()->json([
'status' => 'success',
]);
}
Now I need an exact solution to go farther. Thank you.
I have implemented select2js in my project, In few cases when i load my page, an empty value is appending to my select input box. Can anyone help me out, what is the issue,
I have added a image of it and My code is
{!! Form::select('searchSkillTools[]',[],(isset($skillToolXref) && $skillToolXref!='')?$skillToolXref:'', array('autocomplete' => 'off', 'class' => 'chosen-select','multiple'=>'multiple', 'id' => 'searchSkillTools-'.$randomId, 'placeholder' => '' ,'style' => 'height: auto !important')) !!}
$('#searchSkillTools-{{$randomId}}').select2({
ajax: {
url: skillToolUrl,
dataType: 'json',
method:'get',
delay: 250,//delay in response
data: function (data) {
return {
search: data.term //search term
};
},
/*option to transform the data returned by response into the format expected by Select2*/
processResults: function (response) {
return {
results:response
};
},
cache: true
}
});
This way will fix the bug:
(isset($skillToolXref) && $skillToolXref!='')?$skillToolXref:null
Fetch post is not working with the json api coded with codeIgniter. The get method works but there's issue in post method. The key is not recognized between the react native and code igniter. Any help is appreciated. Thankyou
fetch('http://zzz.com/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'abc',
}),
})
.then(response => response.json())
.then(responseJson => {
console.log('responseJson', responseJson);
})
.catch((error) => {
console.error('fetchError', error);
});
CodeIgniter controller
public function login()
{
$un = $this->input->post('username'); //why doesn't the key 'username' is working here
echo json_encode($un);
}
CONSOLE LOG:
responseJson false
Updates:
1)Using json_decode, gives error
"fetchError SyntaxError: Unexpected end of JSON input"
public function login()
{
$Data = json_decode(file_get_contents('php://input'), false);
echo $Data;
}
2)Using json_encode gives following outcomes:
responseJson {"username":"abc"}
public function login()
{
$Data = json_encode(file_get_contents('php://input'), false);
echo $Data;
}
Update 1:
1) Using only file_get_contents gives the output as: responseJson {username: "abc"}
public function login()
{
$Data = (file_get_contents('php://input'));
echo $Data;
}
2)using var_dump and json_decode in server code, it gives following error in the app console
public function login()
{
$Data = json_decode(file_get_contents('php://input'), true);
var_dump ($Data);
}
Error:
fetchError SyntaxError: Unexpected token a in JSON at position 0
at parse (<anonymous>)
at tryCallOne (E:\zzz\node_modules\promise\setimmediate\core.js:37)
at E:\zzz\node_modules\promise\setimmediate\core.js:123
at E:\zzz\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:295
at _callTimer (E:\zzz\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:152)
at _callImmediatesPass (E:\zzz\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:200)
at Object.callImmediates (E:\zzz\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:464)
at MessageQueue.__callImmediates (E:\zzz\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:320)
at E:\zzz\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135
at MessageQueue.__guard (E:\zzz\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297)
console log the response as following gives the array in app console:
fetch('http://zzz.com/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'abc',
})
})
.then((response) => console.log('response', response))
Console:
response
Response {type: "default", status: 200, ok: true, statusText: undefined, headers: Headers, …}
headers:Headers {map: {…}}
ok:true
status:200
statusText:undefined
type:"default"
url:"http://zzz.com/login"
_bodyInit:"array(1) {↵ ["username"]=>↵ string(3) "abc"↵}↵"
_bodyText:"array(1) {↵ ["username"]=>↵ string(3) "abc"↵}↵"
__proto__:Object
Try to add same-origin mode like below :
fetch('http://zzz.com/login', {
method: 'POST',
credentials: 'same-origin',
mode: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: 'abc',
}),
})
.then(response => response.json())
.then(responseJson => {
console.log('responseJson', responseJson);
})
.catch((error) => {
console.error('fetchError', error);
});
From the front end, send the data as a form data (as shown below).
const formData = new FormData();
formData.append("name", "RandomData");
formData.append("operation", "randomOperation");
In your Codeigniter controller, receive it as...
$name = $this->input->post("name");
$operation = $this->input->post("operation");
I have this add method in my vue script
if (this.edit === false) {
this.link.link = submitEvent.target.elements.link.value;
fetch('products', {
method: 'POST',
body: JSON.stringify(this.link),
headers: {
'content-type': 'application/json'
}
})
.then(res => res.json())
.then(res => { // this does not get executed
this.qrcode.redirect_url = "";
alert('Added');
this.fetchAll()
})
.catch(err => console.log(err.res));
}
}
When I fill the form the request is send and entry is made to the database but I do not get response.
I am using laravel as backend and Add method in Controller returns 200 response after creation.
What could cause it and why console.log(err) does not not display anything?
Hi I was wondering why my Laravel 5 Ajax request doesnt work
<input type="hidden" class="_token" value="{{Session::token()}}" name="_token">
$.ajax({
url: "{{ route('groups.store') }}",
method: 'post',
data: {
name: 'name',
_token: $("input[name=_token]").val()
},
success: function(response) {
if (response.success == true) {
// remove error message
alert('success');
}
},
error: function(xhr) {
alert('error');
}
});
on the Route File I put:
Route::post('search/store', [
'uses' => 'SearchController#store',
'as' => 'groups.store'
]);
and on my controller I put:
public function store(Request $request)
{
return response()->json(['success' => true]);
}
then I keep getting error 404 while I simply wants to display the json result from my controller much help appreciated thx
btw heres the full routes.php
<?php
carbon()->setLocale('id');
Route::get('/', function () {
return view('welcome');
});
Route::post('search/SearchController','SearchController#postMapSearchResult');
Route::get('/getRequest', function(){
if(Request::ajax()){
return 'getRequest has loaded';
}
});
Route::group(['middleware' => ['web']], function () {
// Backend Area
Route::controller('login','Backend\LoginController');
Route::get('admin-cp' , function(){
return redirect('login');
});
if(request()->segment(1) == webarq()->backendUrl)
{
include __DIR__.'/backendRoutes.php';
}
//
// Frontend Area
Route::get('account/confirmation/{token}', 'Auth\AuthController#activateUser')->name('user.activate');
Route::controller('faq','FaqController');
Route::controller('blog','BlogController');
Route::controller('social','SocialController');
Route::controller('account','AccountController');
Route::controller('iklan','IklanController');
Route::controller('search','SearchController');
Route::controller('/','HomeController');
Route::post('search/store', [
'uses' => 'SearchController#store',
'as' => 'groups.store'
]);
});
Put the route outside of middleware group
Below is a code which work perfect for me.
var count = 100;
$('#ID').on("click", ".CLASS",function() {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: 'URL',
type: 'POST',
data: {_token: CSRF_TOKEN,id:count},
dataType: 'html',
success: function (data) {
alert('success');
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});