开发者

How to pass var's to another page using jquery & php

I am trying to figure out how to pass my form var's to anothe page..

var login = $('#login').val();
var pass = $('#pass').val();
var data = {
    login: login,
    pass: pass
};

$.ajax({  
    type: "POST",
    data: data,
    url: "page_2.php",
    success: function(data)
    {
        document.location.href = url;

    }
}); 

It doesn't post to the new page at all.. In page_2.php I have:

<?php
        $error = false;


        if (isset($_REQUEST))
        {
            extract($_REQUEST);   
            print_r($_REQUEST);
     开发者_Go百科   }
//      else
//      {
//              header("location:page_1.php");
//      }

?>

I've searched google for 2 days with no luck on examples of posting var's to another page via jquery/ajax/php.. Can anyone help or point me to a link that can?

Thanks so much!


@Dennis -

IOW, you are trying to save state from one page to be utilized on the 2nd page.

The proper way to do this is to post data via form submission. You can do it with an ajax request, but you add un-needed complexity to your code. Use AJAX for when you need to pass data to the server, but want to stay on the same page.

Follow Blackcoat's recommendation. Form Submission

Remember if all you have is a hammer, then your going to be whacking everything including your thumb. Always go with the simple solution first.


Dennis,

After submitting a form, if you want to take the user to a page using that new data, you don't want to use Ajax. Just set the "action" attribute on your <form> to 'page_2.php', and be on your way. You don't even need Javascript for this situation.

<form method="post" action="page_2.php">
  <!-- your form fields go here -->
</form>

If you do need to use Ajax in the future, I have a few suggestions. Run Firebug (for Firefox) or Webkit's Developer Tools (for Safari or Chrome) to examine the Ajax requests being sent, and if/why they are failing. You've got the right idea, but it's possible that your data is never making it to page_2 (e.g. bad URL, a Javascript error elsewhere that prevents the $.ajax from being run, etc.)

Simplify your Ajax submission using jQuery.post(). Combine this with jQuery.serialize() to gather all of the form data for you, and bind this as a submit handler for your <form>. For example:

$('form').submit(function() {
  var url = 'page_2.php';
  $.post(url, $(this).serialize(), function( data ) {
    console.log("Success!\nData: " + data);
  });
  return false;
});

On the PHP end, you have the right idea. I recommend using $_POST instead of $_REQUEST to reduce the possibility of a CSRF.


the url variable is not known to the success callback function...

try alerting something alert(data); inside the success function to see if it get called..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜