I have a HTML form embedded within a PHP file with an onclick button which summons a javascript function.

<form name="addStamp">
    Validation Code:<br>
    <input type="number" name="inputcode"><br>
    <input type="text" name="message" id="message"><br>
    <input type="button" name="submitbutton" value="Submit" onClick="stampme()">

The function looks at the entry in "inputcode" field and:

  • if valid returns the word "valid" into the "message" field
  • if void returns the word "failed" into the "message" field

Script snippet that populates the form:

document.addStamp.message.value = msg;
document.addStamp.inputcode.value = "";
} else if (document.addStamp.inputcode.value != test) {
document.addStamp.message.value = msg2;

What I can't figure out is now how to bring the result back into php so I can use it to perform a update_user_meta task.

All of the above happens without refreshing the page and I need to get the result of the javascript function back into php without refreshing the page also.

Any help please?


Perhaps you could either use admin ajax or the WP REST API to send a request to the server for the user meta update.

If you have a look at the WP documentation (links above) or similar questions here on WPSE, you can find examples on how to do it.

  1. Update user meta with ajax https://wordpress.stackexchange.com/search?q=Update+user+meta+ajax
  2. Update user meta with rest api https://wordpress.stackexchange.com/search?q=Update+user+meta+via+REST+API%3F
| improve this answer | |

You need an ajax call to perform server-side functions.

So in stampme() before or after you show the message you need something like this:

      url: ajaxurl,
      data: {
        action: 'WPSE_339452_update_user_meta',
        value: jQuery('input[name="inputcode"]').val() //if that's the value you want to save...
      success: function (result) {
        // whatever JS based on the result that can be true / false 
      error: function (errorThrown) {

On the server side you've to define your custom ajax hook that updates the user_meta value:

function WPSE_339452_update_user_meta (){
  /* the return of update_user_meta can be 
     true= value updated, 
     false = value not updated since it was the same as the old value 
     in this case it won't update */
add_action ("wp_ajax_WPSE_339452_update_user_meta","WPSE_339452_update_user_meta");
| improve this answer | |
  • Thank you for the explaination. This is so far over my head, seems I really need to go away and research ajax and it's uses. I think because I could interact from php (html) into Javascript I expected to easily be able to pull a variable back the other way. – Shaun21uk Jun 5 '19 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.