jQuery AJAX POST without form elements?

ajax, javascript, jquery

Solution

You're not passing anything along to your `saveAsNewName()` function in the onclick, you're just running the function. Therefore, `str` and `id` are null values.

How about something like this, where you get the values from the elements by ID:

function saveAsNewName() {
    var values = {
            'str': document.getElementById('elem1').value,
            'id': document.getElementById('elem2').value
    };
    $.ajax({
        url: "saveAsNewName.php",
        type: "POST",
        data: values,
    });

    ...

}

Obviously, there are innumerable other ways to get the values.

Also, you can POST to a URL regardless of HTML markup, a form being present, etc.

Edit: Seeing your comment about updating the `onclick` attribute dynamically, I recommend you do 2 things that will allow you to solve this problem on your own. These notes are for Chrome, but will work similarly in Firefox via Firebug.

1) Use the `console.log()` function on `values` to verify that you're sending the data to your function that you think you're sending. E.g. `console.log(values)`, then check the console in developer tools.

2) Open the developer tools and use the network tab to inspect the AJAX call. You can actually see the call happen in realtime and can inspect it to see what data was sent and what data was received.

Problem

I don't have a lot of experience with AJAX calls, but my example seems straightforward (except that I'm not using a element) and it makes me wonder if I'm doing the call wrong, or if you just can't do an AJAX POST without a form. My HTML for the button I'm using is this: ``` <button class="btn btn-primary btn-small" id='saveAsNewName' onclick=saveAsNewName()>Save As</button> ``` My JS: ``` function saveAsNewName(str, id) { var values = { 'str' : str, 'id' : id, }; $.ajax({ url: "saveAsNewName.php", type: "POST", data: values, dataType: 'JSON', success: function(data){ alert("success" + data); } }) .done(function(data) { alert("success" + data); }) .fail(function(data) { alert("failure" + data); }); } ``` And, for now, my php is simply this for testing if this works: ``` echo json_encode($_POST['id'])); ``` I'm getting the failure notice every time I click my button. Is there a specific workaround I need for not using a form, or am I mucking up the basic .ajax example? Edit, to be clear: I'm using another set of jQuery to continually update teh arguments for saveAsNewName(). The result is a call like: ``` onclick="saveAsNewName("wheyjuice 555", "33541")" ``` as a result from this jQuery code: ``` $(document).on('keyup',"[class*=editSimNameField]", function() { var newText = $(this).val(); var id = $(".loadWindow").val(); $("#saveAsNewName").attr('onclick', 'saveAsNewName(\"' + newText + '\", \"' + id + '\")'); }); ```

Original source