简体   繁体   中英

How to POST with AJAX using just an a tag

I have an a tag that is dynamically generated with database content, it includes a data-target that I capture in javascript when it is clicked on, this is an example of one of the generated buttons:

<a href="#" data-target="edit/?id=1">Edit</a>

Simple, right?

Now, what I do in the JS when it is clicked, is as so:

var $this = $(this),
    $target = $this.data("target"),
    $endpointURL = "";

$endpointURL = $target.split("?id=")[0];

$id = $target.split("?id=")[1];

This allows me to set the endpoint I want, in out example above, it would be "edit" and also set the id which is just a number at this point.

Now, I have to POST this ID to the edit endpoint to return the right info, correct?

So, here is my AJAX for that:

$.ajax({
        type: "POST",
        data: '{"id": ' + $id + ' }',
        url: "../assets/scripts/php/" + $endpointURL,
        success: function (data) {
            $("#content-lockup").html(data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("error: " + textStatus + ", error thrown: " + errorThrown);
        }
    });

This does not throw an error and does indeed output a var dump of the $_POST array as I have set it to, however it doesnt contain my ID that I passed over, here is the code on the endpoint and a screenshot of the output:

<?php

var_dump($_POST);

?>

在此处输入图片说明

Why would the vardump on $_POST not contain the id that I passed over in the apparently successful AJAX request?

What I expect is that I can say on the endpoint, something like:

$id = $_POST['id'];

Maybe its something obvious that i'm doing wrong but yeah, any ideas?

it's because you are passing a string to data that isn't form encoded

Make it an object and jQuery will encode it for you

data: {"id": $id },

If it's a string it needs to be in format

data: 'id=' +id + '&someOtherParam=' + somevar

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