Passing a form field to ajax, and then posting it via php

1.1k Views Asked by At

I trying to modify Wordpress plugin. It uses a front-end form, processed with ajax/jquery to post submissions into various logs. I need to add an additional field, pass its value to the .js file and post the additional field as well.

So far I have added the additional field by hooking into an existing function. The field looks like this and is visible on the front end.

$description_input = '<input type="text" id="custom_message" 
name="custom_message" value="" class="transfer-description" 
placeholder="Description" />';
echo $description_input;

The form that this extra field is added into has existing fields: to, sender, recipient, amount, token, and a submit.

What I don't understand is how to pass this extra field to the ajax function.

The first part of the .js file that is processing the form looks like this:

The developer has been helping me, or I'd never make it even this far... He added 'info' and tinfo : info , which I think is supposed to handle the extra field.

jQuery(function($){
// Transfer function
var transfer_creds = function( to, creds, info, label ) {
$.ajax({
type : "POST",
data : {
action    : 'myc-transfer-creds',
sender    : myC.user_id,
recipient : to,
amount    : creds,
token     : myCRED.token,
tinfo     : info
},
dataType : "JSON",
url : myC.ajaxurl,
... (the rest of the .js here)

Then to insert the extra field into the log entries the developer was using this:

$transfer_message = '';
if ( isset( $_POST['tinfo'] ) )
$transfer_message = sanitize_text_field( $_POST['tinfo'] );

This is not the complete code, but seems to be the relevant part. So, my question again is how to send an additional form field to ajax, then posting that information via php? I'm not sure I've explained this properly, but thanks for the help.

2

There are 2 best solutions below

1
On

I will just copy your above code as it is and only mark the changes i have made that i think will work for you:

jQuery(function($){

var info = $('#custom_message').val(); //add this line to get your message

// Transfer function
var transfer_creds = function( to, creds, info, label ) {
$.ajax({
type : "POST",
data : {
action    : 'myc-transfer-creds',
sender    : myC.user_id,
recipient : to,
amount    : creds,
token     : myCRED.token,
tinfo     : info
},
dataType : "JSON",
url : myC.ajaxurl,

... (the rest of the .js here)

Let me know if this works.

0
On

first you need to get the value of the required field ,just like you get the value of info

and add it to the data args after tinfo like:

tinfo     : info,
tcustom_message  : custom_message

you can access this data using $_POST['tcustom_message ']