I'm using this js for recovering some data from my database MYSQL and it works pretty fine.
<script type = "text/javascript" >
$(document).ready(function() { // When the document is ready
$("select#product1").on("change", function() { // We attach the event onchange to the select element
var id = this.value; // retrive the product id
$.ajax({
url: "ajax.php", // path to myphp file which returns the price
method: "post", // POST request
data: "id=" + id, // I retrieve this data in my$_POST variable in ajax.php : $_POST[id]
success: function(response) { // The function to execute if the request is a -success-, response will be the price
$("input#total").val(response); // Fill the price
}
});
});
}); </script>
In my input#total I get this value (for example):
[{"price":"5","time":"10"}]
how can I get just the price value or the time value?
I searched for some json parser but I'm not able to put it into my input.
This is my full HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="j_idt2">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select#product1").on("change", function() {
var id = this.value;
$.ajax({
url: "ajax.php",
method: "post",
data: "id=" + id,
success: function(response) {
var datashow = jQuery.parseJSON(response);
$("input#total").val(response);
}
});
});
});
</script>
</head>
<body>
<select id="product1" name="product1">
<option value="" selected="selected">-</option>
<option value='17'>Product1</option>
</select>
<input id="total" type="text" name="total" class="form-control" />
</body>
</html>
This is what I get into my input field when I select product1 with $("input#total").val(response);
[{"price":"5","time":"5"}]
When I change this line:
$("input#total").val(response);
with
$("input#total").val(datashow.price);
I don't get anything.
My php seems to render properly my json. It just lookslike my response is not parsed or can't be stored in any way into a var.
Best Answer
Parse you response using jQuery.parseJson e.g Change you code like this below
Hope this will solve your problem
/////////////////////// Tried with static response///////////
And i get correct result.