每当按下提交按钮时,如何停止页面重新加载?

每当按下提交按钮时,如何停止页面重新加载?

问题描述:

I'm currently trying to create a system where users of my website can upvote/downvote things. Essentially, the way I'm going about this is by using the following html

<form method='post'>
<input type='submit' name='up' value='up'>
<input type='submit' name='down' value='down'>
</form>

Combined with this php:

<?php

if( isset($_POST['up']) ){

  $con = mysqli_connect("localhost","user","password");

  if (!$con)
  {
    die('Could not connect: ' . mysqli_connect_error());
  }

  $postid = "";
  $userid = $_SERVER['REMOTE_ADDR'];


  $query = "
  INSERT INTO database.table (postid, ipaddress, vote) VALUES ('$postid', '$userid', '+1')";

  mysqli_query($con, $query);

  mysqli_close($con);

  }

elseif( isset($_POST['down']) ){


  $con = mysqli_connect("localhost","user","password");

  if (!$con)
  {
    die('Could not connect: ' . mysqli_connect_error());
  }


  $postid = "";
  $userid = $_SERVER['REMOTE_ADDR'];


  $query = "
  INSERT INTO database.table (postid, ipaddress, vote) VALUES ('$postid', '$userid', '-1')";
  mysqli_query($con, $query);

  mysqli_close($con);
}

?>

This works to some extent. As I'd hoped, it keeps track of the current vote count. The problem I wish to tackle here is the fact that every time the up/down button is pressed - the page is reloaded. How can I prevent this from happening, and make this process more fluid?

Thanks in advance for any input.

I realize that you didn't mention jQuery anywhere in your question, but since you can not do what you are trying to do with pure HTML+PHP, I assume you will sooner or later resort to JS to achieve the effect. jQuery is perfect for this case:

HTML part

<a class="voter" data-vote="up">Vote up</a>
<a class="voter" data-vote="down">Vote down</a>

jQuery part (JSFiddle)

$(function(){

  $('.voter').click(function(e){
    e.preventDefault(); // prevent page reload
    var voteType = $(this).data('vote');
    $.post('/echo/json/', {
        voteType: voteType
    }, function(){
        alert('You have voted');
    });
  });

});

PHP part

$voteType = $_POST['voteType'];

switch($voteType){
    case 'up':
    // Do something
        break;
    case 'down':
    // Do something else
        break;
}