Need Help In Script - javascript

My script code like :
function changePrice(id) {
var url = '<?php echo $base_url ?>home/getprice/';
$.ajax({
url: url,
type: 'post',
data: 'id='+id,
success: function(msg) {
alert(msg);
/*
"regular_price": "800",
"discount_price": 720
*/
}
});
}
I want to both regular price and discount price on separate variable.How??

If you are getting the response as "regular_price": "800", "discount_price": 720 then make it valid JSON, parse it and get the properties.
var obj = JSON.parse('{' + msg + '}');
// valid json -^-----------^-
// get object properties
var regular = data.regular_price;
var discount = data.discount_price;
UPDATE : If response data is valid JSON format then set dataType: 'json' option.
$.ajax({
url: url,
type: 'post',
data: 'id='+id,
// set response datatype as json
dataType:'json',
success: function(msg) {
// get properties
var regular = msg.regular_price;
var discount = msg.discount_price;
}
});
Or parse it directly if the response is a string.
$.ajax({
url: url,
type: 'post',
data: 'id='+id,
success: function(msg) {
// parse the string
var data = JSON.parse(msg);
// get properties
var regular = data.regular_price;
var discount = data.discount_price;
}
});

Thanx to all..Here are the solution :
<script>
function changePrice(id)
{
var url = '<?php echo $base_url ?>home/getprice/';
$.ajax({
url:url,
type:'post',
data:'id='+id,
dataType:'json',
success:function(msg)
{
var regular = msg.regular_price;
var discount = msg.discount_price;
}
});
}
</script>
My Function :
$new = array (
"regular_price" => $result->price,
"discount_price" => $price
);
$newarray = json_encode($new, JSON_PRETTY_PRINT);
print_r($newarray);

Try this:
In server side ajax call:
$respose['regular_price'] = 120;
$respose['discount_price'] = 100;
echo json_encode($response);
In JS: Considering msg is an json object
var data = JSON.parse(msg);
var regular = data.regular_price;
var discount = data.discount_price;

Related

AJAX query post data coming through empty/NULL

I need a sanity check here. I'm posting data through an AJAX call but for some reason it comes through as null.
javascript:
var data = {};
data['pkStudyYears'] = id;
data['years'] = [];
data['years']['pkStudyYears'] = id;
data['years']['fkStudyID'] = $('#fkStudyID').val();
data['action'] = action;
data['years']['intStartYr'] = $('#startYearBox').val();
data['years']['intEndYr'] = $('#endYearBox').val();
console.log(data['years']);
var posturl = '<?php echo site_url('manage/climate_indicators/updateStudyYears');?>'
$.when($.ajax({
type: "POST",
url: posturl,
data: data,
dataType: 'json'
}))
.done(function(result) {
console.log(result.status);
if (result.status === 'failed') {
console.log(result.errors);
}
});
php (updateStudyYears)
$postData = $this->input->post(NULL, true);
$yearArray = $postData['years'];
if(empty($yearArray)) {
echo json_encode(array('status'=>'failed', 'errors'=>'Years are empty'));
exit();
}
I keep getting a failed result with the error "Years are empty". I can't figure out what I'm missing!

Passing array and other data through ajax

This is my javascript function....
But my php controller getting all values but not the array not sure why ? Need help.....
Thanks in advance :)
function submitForm(){
var id = $('#id').val();
var supplier_id = $('#supplier_id').val();
var description = $('#description').val();
var numofpro = $('#numofpro').val();
var product_id = new Array();
for(var i=0;i<numofpro;i++){
product_id[i] = $('#product_id'+(i+1)).val();
}
var payment_mode = $('#payment_mode').val();
//description = description.replace(new RegExp('\r?\n','g'), '<br />');
$.ajax({
url: "<?= base_url(); ?>edit/save_purchase", //The url where the server req would we made.
data: "id="+id+"&supplier_id="+supplier_id+"&description="+description+"&product_id="+product_id+"&payment_mode="+payment_mode,
dataType: "html", //Return data type (what we expect).
beforeSend:function(){
//alert("asds");
},
success: function(data) {
//alert("Edited");
alert(data);
}
});
}
because you pass a string, not an array :) try it:
$.ajax({
url: "<?= base_url(); ?>edit/save_purchase",
type: "POST"
data: {id : id, supplier_id : supplier_id, description : description, product_id : product_id, payment_mode : payment_mode},
dataType: "json",
beforeSend:function(){
//alert("asds");
},
success: function(data) {
//alert("Edited");
alert(data);
}
});
in you php use :
$arr = json_decode($_POST);
//some php code
//some $result;
// if $result arr then
echo json_encode($result);
// else
echo json_encode(array('data' => $result))
hope this helps...
You need to first turn that array into a string in JS. Before sending it, do this:
JSON.stringify(product_id);
Once you receive it in PHP, you need to decode it.
$decoded = json_decode($_POST['product_id'])

Fetch mulitple values using Jquery post getting undefined value

Below is my jquery ajax method
<script type="text/javascript">
$(document).ready(function () {
$('#c_select').change(function(){
var one = 10;
var two = 20;
var three = 30;
var four = 40;
$.ajax({
type:'post',
url:'getvalues.php',
dataType: JSON,
success:function(resp){
alert(resp.first);
}
error:function(resp){
alert(resp.first);
}
});
});
});
</script>
Below given file is where i get the values (PHP File)
<?php
$output = array('first'=>'Steven',
'last'=>'Spielberg',
'address'=>'1234 Unlisted Drive');
echo json_encode($output,JSON_FORCE_OBJECT);
?>
success part is not getting executed i am getting undefined error
Try following code, it should work
$(document).ready(function() {
$('#c_select').change(function() {
var one = 10;
var two = 20;
var three = 30;
var four = 40;
$.ajax({
type: 'post',
url: 'getvalues.php',
dataType: 'json',
success: function(resp) {
alert(resp.first);
},
error: function(resp) {
}
});
});
});

Uncaught SyntaxError: Unexpected token +

I am getting this error using this code, the php id variable is set, why does it show unexpected token?
var current_page = 1;
var id = <?php echo $id; ?>;
$(document).ready(function(){
$.ajax({
'url':'get_data.php',
'type':'post',
'data': 'p='+current_page, 'id='+id,
success:function(data){
var data = $.parseJSON(data);
$('#posts').html(data.html);
$('#pagination').html(data.pagination);
}
console.log(data);
});
});
You should concatenate the data query strings properly:
'data': 'p='+current_page +'&id='+id,
Or using this interface:
data: {p : current_page, id: id},
So it would look like this:
<script type="text/javascript">
var current_page = 1;
var id = <?php echo $id; ?>;
$(document).ready(function(){
$.ajax({
url: 'get_data.php',
type :'POST',
data: 'p='+current_page+'&id='+id,
// data: {p: current_page, id: id},
success:function(data){
var data = $.parseJSON(data);
$('#posts').html(data.html);
$('#pagination').html(data.pagination);
console.log(data);
}
});
});
</script>
Sidenote: You could also explicitly set dataType: 'JSON', so that you would not need $.parseJSON at all.
Wrong syntax for data
replace with following
'data': 'p='+current_page+'&id='+id,
you can do it like this
data: {
p: current_page,
id: id
}

Getting php with js with ajax

It won't give me the value from $scoresArray in php to data_response in js
If I log (obj) it returns nothing.
I have this in JS
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (obj) {
stageRef.$("txtTopscorePunt").html(obj.score[0]);
stageRef.$("txtTopscorePunt2").html(obj.score[1]);
stageRef.$("txtTopscorePunt3").html(obj.score[2]);
}
});
This in php:
function GetScores(){
$query = "SELECT * FROM topscores ORDER BY Scores DESC LIMIT 3";
$result = mysql_query($query);
$scoresArray = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$scoresArray[$i]['score'] = $row['score'];
$i++;
}
echo json_encode($scoresArray);
}
You don't need to JSON.parse(str) with dataType:json -- it's already parsed.
In addition, your selectors are wrong. If you want to select an ID, you need the # character.
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (obj) { // not 'complete'
console.log(obj);
$("#txtTopscorePunt").html(obj.score[0]);
$("#txtTopscorePunt2").html(obj.score[1]);
$("#txtTopscorePunt3").html(obj.score[2]);
}
});
http://api.jquery.com/jQuery.ajax/
update the code to this:
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (data_response) {
console.log(data_response);
var response = data_response;
var response_str = JSON.stringify(response);
alert(response_str); // don't do this if the returned is too much
console.log(response_str); // use your browser console to view the results
}
});
Once you have done this, can you post the results of alert or console log.
Also, in the results does it start with "[" or "{"?
From the results we should be able to help you with the correct way to access your JSON object.
Regards.

Categories

Resources