Making an ajax post request in Wordpress - ajax

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.

Related

How Can I Prevent AJAX From Destroying My Session?

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

How to fetch ajax request data in cakephp 2 controller?

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:

Laravel open url in server side after action

is there any way to open url in "server side".
I'm using https://www.lightsms.com/ as my sms gateway. And to send sms, you need to visit (for example) https://www.lightsms.com/send.php, so i don't want to redirect user to that url. I just want to open it in server background, and close.
after route and before real redirect, example's here:
Route::get('/sms', function() {
//i need to excecute that url here
redirect('success.html');
});
Is there any way to do this?
I think you need to do this asynchronously using xhr or ajax if you use jquery, you basically post the information asynchronously and your server (your php script) just returns a json back, in your success function / promise you can get the data and do something with it if you like, this process does not require any redirect.
This is a simple example which you may need to modify:
function asyncPost(event){
$.ajax({
url: "https://www.lightsms.com/send.php",
data: {
name: "any value or variable,"
id: "any value or variable"
},
datatype: "json",
type: "POST",
success: function(data) {
console.log("success");
// do something with data if you need, data contains the returned data from your php script
},
error: function(data) {
console.log("an error occured");
}
});
}

wordpress my own plugin: ajax always returns 0

I wrote a plugin, which uses ajax. The plugin should allow users (if logged in or not) to delete a value on database.
My Problem is, that the ajax response ALWAYS is NULL and I have no idea why! I googled for hours and I tried everthing... Here are my scripts:
function my_script_enqueuer(){
global $post;
$content = $post->post_content;
if(has_shortcode($content, 'shortcode')){
wp_register_script('my_script',
WP_PLUGIN_URL.'/my-plugin/js/my-plugin.js',
array('jquery'));
wp_localize_script('my_script',
'myAjax',
array( 'ajaxurl' => admin_url('admin-ajax.php')));
wp_enqueue_script('jquery');
wp_enqueue_script('my_script');
}
}
add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' );
add_action('wp_ajax_del_value', 'del_value');
add_action('wp_ajax_nopriv_del_value', 'del_value');
function del_value(){
$val = $_POST['val'];
echo $val;
//$wpdb->...an so on
die();
}
and here my ajax (my_plugin.js)
jQuery(document).ready( function(){
jQuery(document).on('click', '.delval', function($){
var val = this.id;
jQuery.ajax({
type: "POST",
url: myAjax.ajaxurl,
data: {action:"del_value", val: val},
success: function(response){
if(response.type = "success"){
console.log(response);
}else{
console.log("Error");
}
}
});
});
});
The problem isn't with the code here. I duplicated the example provided and it worked for me.
When I've run into problems like this in the past it's usually boiled down to one of two problems:
The browser thinks this is a cross-domain request. Solution: make sure that the domain in myAjax.ajaxurl matches the domain you see in your browser location bar.
jQuery isn't interpreting the mime type of the response correctly. You're not specifying the return type. Solution: try including a dataType: "text" key/pair with your jQuery.ajax call; or try encoding the response as JSON.
Got it! I had the same variable twice (different use) in my whole script. Unfortunately, the
add_action('wp_ajax_nopriv_del_value', 'del_value');
...was...
add_action('wp_ajax_nopriv_my_del_value', 'del_value');
...in my script.
Sorry for that. I hope that my script will help others sometimes, somehow.
Greets,
Yab86

prevent redirection on submit to form

I have the following code I am using to submit my form to a processing script. the form gets submitted but I am getting redirected to the response html from the server. I want to stay on the same page and run the callback function inside success:
the response header is sending
location:http://url-I-am-Redirected-to-and-don't-want-to-be.html
I am working with third party and have no control over the server side code I am submitting to.
$('#go').click (function () {
$.ajax ( {
type: 'POST',
data: $('#newsletter form').serialize(),
url: $('#newsletter').attr('action'),
success: function(){
$('#image_container').hide (1000,
);
}
});
}
At the end of the click block add
return false

Resources