Hii i am trying to save data of form to user meta data table by using javascript, AJAX and php. Here is my code
HTML Form:
<form id="savem" method="post">
<input type="text" name="profile_name" id="profile_name"/>
<input type="text" name="value1" id="value1"/>
<input type="text" name="value2" id="value2"/>
<input type="submit" value="save"/>
</form>
Enqueued the script in functions.php
function save_measurment() {
$theme_url = get_template_directory_uri(); // Used to keep our Template Directory URL
$ajax_url = admin_url( 'admin-ajax.php' ); // Localized AJAX URL
// Register Our Script for Localization
wp_register_script(
'measurment', // Our Custom Handle
"{$theme_url}/assets/js/measurment.js", // Script URL, this script is located for me in `theme-name/scripts/um-modifications.js`
array( 'jquery' ), // Dependant Array
'1.0', // Script Version ( Arbitrary )
true // Enqueue in Footer
);
// Localize Our Script so we can use `ajax_url`
wp_localize_script(
'measurment',
'ajax_url',
$ajax_url
);
// Finally enqueue our script
wp_enqueue_script( 'measurment' );
}
add_action( 'wp_enqueue_scripts', 'save_measurment' );
Javascript function to process meta values:
jQuery( 'document' ).ready( function( $ ) {
// Form submission listener
$( '#savem' ).submit( function() {
var measrumentData = {};
// Grab our post meta value
measrumentData.profile_name = $( '#savem #profile_name' ).val();
measrumentData.value1 = $(' #savem #value1').val();
measrumentData.value2 = $(' #savem #value2').val();
var jsonString = JSON.stringify(measrumentData);
// Do very simple value validation
$.ajax( {
url : ajax_url, // Use our localized variable that holds the AJAX URL
type: 'POST', // Declare our ajax submission method ( GET or POST )
data: {data: jsonString},
} )
.success( function( results ) {
console.log( 'User Meta Updated!' );
} )
.fail( function( data ) {
console.log( data.responseText );
console.log( 'Request failed: ' + data.statusText );
} );
return false; // Stop our form from submitting
} );
} );
and finally the ajax callback function
function measurment_callback() {
// Ensure we have the data we need to continue
if( ! isset( $_POST ) || empty( $_POST ) || ! is_user_logged_in() ) {
// If we don't - return custom error message and exit
header( 'HTTP/1.1 400 Empty POST Values' );
echo 'Could Not Verify POST Values.';
exit;
}
$user_id = get_current_user_id(); // Get our current user ID
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $key=>$value)
{
add_user_meta( $user_id, $key, $value );
}
exit;
}
Now whats happening is while submitting the form the console is showing meta values updated but phpmyadmin is giving error message "null is not an object (evaluating 'field_id.match(/[^-]+$/)')". I have no idea whats wrong so any help will be appreciable