how to convert object to JSON - php

My jquery looks like this
var formContent ="action=view&msgid="+id;
$.getJSON("myserv.php",formContent, function(json){
$.each( json, function(k, v){`
alert( "Key: " + k + ", Value: " + v );`
});
});
in my php file i have an array that i json encode
while($message->fetch()) {
$arr[$i]["read"]=$message->test;
$arr[$i]["messageid"]=$message2->test2;
$arr[$i]["subject"]=$message2->test3;
$arr[$i]["text"]=$message2->test4;
}
$str=json_encode($arr);
return $str;
the alert returns Key:0 Value: [Object Object]
Any idea how I can get it to return the correct result? How can I display the results nicely in a div or span?

You are putting it all in a single cell array. And then in your callback, in jQuery, you are trying to loop through the array cell. I'm assuming you want to keep $arr an array (guessing you could have multiple 'read', 'subject', etc) so you should change your js to:
var formContent ="action=view&msgid="+id;
$.getJSON("myserv.php",formContent, function(json){
$.each(json, function(i){
$.each(json[i], function(k, v) {
alert( "Key: " + k + ", Value: " + v ); });
});
});
});
Or, if you don't want a single cell array, and will only return one 'read', 'subject etc, then change your PHP to:
if($message->fetch()) {
$arr["read"]=$message->test;
$arr["messageid"]=$message2->test2;
$arr["subject"]=$message2->test3;
$arr["text"]=$message2->test4;
$str=json_encode($arr);
}
else {
$str=json_encode(Array('error' => 'No message'));
}
return $str;

Related

Json Returning [object object] instead of values

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>

Display JSON Data in HTML using Laravel 4

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"

Unable to select a result from the select2 search results

I am using the select2 for on of my search boxes. I'm getting the results from my URL but I'm not able to select an option from it. I want to use the 'product.productName' as the text to be shown after selection. Is there anything that I have missed out or any mistake that I have made. I have included select2.css and select2.min.js,jquery.js
function dataFormatResult(product) {
var markup = "<table class='product-result'><tr>";
markup += "<td class='product-info'><div class='product-title'>" + product.productName + "</div>";
if (product.manufacturer !== undefined) {
markup += "<div class='product-synopsis'>" + product.manufacturer + "</div>";
}
else if (product.productOptions !== undefined) {
markup += "<div class='product-synopsis'>" + product.productOptions + "</div>";
}
markup += "</td></tr></table>";
return markup;
}
function dataFormatSelection(product) {
return product.productName;
}
$(document).ready(function() {
$("#e7").select2({
placeholder: "Search for a product",
minimumInputLength: 2,
ajax: {
url: myURL,
dataType: 'json',
data: function(term,page) {
return {
productname: term
};
},
results: function(data,page) {
return {results: data.result_object};
}
},
formatResult: dataFormatResult,
formatSelection: dataFormatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) {
return m;
}
});
});
This is my resut_object
"result_object":[{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"},{"productName":"samsung salaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Graphite;32GB"},{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;16GB"}]
You are missing id attribute for result data. if it has not, it makes option "unselectable".
Example:
$('#e7').select2({
id: function(e) { return e.productName; },
});
Since I was using AJAX, what worked for me was returning something as the ID on processResults:
$(field).select2({
ajax: {
// [..] ajax params here
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
// proccessResults NEEDS the attribute id here
id: item.code,
// [...] other attributes here
foo: item.bar,
}
})
}
},
},
});
The id param can be a string related to the object property name, and must be in the root of the object. Text inside data object.
var fruits = [{code: 222, fruit: 'grape', color:'purple', price: 2.2},
{code: 234,fruit: 'banana', color:'yellow', price: 1.9} ];
$(yourfield).select2(
{
id: 'code',
data: { results: fruits, text: 'fruit' }
}
);
I have faced the same issue,other solution for this issue is:-
In your response object(In above response Product details object) must have an "id" as key and value for that.
Example:- Your above given response object must be like this
{"id":"1","productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"}
SO you don't need this
id: function(object){return object.key;}

Getting key => value from json array passed from php

I am trying to get an array from PHP and to manipulate it further using jQuery. In my PHP file i do echo json_encode($data) and when i put an alert in my response in jQuery i get:
[
{
"CustomerID": "C43242421",
"UserID": "432421421",
"Customer": "rqewrqwreeqwr",
"Add1": "rqwerqwreqwrqwrqwr",
"Add2": " ",
"Add3": " ",
"Phone": "4131231",
"Fax": "532442141",
"Contact": "reqwrqwrw",
"Email": "gfdgdsg",
"PaymentTerm": null,
"Country": "3231",
"City": "111",
"Zip": " "
}
]
, wich is a valid json array. Now what i try to do further is get the pairs as key => value as i would in an associative array in php.
$.post("templates/test.php",
{data: query,
cond: $(this).text(),
action: 'select'
},
function(res) {
alert(res) //outputs what i pasted above
$.each($.parseJSON(res), function(key, value) {
alert(key + value);
//this outputs: 0[object Object]
});
Removing the $.parseJSON in the above function gives me a invalid 'in' operand e on jquery.min.js(line 3) in Firebug error log.Can you assist me with my troubles?
Try:
var r = $.parseJSON(res);
$.each(r[0], function(key, value) {
alert(key + value);
});
The result of $.parseJSON(res) is an array, containing a single element (an object). When you iterate over that array (using $.each), value represents the entire object that's stored at the current index of the array. You'll need to iterate over that object to output its properties:
$.each($.parseJSON(res)[0], function(key, value) {
alert(key + ' = ' + value);
});
If you have an array with multiple objects inside it, this more general code should output the key-value pairs for all of them:
$.each($.parseJSON(res), function(index, arrayObject) {
$.each(arrayObject, function(key, value) {
alert(key + ' = ' + value);
});
});
res = $.parseJSON(res);
for (var i = 0; l = res.length; i < l; i++) {
data = res[i];
customer = data.Customer;
}
You have there an Array of Objects. You can iterate through the array of objects just like the code above.
You can get some kind of object from json:
function parse_json(res)
{
try{
return eval('(' + response + ')');
}
catch(e){
// invalid json
}
}
Try this:
$.getJSON('your-json-string-file.php', function (data) {
$.each(data, function(key, val) {
alert(key +'=>'+ val)
});
});
Hope this will help you

convert `[object Object]` and append it in a class.?

Q1. How can convert [object Object] to word?
LIKE: [object Object] =to=> salam
Q2. How can append outputs result search[after click on it] in class .list with(mid) tow input.
LIKE: If resulet search was value salam and after click on it get as:
EXAMPLE:
[object Object] -> input ... & input ...
[object Object] -> input ... & input ...
[object Object] -> input ... & input ...
Js:
$('.auto_complete').keyup(function () {
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
//url: 'http://binboy.gigfa.com/admin/tour_foreign/auto_complete',
url: 'auto_complete',
data: dataObj,
cache: false,
success: function (data) {
var id_name = $('.list_autobox_hotel').attr('id');
$('.list_autobox_hotel').show().html('');
if (data == 0) {
$('.list_autobox_hotel').show().html('<p><b>there is no</b></p>');
} else {
$.each(data, function (index, value) {
$('<p id="' + value.name + '">' + value.name + '</p>').appendTo('.list_autobox_hotel');
});
//////////////////////*HERE Q1//////////////////////
$('.list_autobox_hotel p').bind("click", function (e) {
e.preventDefault();
var ac = $(this).attr('id');
var ok = $.grep(data, function (e) {
return e.name == ac;
})[0].units;
//alert(ok);
/////////////*HERE Q2//// for append////////
$(ok).appendTo('.list');
/////////////HERE Q2*////////////
$(this).remove();
return false;
});
//////////////////////HERE Q1*//////////////////////
$('body').click(function () {
$(".list_autobox_hotel p").hide().remove();
$('.auto_complete').val('');
$('.list_autobox_hotel').show().html('');
$('.list_autobox_hotel').css('display', 'none');
});
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
PHP[insert to database]:
$units = array();
$name_units = $this->input->post('name_units');
$price_units = $this->input->post('price_units');
$checkbox_units = $this->input->post('checkbox_units');
foreach ($name_units as $idx=>$name){
$units[] = array(
'name_units' => $name_units[$idx],
'price_units' => $price_units[$idx],
'checkbox_units' => $checkbox_units[$idx],
);
}
$data = array('name' =>$this -> input -> post('name'),
'units' => json_encode($units)
);
$this -> db -> insert('hotel_submits', $data);
PHP[select code]:
$data = array();
foreach ($query_hotel_search->result() as $row)
{
$units = json_decode($row->units);
$data[] = array('name' => $row->name, 'units' =>$units );
}
echo json_encode($data);
DEMO: There are here the contents of the database and output code PHP and test code for you => CLICK HERE
UPDATE: json response:
Output values salam & salavat of php code: [this values select(selcet * from ...) by json_encode()]
salam:
[{"name":"salam","units":[{"name_units":"salam","price_units":"74,554","checkbox_units":["minibar","mobleman"]},{"name_units":"mokhles","price_units":"4,851,269","checkbox_units":["mobleman","tv"]},{"name_units":"fadat","price_units":"85,642","checkbox_units":["minibar","mobleman","tv"]}]}]
salavat:
[{"name":"salavat","units":[{"name_units":"salam","price_units":"5,452","checkbox_units":null},{"name_units":"khobe","price_units":"5,452,545","checkbox_units":["minibar","mobleman"]}]}]
my answer is totally based on assumption you are getting this json as response when i searched "salam"
[
{
"name": "salam",
"units": [
{
"name_units": "salam",
"price_units": "74,554",
"checkbox_units": [
"minibar",
"mobleman"
]
},
{
"name_units": "mokhles",
"price_units": "4,851,269",
"checkbox_units": [
"mobleman",
"tv"
]
},
{
"name_units": "fadat",
"price_units": "85,642",
"checkbox_units": [
"minibar",
"mobleman",
"tv"
]
}
]
}
]
in the success callback iterate over the json as follow
if (data == 0) {
$('.list_autobox_hotel').show().html('<p><b>there is no</b></p>');
}
else
{
$.each(data[0].units, function (index, value) {
$('<p id="' + data[0].units[index].name_units + '">' + data[0].units[index].name_units + '</p>').appendTo('.list_autobox_hotel');
});
here is a demo hopefully you will get the idea http://jsfiddle.net/BBSyy/
EDIT
see this fiddle http://jsfiddle.net/BBSyy/1/
Another Edit
see this fiddle with grep example http://jsfiddle.net/BBSyy/3/

Categories