0

I am currently trying to send form data to a PHPMyAdmin MySQL server. Without Ajax, everything works on a web server, but the problem is that the webpage is redirected. Here is the jquery script, which refers to the insert.php script. I am not sure what to input for data, because form.serialize() throws an error.

$.ajax({
        url: "insert.php",
        type: "post",
        data: form.serialize() ,
        success: function (response) {

        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }

What do I need to add? I am a beginner with Ajax. Here is the PHP script:

<?php
    $con = mysqli_connect('localhost','tejsingh_tej','password');
    if(!$con){
        echo 'Not Connected to Server';
    }

    if (!mysqli_select_db($con,'tejsingh_bhs2018')){
            echo 'Not Selected';
    }

    $Player = $_POST['player'];
    $Quarter = $_POST['quarter'];
    $Time = $_POST['time'];
    $Where = $_POST['where'];
    $Notes = $_POST['notes'];
    $What = $_POST['what'];

    $sql = "INSERT INTO game1 (player,quarter,time1,where1,notes,what) VALUES ('$Player', '$Quarter', '$Time', '$Where','$Notes','$What')";
    if(!mysqli_query($con,$sql)){
        echo'Not Inserted';
    }
    else{
        echo 'Inserted';
    }

    header('refresh:2; url=index.html');


?>

Let me know if you need more info. Thanks!

EDIT: Rest of Code

<!DOCTYPE html>
<html>
<head>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
</style>

</head>
<body>

  <img id = 'pool' src="wapo.png" height="322" width="592">
  <form name="game" action="insert.php" method="post" target="_blank">
  <p> <select id="er" name = 'player'>
    <option value="dy">r</option>
    <option value="d">n</option>
    <option value="ex">on</option>
    <option value="per">per</option>
    <option value="tt">t r</option>
    <option value="jon">He</option>
    <option value="jk">Jk</option>

  </select>
  <select id="what" name = 'what'>
    <option value="shoton">Shot on Cage</option>
    <option value="shotoff">Shot off Cage</option>
    <option value="goal">Goal</option>
    <option value="countergoal">Goal on Counter</option>
    <option value="countershot">Shot on Counter</option>
    <option value="assist">Assist</option>
    <option value="block">Block</option>
    <option value="steal">Steal</option>
    <option value="turnover">Turnover</option>
    <option value="drawn">Ejection Drawn</option>
    <option value="ejected">Ejected</option>
  </select>
  <select id="where" name = 'where'>
    <option value="set">Set</option>
    <option value="navy">Navy</option>
    <option value="leftwing">1/2 side past 5</option>
    <option value="rightwing">4/5 side past 5</option>
    <option value="point">Point/3</option>
    <option value="lefttwo">1/2 side 2 meter</option>
    <option value="righttwo">4/5 side 2 meter</option>
    <option value="1">6 on 5 1</option>
    <option value="2">6 on 5 2</option>
    <option value="3">6 on 5 3</option>
    <option value="4">6 on 5 4</option>
    <option value="5">6 on 5 5</option>
    <option value="6">6 on 5 6</option>
  </select>
  <select id="quarter" name = 'quarter'>
    <option value="q1">Quarter 1</option>
    <option value="q2">Quarter 2</option>
    <option value="q3">Quarter 3</option>
    <option value="q4">Quarter 4</option>
  </select>
    <select id="time" name = 'time'>
    <option value="0:30">0:30</option>
    <option value="1:00">1:00</option>
    <option value="1:30">1:30</option>
    <option value="2:00">2:00</option>
    <option value="2:30">2:30</option>
    <option value="3:00">3:00</option>
    <option value="3:30">3:30</option>
    <option value="4:00">4:00</option>
    <option value="4:30">4:30</option>
    <option value="5:00">5:00</option>
    <option value="5:30">5:30</option>
    <option value="6:00">6:00</option>
    <option value="6:30">6:30</option>
    <option value="7:00">7:00</option>
  </select>

  Notes: <input type="text" id = 'notes' name = 'notes'>

 <button type="button" onclick="save()" name = 'form'> Save </button> 
<!---<input type="submit" name="submit">-->
</p>
</form>
  <p> Log </p>
  <table id='log'>
  <tr>

    <th>Player</th>
    <th>Action</th>
    <th>Location</th>
    <th>Quarter</th>
    <th>Time</th>
    <th>Notes</th>

  </tr>
</table>

<script>

function save() {

  var a = document.getElementById("player");
  value = a.options[a.selectedIndex].value;
  console.log(value);
  var b = document.getElementById("what");
  value1 = b.options[b.selectedIndex].value;
  console.log(value1);
  var c = document.getElementById("where");
  value2 = c.options[c.selectedIndex].value;
  console.log(value2);
  var d = document.getElementById("quarter");
  value3 = d.options[d.selectedIndex].value;
  console.log(value3)
  var e = document.getElementById("time");
  value4 =e.options[e.selectedIndex].value;
  console.log(value4)
  var f = document.getElementById("notes");
  value5 = f.value;
  console.log(value5)
  var table = document.getElementById("log");
  var row = table.insertRow(1);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  var cell4 = row.insertCell(3);
  var cell5 = row.insertCell(4);
  var cell6 = row.insertCell(5);

  cell1.innerHTML = value;
  cell2.innerHTML = value1;
  cell3.innerHTML = value2;
  cell4.innerHTML = value3;
  cell5.innerHTML = value4;
  cell6.innerHTML = value5;


  $.ajax({
        url: "insert.php",
        type: "post",
        data: form.serialize() ,
        success: function (response) {
           // you will get response from your php page (what you echo or print)                 

        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }


    });

  if(value2 == 'leftwing'){
      document.getElementById('pool').src='onetwofive.png'
  } else if (value2 == 'set'){
      document.getElementById('pool').src='set.png'
  } else if (value2 == 'point'){
      document.getElementById('pool').src='point.png'
  } else if (value2 == 'rightwing'){
      document.getElementById('pool').src='fourfivefive.png'
  } else if (value2 == 'lefttwo'){
      document.getElementById('pool').src='onetwotwo.png'
  } else if (value2 == 'righttwo'){
      document.getElementById('pool').src='fourfivetwo.png'
  } else {
      document.getElementById('pool').src='wapo.png'
  }

}
</script>
</body>
</html>
tfs
  • 53
  • 7
  • 1
    What's the error from `form.serialize()`? – Rory McCrossan Jul 27 '18 at 19:16
  • 1
    You need to preventDefault the submit event and return something from the php, not send a refresh header. Remove the header and console.log the response. Also show us the event handler you use to send the Ajax request – mplungjan Jul 27 '18 at 19:19
  • http://stackoverflow.com/a/20150474/2191572 – MonkeyZeus Jul 27 '18 at 19:22
  • 3
    `form` is undefined right? Define it or pass the following to data `$("form").serialize()` – Simon K Jul 27 '18 at 19:27
  • @RoryMcCrossan I get an undefined error. – tfs Jul 27 '18 at 19:31
  • So where are you attempting to define it? It's just common sense that we need to see that code at this point... – Rory McCrossan Jul 27 '18 at 19:32
  • @RoryMcCrossan Sorry. I posted the entire html doc. As you can see, I attempt to define" form" in the button that submits the form. – tfs Jul 27 '18 at 19:39
  • @mplungjan I'm sorry, I'm not sure I completely understand. What do you mean by remove the header and console.log the response. Which header? Also, what do you mean by event handler? – tfs Jul 27 '18 at 19:41
  • You're getting an undefined error because you're using the variable `form` even though you don't have a line declaring it (`var form = $("form");`). – dokgu Jul 27 '18 at 20:27
  • @uom-pgregorio I changed it to this.serialize and it works fine. It tells me the data has been inserted. However, when I look at the phpmyadmin database, nothing shows up but empty rows. It also gives me this error: Warning: log() expects parameter 1 to be double, string given in /home4/tejsingh/public_html/insert.php on line 25
    .
    – tfs Jul 27 '18 at 20:30

1 Answers1

1

The main issue is you are attempting to use form.serialize() for the data in the Ajax request. form doesn't point to anything and is undefined. You need to point/assign the form declaration to a DOM element using an identifier (id). So add id="game" to your open form tag. Then you can do the following using Jquery.

jQuery:

var form = $('#game');

Then you can do:

form.serializeArray() for the data part of your Ajax request, to ensure you send the data over as $_POST variables.

If you're using jQuery and want to do an Ajax request from same page, please try out the snippet below, with the following code that will allow you to click the submit button without re-routing to a page for processing. You can still use a submit button instead of just a button if you want.

$(document).ready(function() {

  $('form').on('submit', function(e) {
    e.preventDefault();
    save();
  });

});

A few other issues/tips that were identified looking at your code:

  • Remove target="_blank" from your opening form tag, this isn't needed
  • Your first select id is incorrect and will result in a JS runtime error. The id needs to be player so your JS code can reference it properly.
  • You are using ' and " interchangeably within your HTML tags. Please stick to using one or the other. In HTML the use of single quotes (') and double quotes (") are interchangeable, there is no difference. But consistency is recommended, therefore we must pick a syntax convention and use it regularly.

function save() {

  var a = document.getElementById("player");
  value = a.options[a.selectedIndex].value;
  console.log(value);
  var b = document.getElementById("what");
  value1 = b.options[b.selectedIndex].value;
  console.log(value1);
  var c = document.getElementById("where");
  value2 = c.options[c.selectedIndex].value;
  console.log(value2);
  var d = document.getElementById("quarter");
  value3 = d.options[d.selectedIndex].value;
  console.log(value3)
  var e = document.getElementById("time");
  value4 = e.options[e.selectedIndex].value;
  console.log(value4)
  var f = document.getElementById("notes");
  value5 = f.value;
  console.log(value5)
  var table = document.getElementById("log");
  var row = table.insertRow(1);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);
  var cell4 = row.insertCell(3);
  var cell5 = row.insertCell(4);
  var cell6 = row.insertCell(5);

  cell1.innerHTML = value;
  cell2.innerHTML = value1;
  cell3.innerHTML = value2;
  cell4.innerHTML = value3;
  cell5.innerHTML = value4;
  cell6.innerHTML = value5;

  $.ajax({
    url: 'insert.php',
    type: 'POST',
    data: $('#game').serializeArray(),
    success: function(response) {

    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.log(textStatus, errorThrown);
    }
  });

  if (value2 == 'leftwing') {
    document.getElementById('pool').src = 'onetwofive.png'
  } else if (value2 == 'set') {
    document.getElementById('pool').src = 'set.png'
  } else if (value2 == 'point') {
    document.getElementById('pool').src = 'point.png'
  } else if (value2 == 'rightwing') {
    document.getElementById('pool').src = 'fourfivefive.png'
  } else if (value2 == 'lefttwo') {
    document.getElementById('pool').src = 'onetwotwo.png'
  } else if (value2 == 'righttwo') {
    document.getElementById('pool').src = 'fourfivetwo.png'
  } else {
    document.getElementById('pool').src = 'wapo.png'
  }

}

$(document).ready(function() {

  $('form').on('submit', function(e) {
    e.preventDefault();
    save();
  });

});
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
<!DOCTYPE html>
<html>

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

<body>
  <img id="pool" src="wapo.png" height="322" width="592">
  <form name="game" id="game">
    <p>
      <select id="player" name="player">
        <option value="dy">r</option>
        <option value="d">n</option>
        <option value="ex">on</option>
        <option value="per">per</option>
        <option value="tt">t r</option>
        <option value="jon">He</option>
        <option value="jk">Jk</option>
      </select>
      <select id="what" name="what">
        <option value="shoton">Shot on Cage</option>
        <option value="shotoff">Shot off Cage</option>
        <option value="goal">Goal</option>
        <option value="countergoal">Goal on Counter</option>
        <option value="countershot">Shot on Counter</option>
        <option value="assist">Assist</option>
        <option value="block">Block</option>
        <option value="steal">Steal</option>
        <option value="turnover">Turnover</option>
        <option value="drawn">Ejection Drawn</option>
        <option value="ejected">Ejected</option>
      </select>
      <select id="where" name="where">
        <option value="set">Set</option>
        <option value="navy">Navy</option>
        <option value="leftwing">1/2 side past 5</option>
        <option value="rightwing">4/5 side past 5</option>
        <option value="point">Point/3</option>
        <option value="lefttwo">1/2 side 2 meter</option>
        <option value="righttwo">4/5 side 2 meter</option>
        <option value="1">6 on 5 1</option>
        <option value="2">6 on 5 2</option>
        <option value="3">6 on 5 3</option>
        <option value="4">6 on 5 4</option>
        <option value="5">6 on 5 5</option>
        <option value="6">6 on 5 6</option>
      </select>
      <select id="quarter" name="quarter">
        <option value="q1">Quarter 1</option>
        <option value="q2">Quarter 2</option>
        <option value="q3">Quarter 3</option>
        <option value="q4">Quarter 4</option>
      </select>
      <select id="time" name="time">
        <option value="0:30">0:30</option>
        <option value="1:00">1:00</option>
        <option value="1:30">1:30</option>
        <option value="2:00">2:00</option>
        <option value="2:30">2:30</option>
        <option value="3:00">3:00</option>
        <option value="3:30">3:30</option>
        <option value="4:00">4:00</option>
        <option value="4:30">4:30</option>
        <option value="5:00">5:00</option>
        <option value="5:30">5:30</option>
        <option value="6:00">6:00</option>
        <option value="6:30">6:30</option>
        <option value="7:00">7:00</option>
      </select>
      Notes: <input type="text" id="notes" name="notes" />
      <input type="submit" name="save" value="Save" />
    </p>
  </form>
  <p> Log </p>
  <table id="log">
    <tr>
      <th>Player</th>
      <th>Action</th>
      <th>Location</th>
      <th>Quarter</th>
      <th>Time</th>
      <th>Notes</th>
    </tr>
  </table>
</body>

</html>
Woodrow
  • 2,740
  • 1
  • 14
  • 18