简体   繁体   中英

Not able to POST Variable to Another Page (PHP, Javascript, AJAX)

I have a while loop (inside the "searchvessel.php") that display the content of a query and have a button "upgrade" for each record of that query.

`while($fetch = $read->fetch_array()) {
?>
<tr>
<td id="1" style="display:none;"><?php echo $fetch['VesselID']?></td>
<td id="2"><?php echo $fetch['VesselName']?></td>       
<td><input type="submit" class="button" name=<?php echo $fetch['VesselID']; ?> value="Upgrade"/></td>
</tr>`

This "Upgrade" button when click will call to a Javascript code that use the value inside the tag name to pass to another page using AJAX.

<script type = "text/javascript">
        $('.button').click(function(){  
            alert($(this).attr('name'));
            $.ajax({
                type: "POST",
                data: {
                    name: $(this).attr('name')
                },
                url: "vesselrecord.php",
                dataType: "json",
                async: true,
                beforeSend: function(){
                    $(".ajaxTest").text("Trying to upgrade...");
                },
                complete: function(){
                    window.location.href = "vesselrecord.php";
                 },
                success: function(data) {
                    $(".ajaxTest").text(data.a);
                    if (data.b == "true") {
                        location.reload();
                    }
                }
            });             
        });
</script>
  1. I were able to prompt/alert the value of vessel identification using the "alert($(this).attr('name'));" then
  2. Move/Transfer to the "vesselrecord.php
  3. But inside the "vesselrecord.php" there is no value in the $_POST['name']. Looks like there is an issue on my ajax code. Can you guide me on this? TIA.

Below is my code inside the "vesselrecord.php"

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $vessel_id = strip_tags($_POST['name']);            
}

When you change the location of the window, you make a $get request not $post, that is why you are not getting any value $_POST['name'] .

You can change the location from-

window.location.href = "vesselrecord.php"

to-

window.location.href = "vesselrecord.php?myquerystringdata=" + $(this).attr("name");

and then on you php file you can write code to get value from query string.

'name' is nested within 'data'. Maybe you need to access data.name? I'm more used to JS than PHP so I'm not sure how to express this. Hope this helps.

  data:{
    name:'Al'
  }

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