0

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'];
1
  • 1
    Why post and redirect at the same time... despite the programing thing, this does not make sense at all. Commented Mar 30, 2014 at 14:01

4 Answers 4

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

I agree with this answer, jquery to form variable (hidden), very simple solution.
No, that's as simple as it gets.
1

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

1 Comment

This doesn't handle the content of the JS variable RestName.
0

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

2 Comments

sir, error : Undefined index: RestName in C:\wamp\www\restauarnt.php on line 6
console.log(RestName) before calling the ajax.post
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.