简体   繁体   中英

jQuery AJAX with PHP to upload contents to MYSQL DB

I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.

Here is my jQuery function "store"

<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
  url: 'http://www.exampledomain.com/folder/store.php',
  type: 'POST',
  data: 'ud='+ud+'&ld='+ld+'&tp='+tp
  success  : function() {
        alert("WORKED!");
  },
  error    : function() {
        alert("DIDN'T WORK!");
  },
  complete : function() {
  }
  });
}
</script>

Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)

<?php

require ('../mysqli_connect.php');

$errors = 0;

if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
    $ud = $_POST['ud'];
} else {
    ++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
    $ld = $_POST['ld'];
} else {
    ++$errors;
}
if(isset($_POST['tp'])) {
    $tp = strip_tags(stripslashes($_POST['tp']));
} else {
    ++$errors;
}

if($errors == 0) {

    $q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')"; 
    mysqli_query($mysqli, $q);

} else {

echo 'There was a problem!';

}
?>

Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!

<-- EDIT -->

New jQuery & AJAX Script ...

<script type="text/javascript">

function store(ud, ld, tp) {
   $.ajax({
      url: 'http://www.exampledomain.com/folder/store.php',
      type: 'POST',
      data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
          error    : function() {
            alert("error");
      },
      success  : function(data) {
            alert(data);
      },
      complete : function() {
            alert("complete");

      }
   });
}

$(function () {
  $("a.rec").on("click", function () {
    var $this = $(this),
        ud = $this.data("ud"),
        ld = $this.data("ld"),
        tp = $this.data("tp");

    store(ud, ld, tp); 
  });
});

</script>

Revised PHP

<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){

require ('../mysqli_connect.php');

$errors = 0;

if(isset($_POST['ud'])) {
    $ud = $_POST['ud'];
} else {
    ++$errors;
}
if(isset($_POST['ld'])) {
    $ld = $_POST['ld'];
} else {
    ++$errors;
}
if(isset($_POST['tp'])) {
    $tp = $_POST['tp'];
} else {
    ++$errors;
}

if($errors == 0) {

    $q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";     
    mysqli_query($mysqli, $q);

} else {

    echo 'There was a problem!';

}

} else {

    $url = 'http://www.exampledomain.com/error.php';
    ob_end_clean();
    header("Location: $url");
    exit();

}
?>

Now for my HTML

<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>

However, when this button is clicked, it still does not do anything!

As you said onclick is something you are going to want to avoid. This is how you do it.

$(function () { //This function will be ran when the page loads
  $(".button-class").on("click", function () { //This will run when any button is clicked
    var $this = $(this),
        ud = $this.data("ud"),
        ld = $this.data("ld"),
        tp = $this.data("tp");

    store(ud, ld, tp); 
  });
});

HTML

<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>

I find it easier to use JSON and pass variables in an object to the server:

<script>
    (function(){

        var store = function (ud, lrid, type) {

            var data = {
                        ud:ud,
                        lrid:lrid,
                        type:type
                };

            $.ajax({
              url: 'http://www.exampledomain.com/folder/store.php',
              type: 'POST',
              data: data,
              success  : function(data) {
                    alert(data);
              },
              error    : function() {
                    alert("DIDN'T WORK!");
              },
              complete : function() {
              }
              });
         };


        $('#btn').on('click', function(){

            store(1,2,3);

        });

    }());
    </script>

Use this script to test you are getting the variables on the server side:

<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
    if(
        isset($_POST['ud']) &&
        isset($_POST['lrid']) &&
        isset($_POST['type']) 
    )
    {
        $var = $_POST['ud'] . ", ".$_POST['ud']  . ", ".$_POST['type'] ." passed successfully via ajax!";
        echo json_encode($var);
    }

}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM