0
<button id='0' value="23" name='process'>Click 0</button>
<button id='1' value="45" name='process'>Click 1</button>
<button id='2' value="66" name='process'>Click 2</button>
<button id='3' value="88" name='process'>Click 3</button>
<button id='4' value="92" name='process'>Click 4</button>

$('#id').click(function(){
    $.ajax({
      url: "test.php",
      data: {0:123},
      processData: false,
      contentType: 'application/json'
    });
});

I'm not very familiar with ajax but I want to use it to avoid reloading the page which is currently what is happening with the php I'm using. I need to send the data through ajax upon clicking one of the buttons. Each button needs to send a unique key (the id) and also a simple numeric value.

Not sure how this is done with Ajax exactly with respect to sending through unique pieces of information per click and how to trigger different results for different buttons.

Serge K.
  • 5,303
  • 1
  • 20
  • 27
Hasen
  • 11,710
  • 23
  • 77
  • 135
  • 4
    `$('#id')` isn't going to find any matching elements, because nothing has that `id`. But `$('button[name="process"]')` will find your buttons. – David Oct 03 '17 at 12:59

3 Answers3

6

Try something like this:

<button data-id='0' value="23" name='process'>Click 0</button>
<button data-id='1' value="45" name='process'>Click 1</button>
<button data-id='2' value="66" name='process'>Click 2</button>
<button data-id='3' value="88" name='process'>Click 3</button>
<button data-id='4' value="92" name='process'>Click 4</button>

$('button').on("click", function() {
    $btn = $(this),
    id = $btn.data("id"),
    value = $btn.val();

    $.ajax({
      url: "test.php",
      data: {
          id: id,
          value: value
      },
      processData: false,
      contentType: 'application/json',
      success: function(data) {
          console.log('Request successfull!', data);
      }
    });
});
  1. $('button').on("click" this will set the event to all buttons. Use on() instead of click(). You can also set a class for those buttons and select them by it, in case you have other buttons in your document that doens't have to perform this action;

  2. Use data- attributes to store any custom data into your elements, don't use default or unexistent attributes for that. Then you can get them with data();

  3. Send them to as an object in the ajax request as made in data parameter.

  4. Add success, error or complete callbacks to get the result of your request as soon it finishes.

Update: Final Ajax request

$.ajax({
    type: "post",
    url: "test.php",
    data: {
        id: id,
        value: value
    },
    processData: false,
    success: function(data) {
        console.log('Request successfull!', data);
    }
});
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
  • 1
    also add here success function if @hasen want to do something in a response – Dhaval Purohit Oct 03 '17 at 13:01
  • @DhavalPurohit sure! Nice catch! – DontVoteMeDown Oct 03 '17 at 13:03
  • This looks good but for some reason the ID and VALUE aren't going through? Other than that it is going through ok and taking action in the php file, also it triggers the console log message. They have null values even if I manually change them to numbers instead of variables - any ideas? I'm getting the values in php with $_POST['value'] and $_POST['id']; Also btw for completeness your code has non matching quotes in the console log send. – Hasen Oct 03 '17 at 14:44
  • @Hasen [check this out](https://stackoverflow.com/a/20295138/1267304). I suggest you to remove it and send the default way. – DontVoteMeDown Oct 03 '17 at 14:50
  • @DontVoteMeDown Yes it needs to be type: 'post' and not json. That's why it wasn't working. – Hasen Oct 04 '17 at 13:03
  • @Hasen check the update. Is that what you have done? – DontVoteMeDown Oct 04 '17 at 13:38
1

See the code below. I've commented out the ajax call so that you can see the console log without error. Uncomment it when you use it and remove the console.log() if you do not need it.

$('button').on('click', function(){
  
  // First we get the values from the button that's clicked
  var val1 = $(this).attr('id');
  var val2 = $(this).val();
  
  //We then convert the values into JSON format
  var data = {"id":val1, "val":val2};
  
   console.log(data);

  //$.ajax({    
    //url: "test.php",
    //data: data,
    //dataType: "json",
    //processData: false,
    //contentType: 'application/json'
  //});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='0' value="23" name='process'>Click 0</button>
<button id='1' value="45" name='process'>Click 1</button>
<button id='2' value="66" name='process'>Click 2</button>
<button id='3' value="88" name='process'>Click 3</button>
<button id='4' value="92" name='process'>Click 4</button>
ProEvilz
  • 5,310
  • 9
  • 44
  • 74
  • Why are you being so pedantic? It's a figure of speech. – ProEvilz Oct 03 '17 at 13:04
  • I am being pedantic because you have not told the OP what you've done. An explanation *always* adds value to the answer. If you add one you'll get upvotes because code only answers are generally not a good thing on Stack Overflow. – Jay Blanchard Oct 03 '17 at 13:06
  • I found answers by yourself that aren't explained to the level that you preach. Append your comments with 'do as I say, not as I do' as that is appropriate. – ProEvilz Oct 03 '17 at 13:06
  • That's true, I have not explained well in the past. If I were to go back and edit those answers it would take a while. But I've learned that we should consider ourselves to be teachers when we answer and my more recent answers reflect that. – Jay Blanchard Oct 03 '17 at 13:07
  • @JayBlanchard I've added code comments for an explanation. – ProEvilz Oct 03 '17 at 13:08
  • I'm having trouble getting the data value to go through with these answers. Can you confirm what the command in php would be to get the values in your code? Is it $_POST['data'] or $_POST['id'] or what? – Hasen Oct 03 '17 at 15:06
  • @Hasen You don't need PHP. PHP isn't involved in any of these answers. The data comes from clicking the button... it's extracts the data from which ever button you click – ProEvilz Oct 03 '17 at 15:12
  • `var val1 = $(this).attr('id'); ` gets the `id=""` value on the button and `var val2 = $(this).val();` gets the `value=""` from the button. – ProEvilz Oct 03 '17 at 15:14
  • Well the question was about submitting to a php file so yes php would have to be involved...? – Hasen Oct 03 '17 at 16:46
  • @Hasen I see your point, but this is in regards to sending it *to* the PHP file. There is no PHP involved in sending to PHP... – ProEvilz Oct 03 '17 at 23:03
  • Haha but ironically your code doesn't send it to php either though. Sending also needs a receiver otherwise its just a ship in a bottle. Anyway yours was the code I used in the end although it needed to be type: 'post' to work. – Hasen Oct 04 '17 at 13:05
  • @Hasen If it's not sending it to PHP, then where is it sending it? You are right about send & receive. This is what I was trying to explain... your post here isn't a problem with the receiving part, it is a problem with the *sending* part, which is the AJAX. To which you hten said you have a problem getting the data to *go through* to the PHP. But anyhow, glad you got it sorted. – ProEvilz Oct 04 '17 at 13:35
  • Check your code, it just sends to the console log, anyway that was kind of a joke. Regarding the sending to php you're just being pedantic, sending also requires receiving to function in code otherwise the sending never had any point in the first place. – Hasen Oct 06 '17 at 02:24
0
    <button id='23' class='process' name='process'>Click 0</button>
    <button id='45' class='process'  name='process'>Click 1</button>
    <button id='66' class='process'  name='process'>Click 2</button>
    <button id='88' class='process' name='process'>Click 3</button>
    <button id='92' class='process'  name='process'>Click 4</button>

    $('.process').click(function(){
        var uniqueVal = $(this).attr('id');
        $.ajax({
          url: "test.php",
          data: {'inputName':uniqueVal},
          type: 'POST',
           contentType: 'application/json; charset=utf-8',
          success: function (response) {
            //do what ever you want here
        },
        error: function () {
            alert("error");
        }

        });
    });

   In test.php

    <?php
       //access as follows
        echo $_POST['inputName'];

    ?>
K.B
  • 885
  • 5
  • 10
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. A ***good answer*** will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO. – Jay Blanchard Oct 03 '17 at 13:04