I am using this ajax call params to pass data:
var formData = new FormData();
formData.append('file', selectedFile);
formData.append('subject', 'test subject');
formData.append('message', 'test message');
url: 'my/endpoint',
type: 'POST',
data: formData,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false
Here is my endpoint:
function test_endpoint(WP_REST_Request $request){
return $request->get_body();
//return wp_mail( $to, $subject, $body, $headers, $attachments );
}
I can see the data:
So basically I am trying to access the form parameters so I can put them into an email. I can't figure our how to access file, subject and message?
You can't or at least shouldn't call ajax directly when using Wordpress.
There is a mechanism built in to deal with ajax calls.
More or less what you have to do is:
Write the function of what will be executed on the server when the ajax call is triggered and then bind it to an ajax callback action.
add_action( 'wp_ajax_nopriv_myaction', 'my_ajax_processing_func' );
add_action( 'wp_ajax_myaction', 'my_ajax_processing_func' );
function my_ajax_processing_func() {
<Your processing here>
}
note the 'myaction' part in the add_action(). In the form data sent from the client, there has to be an action parameter set to this identifief (myaction) for the binding to take place.
Also in the form the url has to be set to the admin_url( 'admin-ajax.php' ). The way of getting hold of this url is to download it to the js script using wp_localized_script().
You can find a full explanation here:
Using AJAX With PHP on Your WordPress Site Without a Plugin
Also chck out this article to add a nonce to the form for security reasons.
How to Add a WordPress AJAX Nonce
I found out that it was my ajax. So I switched to straight XHR and it worked:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'my/endpoint', true);
xhr.onload = function () {
console.log('response',JSON.parse(this.responseText));
};
xhr.send(formData);
Related
I'm currently building a web application using CodeIgniter 4. In one of my forms, I need ajax to send a post request and get the data result to modify the form base on item selected on a combo box.
The first requests were always okay, but it won't work for the next one. When I refresh the page, it redirects me to login page, due to my filter. It turns out that the AJAX request either destroy all my sessions, or update it to the new ones.
this is my ajax :
`
$('#penilaian_jenis').on('change', function() {
$.ajax({
OST type: "P",
url: '<?= base_url('guru/penilaian/get_nilai') ?>',
data: {
'kelas_id': '<?= $kelas->kelas_id ?>',
'kd_id': '<?= $kd->kd_id ?>',
'penilaian_jenis': $('#penilaian_jenis').val(),
},
dataType: 'json',
success: function(data) {
var result = JSON.parse(data);
alert(result);
}
})
})
`
This is my Controller :
`
public function get_nilaii()
{
echo json_encode('success');
}
`
This is how I stored my session at the auth controller:
$data = [
'user' => $user,
'guru' => $model->where('user_id', $user->user_id)->first(),
'guru_logged_in' => 1,
];
session()->set($data);
My Ajax codes I user are the simplest one. Can Anyone help give me the solutions to this problem, or recommend me another way to do HTML request without losing all my sessions?
Sorry for bad grammar, and thank you in advance
I'm trying to send some data from my view to my controller via ajax. How do I retrieve this data in my action?
I've tried jQuery's $.ajax and $.post methods, providing the url and data, but using $this->data, $this->request->data, $_POST, $_GET or $_REQUEST doesn't work (all return as empty arrays).
$.ajax({
url: "<?php echo Router::url( array("controller" => "Progression", "action" => "submit", $user['User']['id']) ); ?>",
type: 'post',
data: { name: "John" }
}).done( function(data) {
console.log(data);
});
function submit() {
$this->request->allowMethod('ajax');
$this->autoRender = false;
$data = array();
$data['answer'] = $this->request->data; // or any of $_POST, $_GET, etc.
return json_encode($data);
}
My console always keeps printing {"answer":[]}. I checked the network tab of my devtools and the data is successfully listed under Form data, yet I can't seem to get hold of the data in the action.
EDIT:
Thanks to Greg Schmidt I found out that my request indeed got redirected: first it gives me a 302, then it makes a new request without the post data and returns a 200. I just can't find what the critical difference is between the two requests (URLs look the same, no case difference or anything). Can anybody help me with that?
First request:
Second request:
I'm trying to submit a form via ajax and post to /wp-admin/admin-ajax.php but I am getting response code 400.
I am submitting the form as so:
$.ajax("/wp-admin/admin-ajax.php", {
type: 'post',
dataType: 'json',
data: form_data,
success : function(response) {
console.log('working', responseText)
},
error: function(err){
console.log('err', err)
}
});
On my Wordpress backend I simply have an action and my handler function:
function panacea_form_process() {
// do whatever you need in order to process the form.
return 'working';
}
add_action("wp_ajax_nopriv_panacea_form", "panacea_form_process");
I was following this guide - https://teamtreehouse.com/community/submitting-a-form-in-wordpress-using-ajax but have tried to simplify it for debugging purposes.
I tried having a nonce but believe I don't require it as that is only needed for users who are logged in?
Hitting a wall so any suggestions would be appreciated. Thanks.
EDIT:
Have added localize script:
wp_localize_script( "_main-sripts",
'theUniqueNameForYourJSObject',
array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( "randomstring" ),
)
);
Updated my ajax call with localized admin url and also action name etc
$.ajax(theUniqueNameForYourJSObject.admin_url, {
type: 'post',
dataType: 'json',
data: data : {action: "panacea_form", form_data : form_data, nonce: theUniqueNameForYourJSObject.nonce},
success : function(responseText, statusText, xhr, $form) {
console.log('working', responseText)
},
error: function(err){
console.log('err', err)
}
});
Updated my action to return using wp_send_json and to include the action for logged in users:
function panacea_form_process() {
// do whatever you need in order to process the form.
wp_send_json('working');
}
add_action("wp_ajax_nopriv_panacea_form", "panacea_form_process");
add_action("wp_ajax_panacea_form", "panacea_form_process");
I tried having a nonce but believe I don't require it as that is only
needed for users who are logged in?
Nonce - is required. Request will be more securely.
What about your form_data? This should be json or request string.
And
function panacea_form_process() {
// do whatever you need in order to process the form.
return 'working';
}
Must have an echo, not return. Use wp_send_json() for returning data. Or wp_send_json_success() for success results or enter link description here for failed.
Your specific problem probably comes from the fact that you're missing an action.
You're using add_action("wp_ajax_nopriv_panacea_form", "panacea_form_process"); but the wp_ajax_nopriv is for non privileged users. Or users that are not logged in to the website/wp-admin
Since you're developing the site you're probably logged and so AJAX calls that should work for both logged-in en non-logged-in users you need another action so change is to
add_action("wp_ajax_nopriv_panacea_form", "panacea_form_process");
add_action("wp_ajax_panacea_form", "panacea_form_process");
Other then that you should echo results from AJAX calls, returning doesn't work properly in this case. Ideally you'd use wp_send_json as well.
Tip:
You should localize your ajax URL from where you enqueue the script to ensure the call still works when wp-admin is renamed.
I wanted to submit a for using ajax call in laravel 5.
In view i wrote something like
$("#updateSubmit").on('submit',function(e){
e.preventDefault();
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
method:'POST',
url: '/account/updateForm',
//dataType: 'json',
data: {accountId:'1111', _token: '{{csrf_token()}}'},
success: function( data )
{
alert(data)
return false;
}
},
error: function(error ){
alert("There is some error");
}
});
and on controller side
public function update(Request $data )
{
return Response()->json(['success' => true],200);
}
while in route for post method
Route::post('account/updateForm', 'AccountController#update')->name('account/updateForm');
its working till ajax. on Submission of ajax it goes to controller action.
but it does not retrun back as ajax comes back in normal form submisson.
it just go to controller and stops there with {"success":true} line.
I want ajax to come back to view form so that I can perform different dependent actions.
Do you mean that when you submit your form, you just have a white page with {"success": true} ?
If that's the case, maybe the error is on your javascript.
Maybe your jQuery selector is wrong, or maybe your js isn't compiled ?
I have a system implemented in CodeIgniter, I am trying to send some data in a text area of Rsform component via POST to the url referring to my CodeIgniter system, I have tried usign AJAX request to send the post data using the following code
<script>
alert("jsc");
var data;
data='test from joomla!';
$.ajax({
type: "POST",
url : 'http://localhost/cii/index.php/login/getNews/',
data: {news:data},
cache: false,
success: function(html){
alert(html);
}
});
getNews controller:
function getNews() {
//print_r($this->session->userdata);
header('Access-Control-Allow-Origin: *');
echo "news is ".$news=$_POST['news'];
$data = array ( 'username' => "null", 'is_logged_in' => false, 'news'=>$news);
$this->session->set_userdata($data); //var_dump($_POST); //
print_r($this->session->userdata); session_start(); echo session_id();
}
but it failed, is there any other options ?
Use something like Firebug in mozilla firefox to observe what data is being posted to the app to check if your ajax call is working.
Then in your codeigniter controller method, simply put this code to see if the data is getting to it.
function getNews()
{
foreach($_POST as $key => $val)
{
$options[$key] = $this->input->post($key);
}
var_dump($options);
}