Mayzed
Mayzed

Reputation: 75

Submit form with POST/GET using AJAX

At present I have a like/dislike function on my website, which submits SQL to a database on POST, and uses GET to retrieve the product ID and the product category, so after clicking like it currently refreshes and the link appears as:

"/index.php?id=106&category=Entertainment"

I've been looking at AJAX and figured out how to use it to submit SQL to the database without having to refresh, but I can not get it to submit when I need to submit GET variables too. I'm wondering if anyone knows anything about this as I've been trying everything and haven't been successful. Currently the code for this function looks like the following:

Index.html:

<form class="form-horizontal" action="?id=' . $productData->getID() . '&category=' . $productData->getPcategory() . '" method="post">
           <button id="like" type="submit" name="like" value="like" class="btn btn-success" onclick="javascript:return like();"><i class="glyphicon glyphicon-thumbs-up"></i></button>

</form>

Index.php:

if (isset($_POST["like"])) {
    $productDataSet = new productDataSet();
    $productDataSet->addLike();
    $likeDislike = "Product has been added to your <b>likes</b>.";
}

AJAX Function (works in other areas of my website where there are no GET variables needed):

function like()
{
$.ajax({
    url: "index.php",
    context: document.body
    }).done(function() {

    });
    return false;
}

I know I need to add this code in order for the script to be able to read the GET variables on POST but I don't know what to add, any help would be greatly appreciated.

Thanks.

Upvotes: 1

Views: 421

Answers (2)

Beevee
Beevee

Reputation: 198

Generally this is quite a simple task, all you need is to configure an event handler, assuming you're using jQuery (Which you appear to be) the following should do for your javascript:

$(document).on('click', 'a[data-ajax-submission]', function(e)
{
    var link = $(this);
    var action = link.attr('data-ajax-action');
    var id = link.attr('data-resource-id');

    if(action == undefined || id == undefined)
    {
        return;
    }

    e.preventDefault();

    $.ajax({
        url: yourUrl, // Will need to set, could also use a data attribute again
        type: 'POST',
        data: {
            action: action,
            id: id
        },
        dataType: 'json',
        context: document.body
    }).always(function(response)
    {
        // Do stuff here
    })
});

This will cause clicking any element with a data-ajax-submission attribute to trigger this event.

We then take an action, and an id from the other data attributes and send them to the sever as POST data in the ajax request, usage example below:

<a data-ajax-submission data-ajax-action="resource-like" data-resource-id="1">Like</a>

I have used the term "resource" as a placeholder, this could be "product" "category" whatever.

Then in PHP you can just handle it like any other form request:

if(isset($_POST['action']) && $_POST['action'] == 'resource-like')
{
    // Check for an ID & any other validation
    // Persist, do stuff, etc...

    die(json_encode(array(
         'success' => $success
    )));

}

This is a flexible solution, and should allow you to perform several tasks without having to further modify the JavaScript aspect.

It's worth noting, that typically for like, dislike, vote etc... behavior, you will need to limit the voting to one per visitor, usually achieved by setting a cookie.

Let me know if you have any follow up questions etc...

Upvotes: 1

Jeremy Thille
Jeremy Thille

Reputation: 26370

I'm not sure I understand the problem, but if you want to submit GET and POST variables at the same time, you can try this dirty trick :

$.post( "someFile.php?var1=value1&var2=value2", {
     var3 : value3 ,
     var4 : value4 })

In PHP, read :

$_GET['var1']
$_GET['var2']
$_POST['var3']
$_POST['var4']

Upvotes: 0

Related Questions