简体   繁体   中英

How to post variable using jQuery to PHP?

I want to post a variable to PHP page using jQuery and then redirect on that PHP page and echo posted variable.

HTML:

$(document).ready(function() {
$('.restauarnt_result').click(function() {
    var RestName = $('#restauarnt_name', this).html();
            $.post('restauarnt.php', { RestName : RestName } );
            window.location = 'restauarnt.php';
});
});

After I click on $('.restauarnt_result') , automatically redirect to 'restauarnt.php' URL and echo the posted data.

PHP:

<?php
   echo $_POST['RestName'];

The point of Ajax is to communicate with the server without leaving the current page.

Since you want to leave the current page, don't use Ajax.

Create a form, and submit it.

var f = jQuery("<form>", { action: 'restauarnt.php', method: 'post' });
f.append(
    jQuery("<input>", { type: "hidden", name: "RestName", value: RestName })
);
jQuery(document.body).append(f);
f.submit();

There's not much point in using ajax if you're immediately going to redirect

<form method="post" action="restauarnt.php">
<input name="RestName"/>
<input type="submit"/>
</form>

restauarnt.php

<? 
echo $_POST['RestName'];

On the PHP side use session:

<?php
session_start();
// store session data
$_SESSION['RestName']= "RestName";
?>

After reload, this value will be in the new session variable.

You should redirect after the call is completed. So try this-

$.post('restauarnt.php', { RestName : RestName }, function(data){
   // here the call is completed
   console.log(data); // this will print the values echo by the php
   window.location = 'restauarnt.php';
} );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM