Convert json object to string - javascript

I have the following controller:
public function getPrice()
{
$id = $this->input->post('q');
$data['price'] = $this->emodel->get_peUniformPrice($id);
echo json_encode($data);
}
which outputs this:
"{\"price\":[{\"Price\":\"250\"}]}"
How can I make it like 250? My jQuery:
function showPrice(size) {
$.ajax({
type: "POST",
url: "<?php echo site_url('enrollment/getPrice/');?>",
data: {
q: size
},
success: function(data) {
$("#txtpeUniform").val(data);
},
});
}

I can see that you are using jQuery.. if you want to turn the json object into a javascript object you could do something like
var convertedObject = $.parseJSON($data);
alert(convertedObject.Price);
what this effectively does is converts your Json string into a javascript object which you can reference the properties out of and the get the value from these properties.. let me give you another example
var jsonString = {'Firstname':'Thiren','Lastname':'Govender'};
var jObject = $.parseJSON(jsonString);
console.log(jObject.Firstname) // this will output Thiren.
console.log(jObject.Lastname) // this will output Govender.
modify your code
function showPrice(size) {
$.ajax({
type: "POST",
url: "<?php echo site_url('enrollment/getPrice/');?>",
data: {
q: size
},
success: function(data) {
console.log(data); // make sure this is returning something..
$("#txtpeUniform").val(data);
},
});
}
I hope this helps you..
Regards

The $.ajax method will automatically deserialise the string to an object for you, so you simply need to access the required property. Assuming that you only ever want to retrieve the first price returned in the price array, you can access it directly by index. Try this:
success: function(data) {
$("#txtpeUniform").val(data.price[0].Price); // = 250
},

Related

How to access only one object send by json not the whole array in ajax success function?

I am trying to receive data from the controller to the view using json_encode and ajax functions. But I am sending to separate values through json, and I am tring to access it. So how can I separate those two objects, and get only a single value?
Let me show you my code:
function check_relation_status()
{
var id=$('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/check_relation_status"); ?>',
data:{id:id},
dataType:'json',
success:function(data)
{
console.log(data);
var ParsedObject = JSON.stringify(data);
var sender_Data = $.parseJSON(ParsedObject);
var senders_id=sender_Data.senders_id;
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/get_senders_data"); ?>',
data:{id:senders_id},
dataType:'json',
success:function(data)
{
console.log(data);
var ParsedObject = JSON.stringify(data);
var sender_values = $.parseJSON(ParsedObject);
var senders_name=sender_values.sender_data;
// alert(senders_name);
$.each(sender_values, function(key,data)
{
var uname = data.uname;
// alert(uname);
$('#friendship_request').append('<div>'+uname +'has sent you a request</div>');
});
}
});
}
});
}
now the controller code
public function get_senders_data()
{
$sender_id=$this->input->post('id');
$this->load->model('Pmodel');
$userdata=$this->Pmodel->getUserdata($sender_id);
$senders['senders_data']=$userdata;
$senders['senders_post'] = $this->Pmodel->get_all_count($sender_id);
// print_r($senders);
echo json_encode($senders);
}
the json value '$senders' holds both the values but when i try to access it usng 'each' function it shows the values two time when there is only a single column for uname . let me add some images to explain.
Where I am wrong?
Try to change like below:-
if(uname){
$('#friendship_request').html('<div>'+uname +'has sent you a request</div>');
}
Note:-
1.You are appending all usernames (which is not correct).
2.You are not checking that username is either undefined or null or empty etc

Using jquery to parse items from a JSON response

I am using PHP and Ajax to parse some JSON. The PHP is creating the array like this.
$myObj->pid = $_POST["parentid"];
$myObj->comp = $comp;
$myObj->colour = $statuscolour;
$myJSON = json_encode($myObj);
header('Content-Type: application/json');
echo $myJSON;
I use the following jquery code
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var response = jQuery.parseJSON(JSON.stringify(msg));
console.log(response);
pid = response[0].pid;
console.log('id = ' + pid);
});
I can see the output from the first console.log as
Object {pid: "p1", comp: 20, colour: "red"}
However I cannot extract the individual variables, it gives the message
Uncaught TypeError: Cannot read property 'pid'
How can I extract the variable?
You've made this more complicated than it needs to be. msg is already an object, which you then convert to a string and back to an object with stringify and parseJSON. And then you try to use it like an array, when it is an object.
Try this:
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var pid = msg.pid;
console.log('id = ' + pid);
});
You are returning an object, not an array.
Also it makes no sense to stringify the data object and parse that string back to object again
Try
var pid = msg.pid;
console.log('id = ' + pid);
First of all, it can't imagine why it would be neccessary to first stringify, then parse the JSON response.
Second, you are trying to access response[0] as if it were an array, which it isn't. You can simply use
response.pid;
To access the object key.
As you don't need to stringify then parse the response, you can just access msg directly, so it all comes down to
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
console.log(msg.pid);
});

Best practice when changing PHP Data to JS Data via AJAX (especially arrays)

(Secondary title): ajax array recieved as json encoded PHP array not behaving as javascript array
For some reason, my PHP array gets sent over to JavaScript just fine, but when I try to access an individual key of the array, it doesn't return anything, or it returns some other value which doesn't correspond. I am of course using json_encode() in the corresponding PHP file (echoClientData.php):
$id = $_GET['selected_id'];
$id = str_replace("clientSel","",$id);
$getclientinfo = "SELECT * FROM `clients` WHERE `ClientID` = $id";
if ($result = $Database->query($getclientinfo))
{
$row = $result->fetch_row();
$output = $row;
}
echo json_encode($output);
This code works fine:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data;
$('#client-detail-box').html(test);
}
});
And returns an array into the #client-detail-box div, e.g.
["1566","","Adrian","Tiggert","","","","","","","","","","","","0000-00-00","0000-00-00","0.00","","0","","","102","Dimitri Papazov","2006-02-24","102","Dimitri Papazov","2006-02-24","1","0","0"]
However, when I do
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
}
It returns
5
You may need to do one of two things when returning JSON from PHP.
Either set your content type in PHP before echoing your output so that jQuery automatically parses it to a javascript object or array:
header('Content-type: application/json');
or specify that jQuery should treat the returned data as json:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
dataType: 'json',
success: function(data)
{
var test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
Be aware, that in your current PHP script, in the event that your query fails, you will be json_encodeing an undefined variable.
Also, your PHP code is entirely open to SQL injection. Make sure you sanitize your $id, either by casting it to (int) or by escaping it before sending it through in your query.
Have you tried using JSON.parse on the value you are getting back from PHP?
e.g.
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = JSON.parse(data); // should be "Tiggert"
$('#client-detail-box').html(test[3]);
}
});
That seems like it would be a fix.

split JSON data from PHP to three arrays in JavaScript

I am passing values from PHP Script to JS using JSON encode.
$arr=array('X'=>$X,'Y'=>$Y,'par'=>$par);
echo json_encode($arr);
Which produces
{"X": ["-0.9537121038646844","-0.9537121038646844","-0.9537121038646844","0.9537121038646843",""],
"Y": ["-0.9537121038646844","-0.7799936811949519","-0.5533396521383813","-0.37962122946864896",null],
"par": ["0.009811016749950838","0.005007306592216437","5.058030686503405E-4","9.451402320405391E-4",null]}
In the javascript, I used the following command
{
$.post("plot.php",param,function(data){dataType:"json";console.log(data);Var X1=data.X;});
}
But I am not able to obtain the values of X alone. I tried few suggestions from similar threads, but none of them did the trick.I need the three arrays, X,Y and Par to be used in JS.
Try this:
$.post("plot.php", param, function(data) {
console.log(data);
var X1 = data.X;
},
"json"
);
You can also use $.ajax (which is the function $.post internally calls):
{
$.ajax({
type: "POST",
url: "plot.php",
dataType: "json",
data: param,
success: function(data) {
console.log(data);
var X1=data.X;
}
});
}
If you are using php you have to specify at the last parameter of post fn that is json type:
$.post("plot.php",param, function(data){
console.log(data);
var X1=data.X;
},'json');

javascript string to variable

I am receiving a JSON string from an ajax call and would like to convert a value to a predefined variable:
var predefined = "hello world";
var foo = {"msg":"predefined"}; // JSON string
I want to echo out the standard string accessing it with
alert(foo.msg)
EDIT: to make the answer more clear here is my call:
var success_msg = "Your email is send successfully!";
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status == "success") {
msg.text(data.msg).addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
})
ajax-share-email.php responds:
{"status":"success", "msg":"success_msg"}
var strings = {"predefined":"hello world"};
alert(strings[foo.msg]);
or e.g.
var messages = {};
messages.success_msg = "Your email is send successfully!";
// ...
msg.text(messages[data.msg]).addClass("email-msg-success");
How about this -- just use the message inline on success and don't even bother to make it part of the JSON. On an error, do include the entire message and use it directly. Also, I'd have your server return something like:
{ "status": true }
or
{ "status": false, "msg": "The mail server is down." }
Then you can just evaluate it as a boolean without comparing it to a string value.
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status) {
msg.text('Your email has been sent successfully!').addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
});
If, and only if, you start reusing your messages for multiple functions, then refactor to a message dictionary and reference it from there. Note your messages object would likely need to be a global variable, or at least in the outer scope of all the functions that use it.
var messages = {};
messages.mail_success = 'Your email has been sent successfully!';
messages.post_success = 'Your data has been updated!';
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status) {
msg.text(messages.mail_success).addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
});
var predefined = "hello world";
var foo = {"msg":predefined}; // JSON string
alert(foo.msg)
?
IFF I understand what you are asking, I think I have all of the pieces here.
You have a variable predefined and you want to be able to return that in your json and have the resulting parsed object contain the value in predefined
JSON.parse will not work for you (at least not in Chrome), but eval will.
var predefined = "Hi! I'm predefined";
// ...
var json = '{"foo": predefined}'; // notice no quotes
var response = eval("(" + json + ")");
alert(response.foo);
var out = eval(foo.msg); // out is now "hello world"
Note: do not use eval() if you are not sure what the content of foo.msg is.
or
var out = foo.msg=="predefined" ? predefined : foo.msg;

Categories