I have a simple code that switches two values in DB and returns them back to jQuery, so I can switch them for user without need to refresh a apge.
The thing is, I return it as array, console.log shows array ok, but I have no idea how to get the data from array.
Return by PHP:
$data = array($id, $img1, $img2);
echo json_encode($data);
jQuery:
$.post("bg_images_ajax.php", "switch=yes&id="+id).done(function(data){
$("#image-left-"+id).attr("src", "/images/backgrounds/"+data[1]).attr("alt", data[1]);
$("#image-right-"+id).attr("src", "/images/backgrounds/"+data[2]).attr("alt", data[2]);
console.log(data);
});
The data[1] worked almost every time I was working with Ajax, but here it looks like it takes the whole returned array as a simple string (data[2] returns 6 which is third character in the array ["6", "blabla", "blalablala"] returned by console.log).
I tried to have the array be returned as:
["id" = "6", "img1" = "blabla", "img2" = "blalablala"]
And to use this to get what I needed:
data.img1
But this just returns undefined.
I checked the page about jQuery.post http://api.jquery.com/jquery.post/
But I am either blind or just too tired, as I do not see what am I doing wrong.
Ps.: I also tried putting format of response to jQuery code, but it did not work (as I am not really sure where exactly to place it, tried two places, as shown here (not simultaneously)).
$.post("bg_images_ajax.php", "switch=yes&id="+id, "json").done(function(data){
$("#image-left-"+id).attr("src", "/images/backgrounds/"+data[1]).attr("alt", data[1]);
$("#image-right-"+id).attr("src", "/images/backgrounds/"+data[2]).attr("alt", data[2]);
console.log(data);
}, "json");
The PHP is missing
header("Content-Type: application/json");
and defaulting to sending text/html.
jQuery treats the result as a string of (invalid) HTML instead of parsing the JSON into the expected data structure.
Additionally, if you want an object (with named properties) instead of an array (which is accessed by numerical index), then you have to start with an associative array in PHP:
$data = array("id" => $id, "img1" => $img1, "img2" => $img2);
Related
I want to show some data from JSON string by making that string to array
I have used json_decode to convert the json string into an array. Here is my json string (dd):
"{"title":"W3Schools Online Web Tutorials","description":"w3schools.com","image":"http:\/\/www.w3schools.com\/images\/colorpicker.png","url":"https:\/\/www.w3schools.com\/"}"
When I am returning the array or dd the array, that showing me the array as I intended (dd):
array:4 [▼"title" => "W3Schools Online Web Tutorials""description" => "w3schools.com""image" => "http://www.w3schools.com/images/colorpicker.png""url" => "https://www.w3schools.com/"]
But then when I am trying to show $myarray->title it is giving me error:
Trying to get property 'title' of non-object
public function showDetail(Request $request){
$rUrl = "http://api.linkpreview.net/?key=5c59318d927ca5c5b481c89a6c18a0a2623a61d568502&q=".$request->body;
$json_string= file_get_contents($rUrl);
$data= json_decode($json_string,true);
return view('showIn')->with('data', $data);
}
Expected result: W3Schools Online Web Tutorials
Actual result: Error:Trying to get property 'title' of non-object
Your JSON string is in double quotes for one, use single quotes.
Secondly, $myarray->title is what you would do if you were working with an object. Since your working with an array, do it like $myarray['title']
This will work.
$myjson = '{"title": "W3Schools Online Web Tutorials", "description":"w3schools.com","image":"http:\/\/www.w3schools.com\/images\/colorpicker.png","url":"https:\/\/www.w3schools.com\/"}';
$myarray = json_decode($myjson, true);
echo $myarray['title'];
It is an array so you should be able to access it like this $data['title'];
You should use response json instead of return view('showIn')->with('data', $data);
return response()->json($data);
but if you want to print json in your view you can simply do
$rUrl = "http://api.linkpreview.net/?key=5c59318d927ca5c5b481c89a6c18a0a2623a61d568502&q=".$request->body;
$json_string= file_get_contents($rUrl);
return view('showIn')->with('json', $json_string);
In your blade template use
{{ $json }}
I have this JSON encoded with PHP:
{
"id": "37",
"user_id": "1",
"account": "ssdv",
"amount": "5002",
"subject": "\u0647\u062f\u06cc\u0647",
"tags": "[{\"ttt\"}]"
}
the php array for above json was:
array (
'id' => '37',
'user_id' => '1',
'account' => 'ssdv',
'amount' => '5002',
'subject' => 'هدیه',
'tags' => '["ttt"]',
)
tags index is read from MySQL table with JSON datatype, so I can't change format of tags it have to be json array.
I've tried to decode first string as json by this code:
<script>
var obj = JSON.parse('{"id":"37","user_id":"1","account":"ssdv","amount":"5002","subject":"\u0647\u062f\u06cc\u0647","tags":"[{"ttt"}]"}');
</script>
but it throws this error:
Uncaught SyntaxError: Unexpected token t in JSON at position 86 at JSON.parse (<anonymous>)
how can i parse this json as a valid json in javascript?
update
my table is like this:
id user_id account amount subject tags
37 1 ssdv 5002 هدیه ["ttt"]
tags field is MySQL json type.
I fetch this record and try to json_encode it, the tags index turns to "tags":"[{"ttt"}]" after encode. but it cause error when i try to JSON.parse(myEncodedRecord). it looks the tags have to be like this "tags":["ttt"]. I know I can achieve this by preg_replace() , but is there any better way?
JSON.parse('{"id":"37","user_id":"1","account":"ssdv","amount":"5002","subject":"\u0647\u062f\u06cc\u0647","tags":["ttt"]}');
If tags are array why you need {}. I removed them and I was able to parse.
This worked for me in the console. It is safe to use parsing inside a try
if tags is a single entity like if we have 3 tags and we need to show only it's name we can simply put it as an array. only if we need to display multiple attributes we need to fetch it as an array of objects.
in first situation it will be like
"tags":["tag1name", "tag2name","tag3name"]
if it has multiple attributes
"tags":[{"name":"tag1name","type":"type1"},{"name":"tag2name","type":"type2"},{"name":"tag3name","type":"type3"}]
You can validate your JSON syntax with the help of the below website
https://jsonformatter.curiousconcept.com/
You have 2 issues in your JSON String:
1.) You cannot use array as a string. So please change the string "[{"ttt"}]" to [{"ttt"}].
2.) When you are initializing an object, you cannot specify an index alone. You should also specify the value. So in the above point notice the object initialization in the array. If you provide only one string it will consider that as the index not the value. This is javascript not PHP.
So you can either:
1.) Change the `[{"ttt"}]` to `[{"ttt":"test"}]`. That should work or
2.) Change the `[{"ttt"}]` to `[{"value":"ttt"}]` however you feel comfortable.
I have considered the first option so your result string is:
var txt = '{"id":"37","user_id":"1","account":"ssdv","amount":"5002","subject":"\u0647\u062f\u06cc\u0647","tags":[{"ttt":"test"}]}'
Try this out and let me know if you face any issues.
Hope This Helps.
to avoid this error I had to decode tags field value first, then encode the whole array
code:
//get the record
$record = $this->db->get_where('table', ['id' => $id])->row_array();
//decode tags value
$record['tags'] = json_decode($expense['tags']);
//encode and use
$record = json_encode($record);
now it's a standard JSON.
is there anyway i can get this malformed json format which is odd i have no control over this json manually so i need to get this data and manipulate it with rxjs observable from http get
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
I tried with your JSON in the console and this seems to work. In the map function I've used you can probably implement more generic replacement methods to alter the strings, but it works for this example.
function fixBadJSON(response){
let badJSON = JSON.stringify(response); // added this edit in case you don't know how to get the response to a string
let arr = badJSON.split('}\n'); // Looks like the JSON elements are split by linefeeds preceded by closing bracket, make into arr length of 3
let fixedArr = arr.map((item)=>{ // map the array to another, replace the comma at the end of the avatarImage key. elements in array should be proper JSON
if(item[item.length] != '}') item += '}'; //put the brackets back at thend of the string if they got taken out in the split, probably a better way to handle this logic with regex etc
return item.replace('jpg",','jpg"')
});
let parsedJSON = JSON.parse(JSON.stringify(fixedArr));
return parsedJSON
}
Take the JSON data you've posted up there and copy it to a variable as a string and test the function, it will return a properly formatted array of JSON data.
Call that when you get a response from your service to transform the data. As far as the observable chains and any async issues you might be seeing those are separate things. This function is just designed to convert your malformed JSON.
I have an array of arrays in PHP that I need to send to javascript as JSON. The PHP script and AJAX call work, but the returned JSON string is not parse-able JSON; instead of an array of arrays, it just sticks the arrays together with no separators or container.
Example JSON String:
[{"id":"77","options":[],"price":"4.25","title":"Zeppoli's","spec":""}][{"id":"78","options":[],"price":"7.95","title":"Battered Mushrooms","spec":""}]
PHP Snippet that creates above JSON String:
$cartArr = array(); // array of objects to be jsonified
foreach($products as $product){
unset($newItem);
$newItem = array(
"id" => $product['itemID'],
"options" => $theseOptions,
"price" => $product['price'],
"title" => $product['name'],
"spec" => $product["special"],
"cartid" => $product['ID']
);
array_push($cartArr,$newItem);
echo json_encode($cartArr);
}
An attempt to JSON.parse() the string will result in the following error, unless the string is manually corrected.
Uncaught SyntaxError: Unexpected token [
You're building json in a loop, which means you're outputting MULTIPLE independent json strings, which is illegal syntax. e.g. you're doing
[0,1,2][3,4,5]
which is two separate arrays jammed up against each other. It would have to be more like
[[0,1,2],[3,4,5]]
to be valid JSON. You encode to json LAST, after you've completely build your PHP data structure, not piecemeal in the middle of the construction process.
e.g.
foreach(...) {
$array[] = more data ...
}
echo json_encode($array);
Here is my code:
I am getting data from mysql query and getting array of values. But i am not able to populate in javasript. could you please any one help me out...
PHP Code:
$parishFamilyInfo = $parishFamilyInfoBO->sendBirthdayGreeting($personalInfoSearchDO, $parishFamilyInfoSearchDO);
foreach ($parishFamilyInfo as $parishFamily){
if(!empty($parishFamily->email)){
print_r($parishFamily);
}
}
JavaScript:
$(document).ready(function(){
var t = $('#people').bootstrapTransfer(
{'target_id': 'multi-select-input',
'height': '15em',
'hilite_selection': true});
t.populate([ /*here i need to populate php array value*/
{
value:"<?php print_r($parishFamily->email);?>",
content:"<?php print_r($parishFamily->name);?>"
},
]);
//t.set_values(["2", "4"]);
//console.log(t.get_values());
});
print_r is only for debugging. It's not for anything else. Let me quote the documentation:
print_r — Prints human-readable information about a variable
As stated above, it is a debugging function that's used to print the contents of a variable in a more readable manner. It just returns a string — JavaScript does not and will not understand this format.
Use JSON (JavaScript Object Notation) instead. It is is a light-weight data interchange format that is very popular nowadays. You can use the built-in function json_encode to create the JSON representation of your PHP array and then transfer it to JavaScript. JSON being language independent and based on the JavaScript scripting language, your JavaScript code will now be able to parse the array:
t.populate([
{
value: <?php echo json_encode($parishFamily->email); ?>,
content: <?php echo json_encode($parishFamily->name); ?>
},
]);