Chamath Gunasekara
Chamath Gunasekara

Reputation: 129

passing data using post array in java-script

i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.

code list as follows A.php

<script type="text/javascript">
     alert_for_the_fucntion();
     window.location.href = "B.php";
     function  alert_for_the_fucntion() {
          $.post("B.php", {action: 'test'});
     }
</script>

B.php

<?php 
if (array_key_exists("action", $_POST)) {
    if ($_POST['action'] == 'test') {
        echo 'ok';       
    }    
}    
?>

for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.

Upvotes: 1

Views: 55

Answers (2)

Quentin
Quentin

Reputation: 943142

Your code does this:

  1. Tells the browser to navigate to B.php (using a GET request)
  2. Triggers a POST request using XMLHttpRequest

The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.

You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.


If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.

Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).

var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";

var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";

f.appendChild(i);
document.body.appendChild(f);
f.submit();

If you want to process the results in JavaScript then:

  1. Don't navigate to a different page (remove the line using `location)
  2. Add a done handler to the Ajax code

e.g.

$.post("B.php", {action: 'test'}).done(process_response);

function process_response(data) {
    document.body.appendChild(
        document.createTextNode(data)
    );
}

Upvotes: 3

Ankit Singh
Ankit Singh

Reputation: 1477

Try this:

Javascript:

<script type="text/javascript">
    window.onload = alert_for_the_fucntion;
    function  alert_for_the_fucntion() {
        $.post("B.php",
               {
                 action: 'test'
               },
               function(data, status){
                  if(status=="success"){
                     alert(data);
                  }
               }
        );
    }
</script>

PHP

<?php 
if(isset($_POST['action'])){
        echo $_POST['action'];       
}
?>

Upvotes: 1

Related Questions