user2509237
user2509237

Reputation: 39

onClick add to database

I have the below code, and I'm not sure if it even works. Basically, I want to do a like system, whereby when I click on the link, it adds a +1 to the user's likes.

I've tried so hard to read up but I just don't get anything, and I found a code similar below.

When I clicked on the link, it does process my insert.php page, but I don't know how to get the variable values...

What should I do? I'm not sure if the code structure below is correct...

Thanks!

<script>
function insertSalary()
{
    var salary = $("#salary").val();
    $.post('insert.php', {salary: salary}, function(data) 
    {
        $("#current-salary").html(data); 
    });
}
</script>

<div id="current-salary">
<a id="salary" onClick="insertSalary();">+1</a>
</div>

Upvotes: 0

Views: 2698

Answers (2)

Sean Cox
Sean Cox

Reputation: 782

While this may work, I would recommend separating your logic from your website by putting the javascript in an external file and then link your HTML page to it.

I would also advise against declarative event binding which you have done by specifying
onClick="insertSalary()".
jQuery provides a method to pro-grammatically assign functions to events using the on method.
So for your code, you could use:

$('#current-salary').on('click', insertSalary());

Upvotes: 1

Daniel Nill
Daniel Nill

Reputation: 5747

The variable will be in your php script as $_POST['salary']

The value of salary is passed as part of the post method in jquery.

So you can do:

$.post('script.php', {salary: 100}, function(data){...});

and this will pass the value 100 to your php script as the salary value.

In php the $_POST and $_GET hashes contain the data that you pass with a given request. In jquery $.post, $.get $.ajax create requests and take data hashes to build the data you want to pass with the request.

Upvotes: 1

Related Questions