0

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!

3
  • Use prepared query's Commented Nov 12, 2013 at 22:05
  • Minor typo may be the third parameter of your store function; you have type but use tp in the query. Try checking that the data is going through as expected by simply dumping the data in your PHP script and checking it. Then, make sure the query is being called at all. Check to make sure that mysqli_query() is not returning an error since you have no error checks on it. Commented Nov 12, 2013 at 22:06
  • @Demonslay335 thank you for the heads up! I forgot to change over the name of the variables being passed through as I was going through my code to make it more general (I thought that'd help) Commented Nov 12, 2013 at 22:34

2 Answers 2

1

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"/>
Sign up to request clarification or add additional context in comments.

14 Comments

This seems nice and simple. Regarding the values that will be passed to the store function, there will be multiple buttons with varying values, so what is the best way of retrieving such values with function()? Also, all the buttons should have the same ID, correct (as to not have to create multiple functions to retrieve the information)?
So there are multiple buttons? And the data is different for every button? In that case you don't want to use IDs, an ID is unique. You'll want to use a class and all the buttons should have this class. The data is also a little tricky, you could store the data using jQuery.data. I'll update my answer to reflect multiple buttons
Indeed there are multiple buttons with varying information that is set via PHP. I was looking at the answer before/below yours and he mentioned a way of passing information... My issue now is how to retrieve such information! I am not very familiar with jQuery but do I just add "data" attributes to each button?
jQuery has a function called attr which can retrieve the value of any attribute on an element. I would suggest having three attributes on each button with the values. I'll update my answer.
Thank you for all the help, this seems like it could solve all my issues! I will respond later on when I have actually implemented my own variant of the code...
|
0

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);
    }

}
?>

2 Comments

I appreciate the answer, I will look through some JSON documentation to attempt to implement it properly
I forgot to add the dataType : "json" attribute after data in the $.ajax. So, this isn't really JSON at all and the json_encode isn't required in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.