简体   繁体   中英

Ajax post to PHP not working

Hi i got a problem im doing a ajax post to a php file but in the php file its empty

JS
google.maps.event.addListener(marker, 'click', function(marker, i) {
return function() {

     var rid = locations[i][4]; //get id to varible
     console.log(rid);
     $.ajax({
            url: uri+'/helper.php',
            type: 'post',
            data: {'referens': rid},
            success: function(data){
                console.log(rid);
                window.location = uri+'/helper.php';
            },error: function(data){
                alert('error'); 
            }
        });
    }
}(marker, i));

and my helper.php

<?php 
$referens = $_POST['referens']; 
echo $referens;
echo 1;
?>

the output in helper.php is only 1 and not my referens post

what if i want to use it like this in same file with location.reload();

 success: function(data){
                console.log(data);
                location.reload();
            },error: function(data){
                alert('error'); 
            }
        });
    }
}(marker, i));

</script>
<?php include_once('helper.php');
 var_dump($referens); ?>

and helper.php

<?php 
   $referens = $_REQUEST['referens']; 
   echo $referens;
   echo 1;

   ?>

Your code looks fine.

You are printing the wrong variable.

Change

success: function(data){
  console.log(rid);
  window.location = uri+'/helper.php';
}

To

success: function(data){
  console.log(data); // Here you are getting return in data not as rid
  window.location = uri+'/helper.php?rid='+rid; // See, pass rid here.
}

in helper.php

<?php 
$referens = $_REQUEST['referens']; 
echo $referens;
echo 1;
?>

As per your comments on other answers and on your post, I would like to mention this:

console.log(rid);
window.location = uri+'/helper.php';

In your success callback rid is 91 as it should be as per your comments and that is absolutely correct because at the php file you are trying to access a POST var.

But when this line executes window.location = uri+'/helper.php'; then location changes and it makes a GET request, so it fails.

To get this var at PHP end you should try with $_REQUEST('referens') and you have to send it with url like this:

window.location = uri+'/helper.php?referens=' + rid;

and at your php end:

<?php 
    $referens = $_REQUEST['referens']; // <---change here.
    echo $referens;
    echo 1;
?>

From the docs [ $_REQUEST() ]:

An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM