tfs
tfs

Reputation: 53

Using Ajax and JQuery to call PHP Script

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>

Upvotes: 0

Views: 70

Answers (1)

Woodrow
Woodrow

Reputation: 2832

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>

Upvotes: 1

Related Questions