boyrock75
boyrock75

Reputation: 1

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'];

Upvotes: 0

Views: 88

Answers (4)

Anri
Anri

Reputation: 1693

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.

Upvotes: 0

andrew
andrew

Reputation: 9593

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'];

Upvotes: 1

Quentin
Quentin

Reputation: 944568

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();

Upvotes: 1

Sahil Mittal
Sahil Mittal

Reputation: 20753

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';
} );

Upvotes: 0

Related Questions