2014-06-18 109 views
0

我想從JS發佈/獲取一些變量(值)到example.com/sentdata.php,並將它們用作php變量。POST(或GET)JavaScript(jQuery)變量值爲php

我試圖從堆棧實現一些技術,但我失敗了。

HTML:

<label for="szt-n">Ilość sztuk: </label><input type="number" name="name1" value="0" id="zz" class="quantity s in-sel" /><p id="niebieskie">Cena: <span></span></p> 
<label for="szt-r">Ilość sztuk: </label><input type="number" id="xx" name="name2" value="0" class="quantity m in-sel" /><p id="rozowe">Cena: <span></span></p> 
<p id="total">Koszt całkowity: <span></span></p> 

JS:

$(document).ready(function() { 
    $('.quantity').bind('click keyup', function(event) { 

      var qs= +$("#zz").val(); 
      var qm= +$("#xx").val(); 

     var price = 2; 
     var total = (qs + qm) * price; 
     var niebieskie = qs * price; 
     var rozowe = qm * price; 
     total = total + ' PLN'; 
     niebieskie = niebieskie + ' PLN'; 
     rozowe = rozowe + ' PLN'; 

      $("#niebieskie span").html(niebieskie); 
      $("#rozowe span").html(rozowe); 
      $("#total span").html(total); 

    }); 
}); 

小提琴:

http://jsfiddle.net/gigol777/XAfTA/1/

任何想法?

+0

你爲什麼不使用AJAX來實現呢? – AppleBud

回答

0
$.post("sentdata.php", { name1: $("#zz").val(), name2: $("#xx").val() }); 
0

試試這個方法來發送數據和處理後發送響應

$(document).ready(function() { 
    $('.quantity').bind('click keyup', function(event) 
    { 
    var qs= +$("#zz").val(); 
    var qm= +$("#xx").val(); 
    var price = 2; 

    $.ajax({ 
     type: "POST", 
     url: "test.php", //url to send data 
     data:{qs:qs,qm:qm,price:price}, 
     dataType: json, 
     success: function(response,textStatus,xhr) 
     { 
     console.log(response); //check response first from server 

     //set value to your required position 
      $("#niebieskie span").html(response.niebieskie); 
      $("#rozowe span").html(response.rozowe); 
      $("#total span").html(response.total); 
     }, 
     error:function(xhr,textStatus,errorThrown) 
      console.log(textStatus) 
    } 
    }); 
    }); 
}); 

//test.php file to get request from js 
<?php 
    print_r($_REQUEST);//check data sent from js file 
    $qs=$_POST['qs']; 
    $qm=$_POST['qm']; 
    $price=$_POST['total']; 

    // further processing on server side 
    $total = ($qs + $qm) * $price; 
    $niebieskie = $qs * $price; 
    $rozowe = $qm * $price; 
    $total= $total + ' PLN'; 
    $niebieskie = $niebieskie + ' PLN'; 
    $rozowe = $rozowe + ' PLN'; 
    $response = array('total' => $total, 'niebieskie' => $niebieskie, 'rozowe' => $rozowe); 
    echo json_encode($response); 
?>