I am creating a form that submits with AJAX then use $_POST to get the values of the form and enter them into the database. But I don't understand why I have had to define the action inside an input in my form, usually I would just define it inside my js. But if I do this I cannot access the $_POST data. Can someone please explain why this happens.
Here's my code that works;
js
jQuery(document).ready(function($){
jQuery('#add_event_form').on('submit', function(e){
e.preventDefault();
var form = $(this);
var form_data = form.serializeArray();
$.ajax({
url: ajax_url,
type: 'post',
data: form_data,
error : function(response){
console.log(response);
},
success : function(response){
}
});
});
});
php
<?php
add_action('wp_ajax_nopriv_add_event', 'add_event');
add_action('wp_ajax_add_event', 'add_event');
function add_event(){
global $current_user;
global $wpdb;
$user_id = $current_user->ID;
$event_name = sanitize_text_field($_POST['event_name']);
$wpdb->insert('wp_events', array(
'user_id' => $user_id,
'event_name' => $event_name,
) );
die();
}
?>
html
<form action="" method="POST" id="add_event_form">
<h3>ADD EVENT</h3>
<div class="form_row">
<label>Event Name
<input type="text" name="event_name" class="event_name required">
</label>
</div>
<input type="hidden" name="action" value="add_event">
</form>
And heres how I would usually define my action, why does this not work?
jQuery(document).ready(function($){
jQuery('#add_event_form').on('submit', function(e){
e.preventDefault();
var form = $(this);
var form_data = form.serializeArray();
$.ajax({
url: ajax_url,
type: 'post',
// data: form_data,
data: {
action: 'add_event',
data: form_data,
},
dataType: 'json',
error : function(response){
console.log(response);
},
success : function(response){
}
});
});
});
This isn't finished so please excuse any security issues etc.
In your JavaScript you have data: form_data which is an array that contains objects like this {name: "event_name", value: "test"}. Which will result in this:
$.ajax({
url: ajax_url,
type: 'post',
data: {
action: 'add_event',
data: [{name: "event_name", value: "test"}]
}
});
This wont work.
The data property of jQuery's ajax should contain key-value pairs, like this:
$.ajax({
url: ajax_url,
type: 'post',
data: {
action: 'add_event',
event_name: 'test'
}
});
Edit: if you don't want to change your javascript code you could also get the data in PHP by using:
$data = $_POST['data']; // the 'data' array from jQuery's ajax call
$event_name = $data['event_name'];
However, I woulnd't recommend doing it in this way.
Related
I want to send an array of ids for the checked checkboxes via ajax to PHP. I keep getting Undefined array key "progid". when I alert the progid in jQuery I got the correct ids. I know it is duplicated question but I really searched a lot and tried a lot of solutions nothing works.
html code:
while($row3 = $result3->fetch_assoc()) {
$courseName = $row3['courseName'];
$coursePrice = $row3['coursePrice'];
$courseId = $row3['id'];
$programList .= ' <div class="form-check">
<input type="checkbox" name="course[]" class="form-check-input" id="'.$courseId.'" value="'.$coursePrice.'">
<label class="form-check-label" for="'.$coursePrice.'">'.$courseName .' price is '.$coursePrice.'$</label>
</div>';
}
echo $programList;
jQuery code:
$('#submit').click(function() {
var progid = [];
$.each($("input[name='course[]']:checked"), function(){
progid.push($(this).attr("id"));
});
$.ajax({
type: "POST",
url: "test.php",
data: progid,
success: function(data){
console.log('success: ' + progid);
}
});
});
php code:
<?php
extract($_POST);
print_r($_POST);
echo ($_POST["progid"]);
?>
Edit:
when I send the data to the same page it does work and displays the array inside a span , but when I send it to another PHP file it doesn't work it displays the error.
Because you didn't post all the html, is it possible that your submit event is not disabled with event.preventDefault(); and the ajax is not executing?
$('#submit').click(function(e) {
e.preventDefault();
..
https://api.jquery.com/event.preventdefault/
$.ajax({
type: "POST",
url: "test.php",
data: {"progid" : progid},
success: function(data) {
console.log('success: ' + progid);
}
});
You can use JSON.stringify() for the array:
$(document).ready(function () {
$('#submit').click(function(e) {
e.preventDefault();
var progid = [];
$.each($("input[name='course[]']:checked"), function(){
progid.push($(this).attr("id"));
});
let stringifyProgid = JSON.stringify(progid);
$.ajax({
type: "POST",
url: "test.php",
data: {progid: stringifyProgid},
success: function(data){
console.log('success');
}
});
});
});
And in PHP you can get the array:
<?php
$arrProgid = json_decode($_POST["progid"]);
var_dump($arrProgid);
?>
I often do this with Multi Select form fields.
var progid = [];
$.each($("input[name='course[]']:checked"), function(){
progid.push($(this).attr("id"));
});
$.ajax({
type: "POST",
url: "ajax_post.php",
data: {
'progid[]': progid
},
success: function(data) {
}
});
Then on the PHP system the $_POST['progid'] will be an array. So all the JSON encoding and decoding others have posted is not needed.
I want to pass a data data: ( {name: 'ccenter', value: 'Sales Department' } ) using AJAX JQuery into PHP page Without any submission.
I try with session_name(); session_start(); But It didn't work.variable $ccenter still remains undefined.I think i have missed some code to do so.please help me.Thanks
Here Is my Jquery AJAX Code:
$(function () {
$.ajax({
url: 'empid_list.php',
type: "post",
async:true,
data: ( {name: 'ccenter', value: 'Sales Department' } ),
dataType: 'html',
success: function(data) {
$('#employeeid').html(data);
}
});
});
And Here Is my PHP File code:
<?php
session_name('session1');
session_start();
$ccenter = $_POST['ccenter'];
?>
Your data format is wrong ,must be {data-name:data-value}
data: {name: 'ccenter', value: 'Sales Department' }
So you should call by data-name
$ccenter = $_POST['name'];
I recommend you to use javascript dataform objects:
var formData = new FormData();
formData.append("ccenter", "Sales Department");
$.ajax({
url: 'empid_list.php',
type: "post",
async:true,
data: formData,
dataType: 'html',
success: function(data) {
$('#employeeid').html(data);
}
});
How to pass extra variables through $.ajax to post.php?
My first variable is
var form_data = new FormData($(this)[0])
I can pass it alone, but if I want to add another variable and make an array
data {
"form_data": form_data,
"name": "hello"
}
it does't work.
My current code:
$(document).ready(function() {
$("form#data").submit(function(){
var form_data = new FormData($(this)[0]);
$.ajax({
url: 'post.php',
type: 'POST',
data: form_data,
success: function (data) {
$('#result').html(data);
},
contentType: false,
processData: false
});
return false;
});
});
<div id="result"></div>
<form id="data" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<button>Submit</button>
</form>
Try this. The formData object has a method append. We're going to use that instead. We're going to append the file under the name file. In PHP access it with $_FILES['file']. Now for the array or object that you want to add to it. Use JSON.stringify on it to turn it into a string. We append the JSON string and add it to the name 'object'. To access the JSON in PHP json_decode($_POST['object']) will turn it into an object.
Fiddle
$(function(){
$("form#data").submit(function (e) {
e.preventDefault();
var form_data = new FormData(),
o = {};
o.name = 'Adam';
o.arr = ['test', 213];
form_data.append('file', $('input[name="file"]', this)[0].files[0]);
form_data.append('object', JSON.stringify(o));
$.ajax({
url: '/info/',
type: 'POST',
data: form_data,
success: function (data) {
$('#result').html(data);
},
contentType: false,
processData: false
});
return false;
});
});
I would JSON.stringify it then json_decode when you get it back in PHP
var data = JSON.stringify({ /* object */ });
Then in your php
$data = json_decode(....);
Try to define a new bariable
var name = "hello";
and then insert it into $.ajax data
$.ajax({
url: 'post.php',
type: 'POST',
data: "form_data="+form_data+"&name="+name,
success: function (data) {
$('#result').html(data);
},
contentType: false,
processData: false
});
I never test this script, but there's no matter to check it out :D
I am trying to get the results of an ajax request in wordpress, but I am getting result of '0' in an alert box of javascript, so the form looks like this:
<form class="form" id="ajax-contact-form" action="#">
<input type="text" name="name" id="name" placeholder="Name" required="">
<button type="submit" class="btn">Submit</button>
</form>
The javascript looks like this:
$('#ajax-contact-form').submit(function(e){
$.ajax({
data: {action: 'contact_form'},
type: 'post',
url: ajaxurl,
success: function(data) {
alert(data); // This prints '0', I want this to print whatever name the user inputs in the form.
}
});
})
And the PHP:
add_action('wp_ajax_contact_form', 'contact_form');
add_action('wp_ajax_nopriv_contact_form', 'contact_form');
function contact_form()
{
echo $_POST['name'];
}
Does anyone know if the code above is correct, I have also tried $_REQUEST['name'] and it doesnt work.
Thanks soo much,
Try something like this, you did not add the name parameter you are expecting in your PHP contact_form function, so you must add it to the data attribute in the jQuery ajax function call.
$('#ajax-contact-form').submit(function(e){
var name = $("#name").val();
$.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: ajaxurl,
success: function(data) {
console.log(data); //should print out the name since you sent it along
}
});
});
Revisiting the answer, year is 2022. The Accepted answer is accepting BLINDLY any AJAX request without verifying WordPress Nonces. AJAX request should be validated as a legitimate request instead of a potentially nefarious request from some unknown bad actor.
#see https://developer.wordpress.org/plugins/javascript/enqueuing/#nonce
The first thing your AJAX handler should do is verify the nonce sent by jQuery with check_ajax_referer(), which should be the same value that was localized when the script was enqueued.
First we pass the AJAX url and create and pass our nonce through wp_localize_script(). wp_localize_script() must be called after the script has been registered using wp_register_script() or wp_enqueue_script().
<?php
wp_localize_script( 'script', 'localize',
array(
'_ajax_url' => admin_url( 'admin-ajax.php' ),
'_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
)
);
From our script.js file we declare our AJAX function.
$(function(){
$('button').click(() => {
$.ajax({
type: 'POST',
url: localize._ajax_url,
data: {
_ajax_nonce: localize._ajax_nonce,
test: 'test',
/**
* The action parameter is the The dynamic portion of the wp_ajax_{$action} action hook (Ajax action callback being fired).
*
* #see https://developer.wordpress.org/reference/hooks/wp_ajax_action/
* #see https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/
*/
action: '_POST_action',
},
success: (res) => {
console.log(res);
}
});
});
});
And we process the result and send a JSON response back to an Ajax request.
<?php
add_action( 'wp_ajax__POST_action', function () {
if ( check_ajax_referer( '_ajax_nonce' ) ) {
$test = $_POST['test'];
//...
wp_send_json_success();
} else {
wp_send_json_error();
};
} );
You should add an attribute for name too in your javascript.
It may look like this........
$('#ajax-contact-form').submit(function(e){
$.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: ajaxurl,
success: function(data) {
alert(data);
}
});
})
You should include this script in functions.php
wp_register_script('my_script_handle','');
wp_add_inline_script('my_script_handle', "var techy_ajaxurl = '".admin_url( 'admin-ajax.php' )."';" );
wp_enqueue_script( 'my_script_handle' );
and in js change to this
$.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: techy_ajaxurl,
success: function(data) {
alert(data);
}
});
It will work 100% tested
hi i want to submit the page through following code but i can't get post data on ajax.php
please tell me where i am wrong
new Ajax(wgScriptPath +'/' + 'ajax.php', {
method: 'post',
data:{items:item},
onComplete: function(res)
{
////Code
}
to keep it simple and fast you can use open source jquery.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
check links below
- http://api.jquery.com/category/ajax/
http://api.jquery.com/jQuery.post/
example
<script>
$(document).ready(function() {
$('#checkbox').click(function() {
$.ajax({type : "POST",
url : "test.php",
data : "ffs=somedata&ffs2=somedata2",
success : function() {
alert("something");
}
});
});
});
</script>
<body>
<input type = "checkbox" name = "checkbox" id = "checkbox">
</body>
Mention the framework you are using, assuming you are using prototype, try below code
new Ajax(wgScriptPath +'/' + 'ajax.php', {
method: 'post',
parameters:{items:item},
onComplete: function(res)
{
////Code
}
});