I am getting JSON encoded data after ajax call to PHP :
[
{
"id":"4",
"name":"Kg",
"vital_sign_list_id":"3",
"created":"2016-03-01 18:52:27",
"modiefied":"2016-03-01 18:52:27"
},
{
"id":"5",
"name":"Pound",
"vital_sign_list_id":"3",
"created":"2016-03-01 18:52:27",
"modiefied":"2016-03-01 18:52:27"
}
]
There are two datas, and I want to decode using loop and use data using jquery. How can I achieve it?
try below code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
<script>
json = '[{"id":"4","name":"Kg","vital_sign_list_id":"3","created":"2016-03-01 18:52:27","modiefied":"2016-03-01 18:52:27"}, {"id":"5","name":"Pound","vital_sign_list_id":"3","created":"2016-03-01 18:52:27","modiefied":"2016-03-01 18:52:27"}]';
var obj = $.parseJSON( json);
$.each(obj, function(index, val){
alert(val.name);
//you can access other data by using val.id, val.created etc
});
</script>
for more detail have a look at http://api.jquery.com/jquery.parsejson/ and http://api.jquery.com/jquery.each/
You can try this way
var data = [{"id":"4","name":"Kg","vital_sign_list_id":"3","created":"2016-03-01 18:52:27","modiefied":"2016-03-01 18:52:27"}, {"id":"5","name":"Pound","vital_sign_list_id":"3","created":"2016-03-01 18:52:27","modiefied":"2016-03-01 18:52:27"}];
for(var i = 0 ; i < data.length; i++){
console.log("ID "+ i +": "+ data[i].id);
console.log("Name "+ i +": "+ data[i].name);
console.log("Vital "+ i +": "+ data[i].vital_sign_list_id);
}
json_encode(jsonArrVar);
use this in your json php file to encode your json data.
and in jquery parse it using json.parse or eval function.
Related
I am trying to extract the values โโof a json but when I return it I get an object object.
Something I did wrong in decoding? this is the decoding code in php
<?php $contenido=file_get_contents("https://www.deperu.com/api/rest/cotizaciondolar.json");
$info = json_decode($contenido,true);
$cadena=array(
0=>$info['cotizacion'],
);
echo json_encode($cadena);
?>
this is the function code
<script>
$(function() {
$("#btnbuscar").on('click',function(){
var direccion='servicio.php';
$.ajax({
type:'get',
url:direccion,
success:function(datos){
var campo=eval(datos);
alert(datos[0]);
}
});
return false;
});
});
</script>
Uwhen you write this:
$cadena=array(
0=>$info['cotizacion'],
);
echo json_encode($cadena);
Your $info is an array, and cadena is an array, too. So you can direct point $cadenra to the array like this:
$cadena= $info['cotizacion'];
echo json_encode($cadena);
Or fix your js like this:
alert(datos[0][0]);
Here is a simple way to read your JSON without Ajax but with using $.getJSON
On your PHP file since you want to get only "cotization" data change: $cadena=array(0=>$info['cotizacion'] to $cadena=array(0=>$info['cotizacion'][0] and you can remove [0] if you are planning to have and to loop on multiple "cotizacion"
On your javascript use:
$.getJSON("servicio.php", function(data) {
var items = [];
$.each(data[0], function(key, val) {
(key + '=' + val);
});
});
There are several solutions, but don't get wrong in a javascript/jquery while calling a json chain.
For example:
<?php
// Page : service.php
$json = '{
"service": "Reference dollar exchange rate",
"website": "website.com",
"link": "https://www.website.com/gearbox_type/",
"quotation": [{
"buy": 3.419,
"sale": 3.424
}]
}';
// $json = file_get_contents("https://www.website.com/api/example.json");
$info = json_decode($json,true); // convert array
$cadena=array(
0=>$info['quotation'][0],
);
echo json_encode($cadena); // convert json
// get-> [{"buy":3.419,"sale":3.424}]
echo json_encode($cadena[0]); // convert json
// get-> {"buy":3.419,"sale":3.424}
?>
// Javascript
// To better use your function I would have to do a cleanup of the code with JSON.parse
<script>
$(function() {
/*
* Check yes and Json and convert json string
* Analyze the data with JSON.parse () and the data becomes a JavaScript object.
* Ex. var obj = '{hello:'mitico'}' -> convert object
* $.clean_string_json(obj) return-> {hello:'mitico'}
* $.clean_string_json('text' + obj) return-> {}
* $.clean_string_json('text' + obj,false) return-> false
* $.clean_string_json('text' + obj,true) return-> true
*/
$.clean_string_json = function (str,xreturn) {
try {
return JSON.parse(str);
} catch (e) {
return xreturn === false ? false : xreturn || {};
}
};
$("#btnbuscar").on('click',function(){
$.ajax({
type:'get',
url: 'service.php',
success:function(datos){
var campo= $.clean_string_json(datos);
alert(datos[0]); // return -> {"buy":3.419,"sale":3.424}
}
});
return false;
});
});
</script>
Welcome to stackoverflow! We hope you like it here.
As already pointed out by #Anurag Srivastava, call the url directly and you'll get json back, you do not need a proxy.
const jUrl = "https://www.deperu.com/api/rest/cotizaciondolar.json";
$.get(jUrl)
.then(({cotizacion}) => console.log(cotizacion));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Please help me with my problem in displaying JSON data into my view..
my script is:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
$.each(data, function(index, element) {
firstnameID.val(element.first_name);
});
});
});
and my JSON reply is:
{"id":7,"first_name":"John","last_name":"Doe"}
the thing is when i tried to:
alert(element.first_name);
it says UNDEFINED, but when I:
alert(element);
it gives me the value of the last name which is Doe.. my question is how can I then access the other values like the ID and the first name..
EDITED:
this is my route:
Route::get('api/dropdown', function(){
$input = Input::get('option');
$supllier = Supplier::find($input);
returnResponse::json($supllier->select(array('id','first_name','last_name'))
->find($input));
});
Please help me with this one, This is my first time using JSON so im a bit confuse on how this works.
Best Regards
-Melvn
Why are you using each? This should work:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
firstnameID.val(data.first_name);
});
});
Ok, give this a try..
Explicitly state that what you're expecting back from the server is JSON using the dataType option in get().
$('#supplierId').change(function()
{
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data)
{
var firstnameID = $('#firstnameID');
$.each(data, function(index, element)
{
firstnameID.val(element.first_name);
});
},
'json' // <<< this is the dataType
);
});
Now you should be able to access the data using the dot syntax:
console.log("last_name: " + element.last_name);
console.log("first_name: " + element.first_name);
console.log("id: " + element.id);
I would add another few lines, just to check that you're getting back what you expect to see:
console.log("NEW ELEMENT"); // << indicator in the console for your reference
console.log(element); // << the whole "element"
I got this code for the Form:
jQuery
$('#form').ajaxForm({
beforeSend: function () {
bar.width(0);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentCompleted = percentComplete + '%';
bar.width(percentCompleted)
bar.text(percentCompleted)
console.log(percentCompleted);
///The Console logs properly.
},
complete:
//------------------------------------
//THIS IS WHERE LIES PROBLEM IS
//------------------------------------
function (xhr) {
//How do you convert the xhr to JSON?
//I tried :
var out = JSON.parse(xhr)
// and :
var out2 = $.parseJSON(xhr)
console.log('Completed1: ' + out);
console.log('Completed2: ' + out2);
},
error: function (xhr, desc, err) {
console.log(xhr)
console.debug(xhr);
console.log("Desc: " + desc + "\nErr:" + err);
}
});
The PHP is like:
$OutCollection is an Associative Array()
Firebug Console says:
Cant figure out what's really Wrong.
Any help is highly appreciated.
PHP output / response in firebug
Console.log(xhr) prints
It seems that xhf is a XMLHttpRequest object so the responseText property will have your json.
function (xhr) {
//How do you convert the xhr to JSON?
//I tried :
var out = JSON.parse(xhr.responseText)
// and :
var out2 = $.parseJSON(xhr.responseText)
console.log('Completed1: ', out);
console.log('Completed2: ', out2);
},
Solved the mystery:
Using the hint from #Musa in the comment that suggested to try the console.log(xhr),
I came up with this.
var out=$.parseJSON(xhr.responseText);
$.each(out,function(i,v){
//then:
console.log(out[i]) //to access each piece of the information.
});
However,
Somehow, both parameters of the $.each() are returning the key of the key=value pair. I somehow thought the i should be the index and the v, value of the $.each loop. So that we could do something like: v[i]. using i as an index to access the values stored in the v Array of values.
Even though, it works hackingly however.
I think you dont have that ; after that variable declaration like:
var out= JSON.parse(xhr);
var out2= $.parseJSON(xhr);
The problem here is HTTP header
We need to make the browser think the receiving data is json and then you don't need to parse the returning string to json.
Just need to add this before you echo the json encoded string:
header("Content-type: application/json");
i return this json from my php page but jquery cannot decode it,result is always null.
{
"City": [
{
"CityID": "1",
"CityName": "istanbul"
},
{
"CityID": "2",
"CityName": "Ankara"
}
]
}
Jquery Code:
$.getJSON("handlers/cityhandler.php", function(json){
var result = jQuery.parseJSON(json);
console.log(result[0].City.CityID);
Jquery alternate code:
$.getJSON("handlers/cityhandler.php", function(json){
$.each(json, function(i,City){
$("#selectcity").append('<option value="' + City.CityID + '">' + City.CityName + '</option>');
});
console.log(json.City[0].CityID);โ
The data is already parsed when you receive it, you don't need to call $.parseJSON. Furthermore, the reason why you are getting a null pointer exception is because result[0] doesn't exist: result is an associative array, not a regular array.
$.getJSON("handlers/cityhandler.php", function(json){
console.log(json.City[0].CityID);
});
Your second attempt isn't right either; if you're trying to loop over the cities you must loop over the inner array:
$.getJSON("handlers/cityhandler.php", function(json){
$.each(json.City, function(i, val){
$("#selectcity").append('<option value="' + val.CityID + '">'
+ val.CityName + '</option>');
});
});
Your JSON output is valid JSON, so the issue is not coming from there. Are you sure that this is exactly what the jQuery handler receives?
Side note, result[0] doesn't exist! Your top element is an object and not an array!
I am currently trying to send a string to a to a php script which will eventually return a JSON file.
Here is code i'm using to send the string:
var str = "testString";
$.post("php/getTimes.php", str,
function(data){
console.log(data.name);
console.log(data.time);
}, "json");
In the 'getTimes' php file I am simply trying to receive the 'str' variable I am passing. Any ideas how to do this? It seems like it should be pretty simple.
You have to name attributes in POST data either with serialized string:
var data = "str=testString";
$.post("php/getTimes.php", data, function(json) {
console.log(json.name);
console.log(json.time);
}, "json");
or with map:
var data = {
str : "testString"
};
$.post("php/getTimes.php", data, function(json) {
console.log(json.name);
console.log(json.time);
}, "json");
To handle this variable in PHP use:
$str = $_POST['str'];
In getTimes.php:
<?php
$var = $_POST['string']; // this fetches your post action
echo 'this is my variable: ' . $var; // this outputs the variable
?>
Also adjust:
$.post("php/getTimes.php", str,
to
$.post("php/getTimes.php", { string: str },