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
Related
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.
So I am working on a project in which I have to pass some form data to a database without reloading the page using Ajax. But the $_POST variable in the PHP file is always empty. I do know that I am actually getting the data from the form since I can print and it looks okay in the javascript code:
$(document).ready(function () {
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
type: 'POST',
data: {name: 'tony'},
dataType: 'json',
success: function (response) {
$('#message').html(response);
}
});
//return false;
});
});
And this is the php code:
<?php
//var_dump($_POST);
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
} else {
echo "error";
}
?>
Use this code instead, you won't need to manually define the parameters to be sent because it will be automatically set by FormData():
$('#form').submit(function(event) {
event.preventDefault();
var data = new FormData(this);
$.ajax({
url: "post.php",
type: "POST",
data: data,
contentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
So, turns out I am just stupid.. It was actually working properly after all but I was checking if it works the wrong way. I was actually navigating to the php file by entering the url expecting to see my data printed on the php page. Finally, I checked the response of the POST request and it was working just fine.Thank you for your answers and I apologize for wasting your time.
try this,
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
method: 'POST',
data: {name: 'tony'},
success: function (response) {
$('#message').html(response);
}
});
});
I have installed the wordpress fuel plugin. By this I have created a plugin to list the property.
Here I have integrated one ajax call like this
In my view file i use this below code:
$('#collapse3').click(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url:"<?php echo $plugin->dispatchRequest("saleshome/index",array('lat' => $latitude,'lng'=>$longitude)); ?>",
data: { },
success: function(data){
$('#collapse3_res').html(data);
}
});
});
By using this code, it is not working. I don't know how to write this. Please help me. Thanks
Try Ajax code like this:
jQuery( document ).on( 'click', '#collapse3', function() {
var data = { };
$.ajax({
type: "POST",
url:"<?php echo $plugin->dispatchRequest("saleshome/index",array('lat' => $latitude,'lng'=>$longitude)); ?>",
data: data,
cache: false,
success: function(response){
$("#collapse3_res").html(response);
}
});
});
javascript add in wp_footer hook on function.php
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
bellow wp_ajax hook add on function.php
add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
function prefix_ajax_add_foobar() {
// Handle request then generate response using WP_Ajax_Response
// Don't forget to stop execution afterward.
wp_die();
}
I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.
First, I'm using the codeigniter framework and I'm a beginner in JS and AJAX, so please bear with me.
I read this question, so I tried to follow the answers.
This is the script (UPDATED):
$(function() {
$( "#datepicker").datepicker().click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
return false;
});
});
And this is my datepicker HTML code:
<input type="text" id="datepicker" name="datepicker"
value="<?php echo isset($umat['tanggal_lahir'])?$umat['tanggal_lahir']:""?>"/>
My questions are (UPDATED):
Is the URL I provided in AJAX above correct?
How should I pass the data from AJAX to PHP (url: "<?php echo base_url(); ?>backend/umat/add")?
Thanks for your help :D
What you have missed here:
your click event is outside of the doc ready handler, that should be inside doc ready so that when page gets ready the element should be available to click.
You have missed a closing }); tag of the click event.(does not matter though)
so try this:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: {frmData : $('#form_daftar').serialize()}, // <----send this way
success: function(data) {
console.log(data.date);
// here data is the returned data from the specified url and make sure
// that url is generating a proper json structrue.
// suppose there is a key named date which holds the submitted date so
// data.date will get you the date.
}
});
}); //<----you missed this closing of click function.
}); //<----------put everything before this closing of doc ready handler.
Although you can chain it too like this:
$(function(){
$( "#datepicker").datepicker().click(function() {
//......ajax function in click here
});
});
See a demo here
Another approach would be to use the datepicker inbuilt methods to trigger ajax request like
$('#datepicker').datepick({
dateFormat:"yyyy-mm-dd",
onSelect:function(){
$.ajax({
type: 'POST',
url: "<?php echo site_url('backend/umat/add'); ?>",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
}
});
Check the manual or inbuild functions and callbacks with your datepicker js.
try it:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").change(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
});
php get data form ajax:
<?php
$date = $_POST["datepicker"];
?>