سؤال

I'm currently using wordpress 3.5 and creating a page template of my own. I have my own form in that template and when I click the submit button, it is successfully saved the data to my database. Unfortunately, when I click F5 or refresh button on my browser, It prompts an alert which says there will be a double form submission if I continue.

Usually I prevent this by using "redirect to the same page after submitting" technique. But I can't use header("location: ") to redirect because it generates error: Warning: Cannot modify header information - headers already sent by. Probably there are echos on other wordpress file that prevent redirecting.

Does anyone know how to solve this? Or does anybody know other technique to prevent double form submission beside redirecting?

هل كانت مفيدة؟

المحلول

I've always done this with Javascript:

<?php if(isset($_POST['submit_flag'])){ ?>

<script type='text/javascript'>
    window.location='URL';
</script>

<?php } ?>

But now that I think about it, you could easily create another PHP page somewhere in your theme that's not included by the rest of your theme to handle the form data and re-direct back to your form.

I'm also about 98% sure that you can include $wpdb without sending headers by simply requiring "wp-blog-header.php".

نصائح أخرى

There is no output besides in your template file. What would that be? Look at the source code of your website, it's only exactly what you tell Wordpress to create.

So that's first: you can use header("Location: ") at the top of the template file that's called on first. Usually header.php.

Secondly, you can (and usually should) use hooks to handle forms. For example:

add_action( 'init', function() { 
    // Handle stuff
} );

But perhaps with a different hook (I don't recall any best practice). Tutorials here and there will give you suggestions. In this case you will definitely call header("Location: " ) before there is any output. Your theme hasn't even been involved yet.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top