From guides I have gotten this far:
add_action('wp_enqueue_scripts', 'do_enqueue_scripts');
function do_enqueue_scripts()
{
wp_enqueue_script('Java', plugins_url( '/js/form.js', __FILE__ ), array('jquery'), '1.0', true);
wp_localize_script( 'Java', 'start', array(
'code' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_ajax_nopriv_func', 'func');
add_action('wp_ajax_func', 'func');
function func()
{
$From = $_POST['dateTo'];
$To = $_POST['dateFrom'];
$Name = $_POST['Name'];
echo $From . " - " . $To . " - " . $Name;
die();
}
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: start.code,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data) {
alert(data);
}
});
}));
My problem comes in with the AJAX call. I am still getting used to this action system WordPress is using and I am not sure what I need to change my data to. I have a generic form with 2 dates and a name; nothing crazy. However the returned data to my AJAX call is zero.
I believe my issue now is how I m either returning data to my ajax or with the data type I am send to my PHP function func().
No errors in chrome or mozilla consoles.
Add a hidden input field to your form with the name of the action so wp can execute the right function
<input type="hidden" name="action" value="func">
change your ajax to:
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: start.code,
type: "POST",
data: $(this).serialize(),
cache: false,
success: function(data) {
alert(data);
}
});
}));
Related
I have a form that is handled via $.post, sending data to a php script. My client just asked me to include the ability to upload an image using this (and a few other) forms.
I have been googling around on this for about an hour, and haven't seen any evidence that you can actually do this using $.post(), so I wanted to reach out and see if there is a way to do this.
the form is handled this way:
jQuery( '.js-saveProduct' ).click(function(e) {
e.preventDefault();
acSaveProduct( jQuery(this).serializeArray() )
};
var acSaveProduct = function( form ) {
var _data = {
action: 'ac_save_product',
form: JSON.stringify( form )
}
jQuery.post(
ajaxscript.ajaxurl,
_data,
function( response ) {
// Do Stuff
}
);
};
If I console.log(form) after acSaveProduct() is called, the upload fields aren't even in the array of objects that gets logged.
I haven't even started on the PHP side of this, as I know that the form object that gets passed to my PHP function doesn't contain the values I am looking for.
EDIT TO SHOW NEW ATTEMPT
So, trying the technique linked by #Andreas, I'm still having trouble with this. Below is my update jQuery / PHP code:
HTML
<input type="file" name="acImageNew" id="acImageNew">
jQuery
var acSaveProductAlt = function( form ) {
var file_data = jQuery( '#acImageNew' ).prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
jQuery.ajax({
url: the_ajax_script.ajaxurl,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
action: 'ac_ajax_save_product_alt',
success: function( response ) {
alert(JSON.parse(response.success));
}
});
};
PHP
function ac_ajax_save_product_alt(){
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
$response = json_encode(
array(
'success' => true,
)
);
header( "Content-Type: application/json" );
echo $response;
exit;
}
At the end of it all, I get an alert with 0 as the contents of the alert. What am I doing wrong?
Try JSON parsing the response first, then accessing the success key.
jQuery.ajax({
url: the_ajax_script.ajaxurl,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
action: 'ac_ajax_save_product_alt',
success: function( response ) {
alert(JSON.parse(response).success);
}
});
$('.single_add_to_cart_button').click(function() {
$.ajax({
type: "POST",
url: script_e.ajaxurl, //url loaded from the plugin
data: {id:test},
cache: false,
success: function(data){
alert(data);
}
});
});
//php
public function enqueue_scripts(){
wp_enqueue_script( 'e_jquery', plugin_dir_url( __FILE__ ).'../assets/js/script_e.js' );
wp_localize_script( 'e_jquery', 'script_e',
array(
'ajaxurl' => plugin_dir_url( __FILE__ ).'event-capture.php' ,
)
);
}
add_action( 'wp_enqueue_scripts', array($this,'enqueue_scripts') );
I am trying to pass some variables in the the PHP script when the button is clicked, the php script is located in the plugin.
Only way this works is if I debug step by step in the firebug, then the value is passed, else it fails.
Basically add event.preventDefault();after ajax call
Something like this,
$('.single_add_to_cart_button').click(function(event) {
$.ajax({
type: "POST",
url: script_e.ajaxurl, //url loaded from the plugin
data: {id:test},
cache: false,
success: function(data){
alert(data);
}
});
event.preventDefault();
});
I have my AJAX working and I can INSERT new data in the database. Basically I can not get an array to echo back into my page. I was wondering, do I need a separate AJAX to get the information from my first AJAX and will it work? Here is my code:
<?
$msg = array ("MSG1"=>"Error","MSG2"=>"Registered");
if(isset($_POST['register'])){
echo $msg['MSG1'];
}
?>
<script>
function Registration(){
var values = {};
values['register'] = '';
$.ajax({
'url' : '',
'type' : 'POST',
'data' : values,
success : function(data){
}
})
}
</script>
How can I get my Array to echo back from AJAX?
How about this one?
formData = {
register: register
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "http://localhost/register.php",
dataType: "json",
data: formData,
success: function(data) {
console.log(data);
//success handler
},
error: function(data) {
//error handler
}
});
about your 'Array to echo back from AJAX', you need to setup if else condition in your 'http://localhost/register.php' . Let say if condition A, "MSG1"=>"Error". If condition B, "MSG2"=>"Registered".
Please refer to this site for your reference.
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
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
I'm sending an ajax call to my PHP script as follows:
function load(){
var request = {};
request['action'] = 'load';
request['file'] = 'lorem_ipsum.txt';
$.ajax({
type: 'POST',
url: cgi_file,
data: JSON.stringify(request),
processData: false,
dataType: 'html',
contentType: 'application/html',
success:function(response){
console.log("received " + response);
}
});
}
and my PHP script is as follows:
$content_dir = '/static/content/';
$action = $_POST['action'];
switch ($action){
case 'load':
$file = $_POST['filename'];
echo file_get_contents($content_dir . $file);
exit();
}
The PHP is responding with the following failure:
Notice: Undefined index: action in /var/www/river/api.php on line 5
What's the issue here?
Try ditch processData: false and contentType: 'application/html' and it should work
$.ajax({
type: 'POST',
url: cgi_file,
data: request,
dataType: 'html',
success:function(response){
console.log("received " + response);
}
});
Just leave data as it is:
data: request,
You don't need to stringify it.
Also, your file parameter allows an attacker to read arbitrary files from your filesystem. Sanitize it.
A few things wrong here, firstly the contentType property is for the data you are sending to the server, secondly dataType should be set to text as that is what you are recieveing from the server. If you want to receive the data in the $_POST array your javascript should look like this,
$.ajax({
type: 'POST',
url: cgi_file,
data: {
action: "load",
file: "lorem_ipsum.txt";
},
dataType: 'text',
success:function(response){
console.log("received " + response);
}
});
Jquery will send your data as a standard post to your server side code.