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>
Related
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"
For a PHP/HTML page what is the simplest method of adding data to JSON?
Should I be using PHP, JS, or jQuery?
I've tried different lots of different methods found online, but I can't get any to work. I've tried all of these but I can't get it quite right.
var myObject = new Object();
JSON.stringify()
JSON.parse()
$.extend();
.push()
.concat()
I have this JSON file loaded
{"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"}
]
}
I want to programmatically add
var THISNEWCOMMENT = 'jkl;
{"thecomment": THISNEWCOMMENT}
so that the JSON variable will be
{"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"},
{"thecomment": "jkl"}
]
}
///////////////////
Edit after answer
//////////////////
This is the ajax in my index.php file I used to call the PHP function (in its separate file):
function commentSaveAction ()
{
var mytext = $(".mycommentinput").val();
mytext = mytext.replace("\"","'");
$.ajax({
url: 'php/commentwrite.php',
data: { thePhpData: mytext },
success: function (response) {
}
});
}
And this is the finished PHP function I used with the help of deceze:
<?php
function writeFunction ()
{
$filename = '../database/comments.txt';
$arr = json_decode(file_get_contents($filename),true);
$myData = $_GET['thePhpData'];
$arr['commentobjects'][] = array('thecomment' => $myData);
$json = json_encode($arr);
$fileWrite=fopen($filename,"w+");
fwrite($fileWrite,$json);
fclose($fileWrite);
}
writeFunction ();
?>
//////////////////////
with JS and not PHP
/////////////////////
var myJsonData;
function getCommentData ()
{
$.getJSON('database/comments.txt', function(data) {
myJsonData = data;
var count = data.commentobjects.length;
for (i=0;i<count;i++) {
$(".commentbox ul").append("<li>"+data.commentobjects[i].thecomment+"</li>");
}
});
}
function commentSaveAction ()
{
var mytext = $(".mycommentinput").val();
mytext = mytext.replace("\"","'");
myJsonData.commentobjects.push({"thecomment": mytext});
var count = myJsonData.commentobjects.length;
$(".commentbox ul").append("<li>"+myJsonData.commentobjects[count-1].thecomment+"</li>");
}
Whichever language you do it in, you have to parse the JSON string into an object/array, modify it, then encode it back into a JSON string. Don't attempt any direct string manipulation of the JSON string. PHP example:
$arr = json_decode($json, true);
$arr['commentobjects'][] = array('thecomment' => 'jkl');
$json = json_encode($arr);
Whether to do this in Javascript or PHP or elsewhere depends on when/why/where you need to do this; that's impossible to say without knowing more about the use case.
Try with json_encode and json_decode PHP functions.
//work on arrays in php
$arr = array('sth1', 'sth2');
//here you have json
$jsonStr = json_encode($arr);
//array again
$arrAgain = json_decode($jsonStr);
$arrAgain[] = 'sth3';
//json again
$jsonAgain = json_encode($arrAgain)
Just do it in javascript:
var x = {"commentobjects":
[
{"thecomment": "abc"},
{"thecomment": "def"},
{"thecomment": "ghi"}
]
};
x.commentobjects.push({"thecomment": "jkl"});
var THISNEWCOMMENT = 'jkl',
myObj = JSON.parse(rawJson),
newComment = {"thecomment": THISNEWCOMMENT};
myObj.commentobjects.push(newComment);
var serialized = JSON.stringify(myObj);
//send the updated JSON to your controller
Parse the object, access the commentobject list inside of it, push the new comment in the list and then serialize the updated object again.
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 },
How do I submit an array from dojo to php.
I'm submitting these values:
["a", "b", "c"]
Here's what I got so far:
btn_send.onclick(function(){
var name_array = name_looper();
console.log(name_array);
dojo.xhrPost({
url: "dojo_phpform.php",
content: {names: name_array},
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
});
function name_looper(){
var names = dojo.query('input[type=text]');
var name_array = [];
names.forEach(function(element, index, array){
name_array[index] = dojo.attr(element, 'value');
});
return name_array;
}
I tried to echo $_POST['names'] from the php file(dojo_phpform.php) and it didn't return any errors. It seems like the array isn't actually submitted. The only thing that's returned is the last item in the array. What do I do?Please help, Thanks in advance!
I just tested this with grails and php. In grails I have no problem getting an array submitted through a dojo xhrPost : I retrieve the array properly parsed with all its values as expected.
If I post :
dojo.xhrPost({
content : {
names : ['foo', 'bar']
},
url : "mygrailscontroller"
});
I get an array param on the other side. Which proves the problem hasn't to be solved on the dojo side, but on the php side.
In php, if a form input has a variable of type array, its name parameter has to be set with square brackets, like : "names[]" rather than "names".
So... in your case the solution is not to flatten the array into a string (sorry), but to name your array argument with brackets. So it would be :
dojo.xhrPost({
content : {
"names[]" : ['foo', 'bar']
},
url : "myphpcontroller"
});
As far as I've been able to see, dojo's xhr functions don't support it. I'm using a helper function to "flatten" parameters myself.
_flattenXhrParams: function(params)
{
var newParams = {};
for(var key in params)
{
if(dojo.isObject(params[key]))
{
for(var innerKey in params[key])
{
newParams[key + "[" + innerKey + "]"] =
params[key][innerKey];
}
}
else if(dojo.isArray(params[key]))
{
for(var i = 0, l = params[key].length; i < l; i++)
{
newParams[key + "[]"] = params[key][i];
}
}
else
{
newParams[key] = params[key];
}
}
return newParams;
}
It's butt ugly, I know, and obviously only works on one dimensional arrays/objects. In your case, you'd do:
dojo.xhrPost({
url: "dojo_phpform.php",
content: _flattenXhrParams({names: name_array}),
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
.. and you'd get POST parameters like names[]=a&names[]=b&names[]=c. For objects, you'd get names[somekey]=a&names[otherKey]=b etc. PHP handles both nicely.
I'm pretty sure the values of the content object only take strings. If you want to submit an array, you'd have to turn it into JSON and then json_decode it on the server.
I am using Codeigniter and trying to use the jQuery autocomplete with it. I am also using #Phil Sturgeon client rest library for Codeigniter because I am getting the autocomplete data from netflix. I am return correct JSON and I can access the first element with
response(data.autocomplete.autocomplete_item[0].title.short);
but when I loop through the results
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short)
}
it acts like a string. Lets say the result is "Swingers", it will return:
Object.value = s
Object.value = w
Object.value = i
and so on.
the js:
$("#movies").autocomplete({
source: function(request, response) {
$.ajax({
url: "<?php echo site_url();?>/welcome/search",
dataType: "JSON",
type:"POST",
data: {
q: request.term
},
success: function(data) {
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
}
});
}
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
$(ul).attr('id', 'search-autocomplete');
return $("<li class=\""+item.type+"\"></li>").data( "item.autocomplete", item ).append(""+item.title+"").appendTo(ul);
};
the controller:
public function search(){
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// set var equal to results
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'));
//$this->rest->debug();
//$json_data = $this->load->view('nice',$data,true);
//return $json_data;
echo json_encode($netflix_query);
}
the json return
{"autocomplete":
{"autocomplete_item":[
{"title":{"short":"The Strawberry Shortcake Movie: Sky's the Limit"}},
{"title":{"short":"Futurama the Movie: Bender's Big Score"}},
{"title":{"short":"Daffy Duck's Movie: Fantastic Island"}}
...
any ideas?
thanks.
there are some console logs with the return
the url
in, as you've noticed, doesn't do what you'd like with arrays. Use $.each
As far as I know, for (property in object) means that you want to access each of its properties rather than accessing them via the index. If you want to access them via the index, you probably want to use the standard for loop.
for (i = 0; i <= 10; i++) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
or if you still want to use your code, try this:
for (i in data.autocomplete.autocomplete_item) {
response(i.title.short);
}
I haven't test them yet but I think you have the idea.
ok I figured out the correct format that I need to send to the autocomplete response method:
the view
$("#movies").autocomplete({
minLength: 2,
source: function(request, response) {
$.post("<?php echo base_url();?>welcome/search", {q: request.term},
function(data){
//console.log(data);
response(data);
}, 'json');
}
});
the controller:
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// Pull in an array
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'),'json');
$json = array();
foreach($netflix_query->autocomplete->autocomplete_item as $item){
$temp = array("label" => $item->title->short);
array_push($json,$temp);
}
echo json_encode($json);
what was needed was to send back to the view an array of objects. Thank you guys for all your answers and help!!