Reputation: 519
i'm doing this in codeigniter
here is my php switch - case part
case 'check':
$balance = $this->Model_transactions->getUserBalance($this->input->post('userId'));
$needToPay = floatval($this->input->post('tuitionRate')) / 2; // 50%
if ($balance >= $needToPay) {
$results = '{"Result": "OK";"Balance":'.$balance.'}';
}
break;
here is the json code
$.ajax({
url: base_url + "api/hires/check/?callback=?",
type: "POST",
dataType: "jsonp",
data: {
userId: $(".navigation").data("login"),
tuitionRate: t.find("#txt-hire-rate").val()
}
}).done(function (a) {
if (a) if ("OK" != a.Result) {
alert (a.Balance);
what i want is to use php $balance variable in my jQuery. please help.
Upvotes: 2
Views: 2713
Reputation: 1523
php switch - case part
case 'check':
$balance = $this->Model_transactions->getUserBalance($this->input->post('userId'));
$needToPay = floatval($this->input->post('tuitionRate')) / 2; // 50%
if ($balance >= $needToPay) {
$results = '{"Result": "OK";"Balance":'.$balance.'}';
// add this in your code
<script>
document.getelementbyId('balance').innerHTML=$balance;
<script>
}
break;
?>
<div id='balance' style='display:none;'></div> // added in the code
json code
var bal=$(#balance).html(); // use this variable where you want to
$.ajax({
url: base_url + "api/hires/check/?callback=?",
type: "POST",
dataType: "jsonp",
data: {
userId: $(".navigation").data("login"),
tuitionRate: t.find("#txt-hire-rate").val()
}
}).done(function (a) {
if (a) if ("OK" != a.Result) {
alert (a.Balance);
I did changes in php code and added the variable in js which can be used anywhere in js you want to.
Upvotes: 1
Reputation: 97
Edit your php script
case 'check':
$balance = $this->Model_transactions->getUserBalance($this->input->post('userId'));
$needToPay = floatval($this->input->post('tuitionRate')) / 2; // 50%
if ($balance >= $needToPay) {
$data = array(
'Result' => 'OK',
'Balance' => $balance
);
echo json_encode($data);
}
break;
Edit your jQuery Script
$.ajax({
type: "POST",
url: '<?php echo base_url()."api/hires/check/?callback=?";?>',
dataType: 'json',
data:{userId: $(".navigation").data("login"),
tuitionRate: t.find("#txt-hire-rate").val()},
success: function(data){
if(data.Result != "OK"){
alert(data.Balance);
}
}
});
Upvotes: 1
Reputation: 50787
Do not try to build the string literal, instead, construct an array and use json_encode
$results = json_encode(array('Result' => 'OK', 'Balance' => $balance), true);
Then return it when you're ready.
return $results;
Upvotes: 1