-3

It seems this should be a simple thing to do but something is still going wrong. I am using the code of the top answer on this page: jQuery Ajax POST example with PHP

When I submit the form, instead of passing that data to the upvote.php and having it edit the database accordingly, it redirects me to /upvote.php?bar=hfAb1he49kk. It is taking the data that I need & redirecting to the php page and adding the data the url. Why is it doing that?

PHP

<?php
// Create connection
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM videos ORDER BY votes DESC");
while($row = mysqli_fetch_array($result)) {
  echo "<div class='entry'>";
  $id = $row['id'];
  echo "<form action='upvote.php'>
          <input type='hidden' name='bar' id='bar' value='" . $id . "' />
          <input type='submit' value='upvote'/>
        </form>";
  echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/' . stripslashes($row['id']) . '" frameborder="0" allowfullscreen></iframe>';
  echo $row['votes'];
  echo "</div>";
}
?>

JQuery

<script>
var request;
// bind to the submit event of our form
$(form).submit(function(event){
if (request) {
    request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();

// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);

// fire off the request to /form.php
request = $.ajax({
    url: "/upvote.php",
    type: "post",
    data: serializedData
});

// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
    // log a message to the console
    console.log("Hooray, it worked!");
});

// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
    // log the error to the console
    console.error(
        "The following error occured: "+
        textStatus, errorThrown
    );
});

// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
    // reenable the inputs
    $inputs.prop("disabled", false);
});

// prevent default posting of form
event.preventDefault();
});
</script>

upvote.php

<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$bar = $_POST['bar'];
mysqli_query($con,"UPDATE videos SET votes = votes + 1 WHERE id = '" . $bar . "'");
mysqli_close($con);
?>
Community
  • 1
  • 1
user2407400
  • 213
  • 1
  • 5
  • 19
  • 3
    Please post your code, otherwise it is a guessing game. – Brandon White May 14 '14 at 19:12
  • 1
    You did remember to add `` tags to the the JS, right? Plus, using any related libraries in your `` should it be required. – Funk Forty Niner May 14 '14 at 19:13
  • 1
    You should probably move the `event.preventDefault()` to the top of the `.submit` function. If there is an error in javascript, it will stop the function and the form will submit as usual. – Jonathan Kuhn May 14 '14 at 19:15
  • You could also open developer tools and set the console to persist navigation. Then submit the form and look for any errors. – Jonathan Kuhn May 14 '14 at 19:17
  • You're using `
    ` and `url: "/upvote.php",` one is presuming that it's inside the same folder as your running your code(s), while the latter is looking for that same file in your root. Where are all your files located? (Together in the same folder?)
    – Funk Forty Niner May 14 '14 at 19:22

2 Answers2

0

maybe add

event.preventDefault();

to prevent the form action

$("#foo").submit(function(event){
            event.preventDefault();

Seb

Sebastien Horin
  • 10,803
  • 4
  • 52
  • 54
0
function postData(event){
event.preventDefault()
$.ajax({
    type: "POST",
    url: "yourfile.php",
    data: $('#myForm').serialize()
    }).done(function( result ) {
        // do something
    });
}

<form id="myForm">
<input type="submit" onclick="postData(event)" value="submit">

In a php file

$bar = $_POST['bar'];
$query = "UPDATE videos SET votes = votes + 1 WHERE id = '" . $bar . "'";
echo $query; //will echo you query to the done function of the ajax
exit();
mysqli_query($con,$query);
mysqli_close($con);
volkinc
  • 2,143
  • 1
  • 15
  • 19