简体   繁体   中英

Send js variable to a php .ajax

I am trying to define id# of a choice and declaring it as variable send to "action.php", the file that connects to DB and inserts values. Div-block with 5 id's in HTML:

 <div class="rate">
 <div id="1" class="b-1 rate-btn"></div>
 <div id="2" class="b-2 rate-btn"></div>
 <div id="3" class="b-3 rate-btn"></div>
 <div id="4" class="b-4 rate-btn"></div>
 <div id="5" class="b-5 rate-btn"></div>
 </div>

anim.js intercepts the click event and declares the variable "therate" as clicked "id":

$('.rate-btn').click(function(){    
 var therate = $(this).attr('id');
$('.rate-btn').removeClass('rate-btn-active');
 for (var i = therate; i >= 0; i--) {
$('.b-'+i).addClass('rate-btn-active');
$.ajax({
 type : "POST",
 url  : "action.php",
 data : therate,
 success:function(){alert(therate)}
 });
 };
});

Second part of above code sends "therate" var to an "action.php". But unfortunately id doesn't=( success:function(){alert(therate)} shows me the id# on every choice no problem. "action.php" is in the same folder as "anim.js". I have also tried "/action.php" - no luck. The problem is anim.js does not send "therate" to "action.php". I'm sure this is really stupid and newbie problem but I don't recognize it=( Please, show me the problem! Thanks.

Knowing the php part of the script will help a lot. It is where you decide what data is returned to the client. Typically it goes something like this:

php

$therate = $_POST['therate'];
$response = array();
if(isset($therate)){
    $response['status'] = 'success';
    $response['therate'] = $therate;
} else {
    $response['status'] = 'failure';
    $response['message'] = 'Variable therate is not set.'
}

echo json_encode($response);

jQuery

$.ajax({
   type : "POST",
   url  : "action.php",
   data : {'therate': therate},
   success:function(data){
       var o = $.parseJSON(data);
       if(o.status == 'success'){
           alert(o.therate);
       } else {
           alert(o.message);
       }
   }
});

Notice the addition of adding a key identifier to the data we are sending to the server. This allows us to pull the post data serverside easily. Also notice the 'data' in the success function argument. This is the actual data returned from the server. Which you will notice below we can easily parse as json due to using json_encode to the array we passed back to the client.

I hope this helps! Let me know if you have any questions.

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