0

I've just checked a double click on my form that inserts new user meta, which actually inserted it twice! The problem is, I actually need the values to be non-unique so I can insert multiple times.

My aim is simple, to capture post the data from the form into the user_metatable only once from the form, but it seems to insert twice, three times... As many times as I click the submit button.

I've tried this Javascript:

var wasSubmitted = false;    
function checkBeforeSubmit(){
  if(!wasSubmitted) {
    wasSubmitted = true;
    return wasSubmitted;
  }
  return false;
}  

And nothing happened, I'm wondering, how do I do this with PHP? Or even a bit of Javascript that will actually work.

Ideally, I don't want to use jQuery, I prefer simple JS.

2

Dunno if you looked at add_user_meta, but it takes an optional fourth parameter.

function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false )

Send "true" to the $unique value and it won't insert it twice.

https://developer.wordpress.org/reference/functions/add_user_meta/

  • I did actually, but this then only allows one existing row associated with that user meta, I have tested with this and doesn't allow another user to insert user meta. – Jake Punton Jun 29 '18 at 16:04
  • I thought that was the point of your question? You don't want to allow the rows to be inserted twice. – Otto Jun 29 '18 at 21:26
  • No, if a user double clicks submit, it posts the data twice. I want to be able to enter only once per click, but not have the value to be unique and only ever entered once. – Jake Punton Jul 10 '18 at 12:17
  • Okay, so, I don't understand the question then. You might want to clarify what exactly it is that you want to happen. – Otto Jul 10 '18 at 19:40
  • For the data to insert once, although the button is clicked numerous times. – Jake Punton Jul 12 '18 at 7:36
0

It will be far less effective trying to do it in JS than on the backend. Let JS call your script all you like, just have PHP prevent the duplicates. Unfortunately, there doesn't seem to be a built-in method. You'll have to check manually, but it's not super hard. Instead of:

add_user_meta($userid,$yourkey,$valuetoadd);

Do this:

$yourkey_arr = get_user_meta($user_id,'yourkey');
if (!in_array($valuetoadd,$yourkey_arr))
    add_user_meta($user_id,'yourkey',$valuetoadd);

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.