Search code examples
phpjquerymysqlajaxhttp-request

Send data to php page from button and post results


Ok. The problem is I am working on a website that you can easily up-vote or down-vote a certain image/video etc. Now the thing that came up was SENDING the request. I can process most php things and so on so forth, I can also do database requests; but, how do I send a request to my php page? I want it to send from the main page and it will do it without refreshing the page. Also, I tried adding it to a "form", the user clicks the button and it submits, but I need a "id" variable added WITH the request. Now, I know I will need some jquery and Ajax, but I have NO CLUE were to start on that. Here is what I have for my first page:

<form action="vote.php">
<input type="image" src="imgs/1.png" name="1" alt="<?php echo $sub; ?>" />
<input type="image" src="imgs/2.png" name="2" alt="NOT" />
<input type="text" value="<?php echo $id; ?>" name="id" hidden />
</form>

Now, the vote page:

<?php

require_once('inc/dbConnect.php');

if (empty($id)) {
  $error = "Which photo to vote?"
}

// Receive vote count, is it UP or DOWN?
// save in variable
// do a check and add it to database, <- I can do this part.  
?>

Solution

  • HTML:

    <form action="vote.php">
    <button type="button" name="vote" value="up">Upvote</button>
    <button type="button" name="vote" value="down">Downvote</button>
    <input type="hidden" name="image" value="filename_or_unique_id_of_img.jpg">
    </form>
    

    jQuery:

    form.find('button').on('click',function(){
      var form,url,data;    
          form = $('form');
          url = form.attr('action');
          data = 'voted='+$(this).val()+'&image='+image;
    
      $.ajax({
        url:url,
        data:data,
        type:'POST',
        success:function(data){
          alert(data) //'Thanks for voting!'
        }
      })
    
    })
    

    PHP:

    $vote = $_POST['vote'];
    $image = $_POST['image'];
    //stuff with database
    echo 'Thanks for voting!';