0

Is there a way in jquery to submit a post without a form. like can I use the function $.post("script.php",{var1:"abc", var2: "cde"}) such that it will not run on the background but instead post and redirect the page to script.php file as if var1 and var2 were submitted via a form.

Neville Nazerane
  • 6,622
  • 3
  • 46
  • 79

1 Answers1

0

You can execute ajax request and make redirect to url when the response comes.

$.post("script.php",{var1:"abc", var2: "cde"},
    function(data) {
        if (data.success) {
            window.location.href = data.redirectTo;
        }

    }
)

in this case response from script.php should looks like {success:true, redirectTo: "newUrl.php"}

kemenov
  • 409
  • 4
  • 13
  • This code did not work. U dont think i used it right. function (data) { window.location.href = data.redirectTo: "script.php"; } is this fine? – Neville Nazerane Oct 27 '13 at 08:22
  • i want to do something like ` function (data) { $("body").html(data); } ` But I need the url to be changed as well – Neville Nazerane Oct 27 '13 at 08:25
  • @NevilleNazerane If you whant to execute request and cahnge body content without reloading, see this article http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page. – kemenov Oct 27 '13 at 08:31
  • @NevilleNazerane "This code did not work" - what error you are getting? – kemenov Oct 27 '13 at 08:34
  • @NevilleNazerane window.location.href = data.redirectTo: "script.php", data.redirectTo should contain url to new url, in case of you need redirect to scipt.php, you can make - window.location.hred = "/script.php" – kemenov Oct 27 '13 at 08:36
  • it shows "toReport is not defined" with `window.location.href = data.redirectTo: "script.php";` – Neville Nazerane Oct 27 '13 at 14:08
  • @NevilleNazerane try this: `window.location.href = "/script.php";` – kemenov Oct 28 '13 at 03:20