Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

William Romero
William Romero
4,807 Points

How update custom fields with ajax in Wordpress?

I'm working on a Profile Page, where users can modify fields like name, address, etc; but i don't want to use a button to save all the fields, just the field(s) that changed . The users data will be loaded automatically from the registration sign in. So, i just need to change some values where the user might have entered something incorrectly. My way to save the data will be a

<input type="text" name="name" /> where the <a href="" onclick"function">

which will redirect to the ajax module, as i see. But, i really don't know anything about working the ajax native functions & hooks for wordpress.

== original message ==
I'm working on a Profile Page, who may be able to users to can modify fields like name, address, etc; but i don't want to use a button to save the whole fieds, just the field who is modifying indeed. The users data will be loaded automaticly from the registration sign in. So, i just need to change some values who users might insert wrong. My way to save the data will be a <input type="text" name="name" /> where the <a href="" onclick"function"> who gonna redirect to the ajax module, as i see. But, i really don't know anything about working the ajax native functions & hocks for wordpress.

Andrew McCormick
Andrew McCormick
17,730 Points

William. I hope you don't mind, I edited your question to make it more readable. I hope I captured everything you wanted to ask correctly.

William Romero
William Romero
4,807 Points

Please Andrew McCormick, feel free to modify my text if you think that it isn't understandable. I'm not a native english speaker but i'm happy to get help like yours to get some help in this question.

2 Answers

Andrew McCormick
Andrew McCormick
17,730 Points

Essentially all you need to do is create the inputs on a page and fill them with the usermeta as the initial value. Then on change, pass the input values to a php file via ajax to update the usermeta.

Below is a really rough idea. This code is not perfect just typed it off the top of my head, but should get you started in the right direction.

//put this in a custom template or shortcode to display on page
$user_id = get_current_user_id;
<input type="text" name="eye_color" id="eye_color" value="<?php get_user_meta($user_id, 'eye_color', true);  ?>"/> 
<input type="hidden" id="userID" value="<?php echo $user_id ?>"/>

since you want to do this without a button, then have an onchange call in your js

<script>
$(document).ready(function(){
    $('input').change(function(){
  var metavalue= this.val();
  var metakey=  this.attr('id');
  var user = $('#userID').val();
        $.post("updateUser.php",{
            user : user,
            metavalue : metavalue,
            metakey : metakey
         },
      function(result){
            alert("Data Updated");
            });
    });
});
</script>

then have a php file updateUser.php

<?php
$userID = sanitize_text_field($_REQUEST['userID']);
$metakey = sanitize_text_field($_REQUEST['metakey']);
$metavalue =  sanitize_text_field($_REQUEST['metavalue']);
update_usermeta( $userID, $metakey, $metavalue );
return "success";
William Romero
William Romero
4,807 Points

Thank you Andrew McCormick! Great way to do that. I tried many ways to do that, but i got the same result since i read an article and i got this example:

Create the file: userInformation.php:

<?php
    echo  "<input type='text' onmouseout='getContent(this)' name='name' placeholder='".get_post_meta( $post->ID, 'country', true )."' />";
?>

Into the same file, i had to create a JS script code:

<script type="text/javascript">
   function getContent(content){ // function that initialize when the user left the the box, sending the object element.
    var postId = document.getElementById("postId").value; // I got the post->ID to the hidden input text field.
    var field = content;
    var fieldName = content.name; // get the name of the element, because it will be the identity who we gonna change.
    var fieldValue = content.value; // get the value of the element.
    jQuery(document).ready(function($) {
       var elem = fieldName; //get the fieldName value
       var containValue = fieldValue; // get the contain value who will be updated 
    //console.log('fieldName: '+elem+' ContainValue: '+containValue );
       jQuery.ajax({ // We use jQuery instead $ sign, because Wordpress convention.
        url : 'https://example-site.com/wp-admin/admin-ajax.php', // This addres will redirect the query to the functions.php file, where we coded the function that we need.
        type : 'POST',
        data : {
            action : 'my_action', 
            fieldname : elem,
            fieldvalue : containValue,
            postid : postId
        },
        beforeSend: function() {
               //console.log('Updating Field');
        },
        success : function( response ) {
             //console.log('Success');
        },
        complete: function(){
            alert( "Field updated");
        }
       });
    });
   }
</script>

Finally, we going to create the action on the functions.php:

<?php
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // This lines it's because we are using AJAX on the FrontEnd.

function my_action(){
    $fieldname = $_POST['fieldname']; // This variable will get the POST 'fieldname'
    $fieldvalue = $_POST['fieldvalue'];  // This variable will get the POST 'fieldvalue'
    $postid = $_POST['postid'];             // This variable will get the POST 'postid'
    update_post_meta($postid, $fieldname, $fieldvalue); // We will update the field.
    wp_die($fieldname = '', $fieldvalue = '', $postid = ''); // this is required to terminate immediately and return a proper response
} 
?>

That's the way i found a solution. If somebody else want to share other option, feel free to show us here.