如何在提交表单时将PHP变量传递给Javascript cookie?
I am setting up a custom form to be used in my wordpress site. What I would like to do is grab the AUTO_INCREMENT ID of that submission and pass it into a Javascript cookie when the form is submitted. Currently the ID is working, but because the ID isn't grabbed until after the form is submitted, I'm having trouble figuring out how I can pass the variable into the cookie immediately after the form has been submitted(currently I have to submit the form twice before the cookie with the ID is created, and its 1 number lower than it should be since it's a submission behind).
Here's what I have currently:
<?php
if(isset($_POST["submit"])) {
$name = $_POST['full_name'];
$city = $_POST['city'];
$state = $_POST['state'];
$email = $_POST['email'];
$wpdb->insert(
'reps',
array(
'name' => stripslashes($name),
'city' => stripslashes($city),
'state' => stripslashes($state),
'email' => stripslashes($email)
)
);
$lastid = $wpdb->insert_id;
}
?>
<script>
$('#dealer-form').submit(function() {
var repID = '<?php echo $lastid ?>';
setCookie('ID', repID);
});
</script>
As I mentioned this code works on the second submission(since the variable has no value on the first submission), and the ID is 1 number behind because it is grabbing the ID of the previous submission before reassigning the variable value.
我正在设置一个自定义表单,用于我的wordpress网站。 我想要做的是获取该提交的AUTO_INCREMENT ID,并在提交表单时将其传递给Javascript cookie。 目前ID正在运行,但由于在提交表单之前不会抓取ID,因此我无法确定如何在表单提交后立即将变量传递到cookie中(目前我必须提交 在创建带有ID的cookie之前两次使用该表单,并且它的1位数应该低于它应该是因为它是后面提交的。) p>
这是我目前所拥有的: p> \ n
&lt;?php
if(isset($ _ POST [“submit”])){
$ name = $ _POST ['full_name'];
$ city = $ _POST [' city'];
$ state = $ _POST ['state'];
$ email = $ _POST ['email'];
$ wpdb-&gt; insert(
'reps',
array (
'name'=&gt; stripslashes($ name),
'city'=&gt; stripslashes($ city),
'state'=&gt; stripslashes($ state),
'email'=&gt ; stripslashes($ email)
)
);
$ lastid = $ wpdb-&gt; insert_id;
}
?&gt;
&lt; script&gt;
$('#dealer-form' ).submit(function(){
var repID ='&lt;?php ec ho $ lastid?&gt;';
setCookie('ID',repID);
});
&lt; / script&gt;
code> pre>
正如我所提到的 此代码适用于第二次提交(因为变量在第一次提交时没有值),并且ID后面是1个数字,因为它在重新分配变量值之前抓取先前提交的ID。 p>
div>
PHP, being a server-side scripting language, is executed before the data is sent to your browser. JavaScript, a client-side scripting language, is executed as soon as the script is encountered by the browser.
Your approach is forgetting this separation between front- and back-end.
To accomplish what you're trying to do, simply output the setCookie
call when you've submitted your form in php:
<?php
if(isset($_POST["submit"])) {
$name = $_POST['full_name'];
$city = $_POST['city'];
$state = $_POST['state'];
$email = $_POST['email'];
$wpdb->insert(
'reps',
array(
'name' => stripslashes($name),
'city' => stripslashes($city),
'state' => stripslashes($state),
'email' => stripslashes($email)
)
);
$lastid = $wpdb->insert_id;
printf( '<script>setCookie("ID", %d);</script>', $lastid );
}
?>