hi i have a page contains a link , when user click the link i want to go to database and retrieve two arrays , but when i alert those two arrays i got this exception
Unexpected token [
this is my js code
function acNewConcpet(element){
var parent = element.parentNode;
parent.removeChild(element);
var concpetSelect = document.createElement('select');
var relationSelect = document.createElement('select');
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var data = JSON.parse(xmlhttp.responseText);
alert(data);
}
}
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+"concept"+"/TRUE",true);
xmlhttp.send();
}
and this is my php code
public function getRelatedConceptsAndRelations($concpetName, $Ajax) {
if ($Ajax) {
$concepts = array('c1', 'c2');
$relations = array('r1','r2');
echo json_encode($concepts);
echo json_encode($relations);
}
return;
}
why is this exception ? and how can i solve it ? and how can i receive those two arrays in my js ?
this is full code code
JSON.parse can only parse a single JSON literal.
You should combine the two arrays into a single object with two properties.
You are returning malformed JSON. From what I understand from your code, it prints out this JSON:
['c1','c2']['r1,r2']
You cant have 2 arrays like this. You must print it like:
[['c1','c2'],['r1','r2']]
Sorry for my rusty PHP, but you must have something like:
$json = array(
array('c1','c2'),
array('r1','r2')
);
echo json_encode($json);
Since you are using jQuery, why not use $.getJSON()?
$.getJSON(url,function(returnData){
//returnData is the parsed JSON
});
When you response a JSON, it needs to be one JSON, but you are sending two seperate arrays.
Merge those two JSONs into one.
Update:
Do it like this:
public function getRelatedConceptsAndRelations($concpetName, $Ajax) {
if ($Ajax) {
$concepts = array('c1', 'c2');
$relations = array('r1','r2');
echo json_encode(array($concepts, $relations));
}
return;
}
Related
I need to show object_id of each object(response) from the following data.
This is the response i'm getting through Api. Suggestion or solution both will be well appreciated.
response:{"object_id":"a9951ef0","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"ON"}
response:{"object_id":"8b1546924063","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"OFF"}
response:{"object_id":"9b9d","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"ONLINE"}
Expected output :
object_id = a9951ef0
object_id = 8b1546924063
object_id = 9b9d
I assume that you have 3 different responses with common key in them and you want to take the value of common key from them
If am correct you can you use streams.
Convert the json responses to List of objects
[
"response1",
"response2",
"response3"
]
arrayList = new Gson().fromJson(<above json>, ArrayList.class)
Then you can get expected values using streams
arrayList.stream.map(<arraylistType> :: <keyName>).collect(Collectors.toList());
Your API is returning JSON, which is a string. You need to “parse” it into a JavaScript Object and then you can simply access the value at the desired key.
const parsedResponse = JSON.parse(response);
console.log(parsedResponse.object_id);
Following logic could work. The example in pseudo code. Not work directly.
# real_response is your message from API.
# Convert it into array by splitting newlines. Use different separator if needed.
responses_in_array = real_response.split("\n");
# Loop through every responses.
foreach(single_response in responses_in_array) {
# Clean responses before converting them into javascript objects.
clean_response = single_response.replace("response:", "");
real_object = JSON.Parse(clean_response);
// Do what ever you want. To access object_id, just call
// real_object.object_id.
//
// If needed, before cleaning line, check if it's not empty line.
}
When you have solved the basic logic to parse the message, you can find better ways or built-in functions that help you.
Solution: I've solved the issue by the following way. Now everything is working fine.
<script type="text/javascript">
document.getElementById('test').onclick = function() {
xhr = new XMLHttpRequest();
xhr.open("GET", "filename.json or api url", true);
//xhr.open("GET", "compose.json", true);
xhr.onprogress = function(e) {
var data = e.currentTarget.responseText;
console.clear();
var data = JSON.parse(JSON.stringify(data));
data = data.replace(/(\r\n|\n|\r)/gm, "#");
data = data.replace(/##response:/g, ",");
data = data.replace(/response:/g, "");
data = data.replace(/##/g, "");
data = data.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
data = "["+data.replace(/[\u0000-\u0019]+/g,"")+"]";
var data = JSON.parse(data);
console.log(data);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log("Complete = " + xhr.responseText);
}
}
xhr.send();
};
</script>
I am trying to send an array from jQuery post to PHP.
But I am not getting any values with the below code.
Could anyone help ?
jQuery
$("body").on("click", ".js-form",function(event){
var arr = [];
i = 0;
$('.addcolor').each(function() {
if( $(this).text()=="done"){
arr[i++]= $(this).data('request-id');
}
});
alert(arr);
$.post("../ajax/save_Request.php", {requestids:arr, action:'save_request' })
});
alert(arr)-> prints 11,24,35 (eg)
But I am not getting any values in the following PHP variable.
PHP
$ids = ( isset($_POST['requestids']) ) ? $_POST['requestids'] : 0;
Try with this 'choices[]'
$.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } );
See more in : jQuery.post and search the key "Pass arrays of data to the server". I think that you missed []. Try it and return me the result.
Try converting the array to a JSON string first, using
var json = JSON.stringify(arr);
Now that it's a JSON string, you can simply pass it through a hidden field. Then, once you get the string back from the PHP page, you can turn it back into an array using
$array = json_decode($arr, true);
where $arr is the JSON string.
I had a similar problem with trying to pass an array from JQuery to another PHP page and this worked for me.
I'm trying to move some processing from client to server side.
I am doing this via AJAX.
In this case t is a URL like this: https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2.
First problem, I need to send a bunch of these URLs through this little function, to just pull out "1081244497" using my example. The following accomplishes this in javascript, but not sure how to make it loop in PHP.
var e = t.match(/id(\d+)/);
if (e) {
podcastid= e[1];
} else {
podcastid = t.match(/\d+/);
}
The next part is trickier. I can pass one of these podcastid at a time into AJAX and get back what I need, like so:
$.ajax({
url: 'https://itunes.apple.com/lookup',
data: {
id: podcastid,
entity: 'podcast'
},
type: 'GET',
dataType: 'jsonp',
timeout: 5000,
success: function(data) {
console.log(data.results);
},
});
What I don't know how to do is accomplish this same thing in PHP, but also using the list of podcastids without passing one at a time (but that might be the only way).
Thoughts on how to get started here?
MAJOR EDIT
Okay...let me clarify what I need now given some of the comments.
I have this in PHP:
$sxml = simplexml_load_file($url);
$jObj = json_decode($json);
$new = new stdClass(); // create a new object
foreach( $sxml->entry as $entry ) {
$t = new stdClass();
$t->id = $entry->id;
$new->entries[] = $t; // create an array of objects
}
$newJsonString = json_encode($new);
var_dump($new);
This gives me:
object(stdClass)#27 (1) {
["entries"]=>
array(2) {
[0]=>
object(stdClass)#31 (1) {
["id"]=>
object(SimpleXMLElement)#32 (1) {
[0]=>
string(64) "https://itunes.apple.com/us/podcast/serial/id917918570?mt=2&uo=2"
}
}
[1]=>
object(stdClass)#30 (1) {
["id"]=>
object(SimpleXMLElement)#34 (1) {
[0]=>
string(77) "https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2"
}
}
}
}
What I need now is to pull out each of the strings (the URLs) and then run them through a function like the following to just end up with this: "917918570,1081244497", which is just a piece of the URL, joined by a commas.
I have this function to get the id number for one at a time, but struggling with how the foreach would work (plus I know there has to be a better way to do this function):
$t="https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2";
$some =(parse_url($t));
$newsome = ($some['path']);
$bomb = explode("/", $newsome);
$newb = ($bomb[4]);
$mrbill = (str_replace("id","",$newb,$i));
print_r($mrbill);
//outputs 1081244497
find match preg_match() and http_build_query() to turn array into query string. And file_get_contents() for the request of the data. and json_decode() to parse the json responce into php array.
in the end it should look like this.
$json_array = json_decode(file_get_contents('https://itunes.apple.com/lookup?'.http_build_query(['id'=>25,'entity'=>'podcast'])));
if(preg_match("/id(\d+)/", $string,$matches)){
$matches[0];
}
You may have to mess with this a little. This should get you on the right track though. If you have problems you can always use print_r() or var_dump() to debug.
As far as the Apple API use , to seperate ids
https://itunes.apple.com/lookup?id=909253,284910350
you will get multiple results that come back into an array and you can use a foreach() loop to parse them out.
EDIT
Here is a full example that gets the artist name from a list of urls
$urls = [
'https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2.',
'https://itunes.apple.com/us/podcast/dan-carlins-hardcore-history/id173001861?mt=2'
];
$podcast_ids = [];
$info = [];
foreach ($urls as $string) {
if (preg_match('/id(\d+)/', $string, $match)) {
$podcast_ids[] = $match[1];
}
}
$json_array = json_decode(file_get_contents('https://itunes.apple.com/lookup?' . http_build_query(['id' => implode(',', $podcast_ids)])));
foreach ($json_array->results as $item) {
$info[] = $item->artistName;
}
print '<pre>';
print_r($info);
print '</pre>';
EDIT 2
To put your object into an array just run it through this
foreach ($sxml->entries as $entry) {
$urls[] = $entry->id[0];
}
When you access and object you use -> when you access an array you use []. Json and xml will parse out in to a combination of both objects and arrays. So you just need to follow the object's path and put the right keys in the right places to unlock that gate.
Following is my JavaScript code to get JSON data:
$(document).ready(function()
{
$.support.cors = true;
$.getJSON('http://example.com/root_dir/test_json.php', function(data1)
{
alert("data1= "+data1);
});
});
but the above alert shows me JSON in following format-
If I hit my php script URL in browser, it shows JSON data in expected formate as shown below-
[{"name":"AB","std":"7","number":"82"},{"name":"CD","std":"9","number":"90"},{"name":"PQ","std":"12","number":"79"}]
Following is my test_json.php code-
<?php
//Create an array
$json_response = array();
$row_array['name'] = 'AB';
$row_array['std'] = '7';
$row_array['number'] = '82';
array_push($json_response,$row_array);
$row_array['name'] = 'CD';
$row_array['std'] ='9';
$row_array['number'] = '90';
array_push($json_response,$row_array);
$row_array['name'] = 'PQ';
$row_array['std'] = '12';
$row_array['number'] = '79';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
getJSON decodes the JSON into a JavaScript data structure.
Concatenating it with a string will implicitly call toString() on it. That will turn arrays in to a comma-seperated format and plain objects into "[Object object]".
Nothing is going wrong. That is the expected behaviour.
If you want to see the data in JSON format, then use JSON.stringify(data) or use .ajax instead of .getJSON and access the raw text data in the jqXHR object.
i'm newbie in javascript so, in this example exists the geometrycontrols.js (for global controls) and markercontrol.js (for marker controls)
my problem is identify the arrays where "data" is saved...
at the reference i see a savedata function but i have no idea how work with this function...
on the other side, in test.html if i've the outup on the Glog startup and output "data", and let me thinking that comes from array...
My objective is save the coordinates and other all atributes to mysql database, and when i discover where are "data" is the easy part.
if someone worked with this example (or not) can help me i'm grateful
ps: i'm really a newbie on javascript :P
edit1:
I was out for a time, and now I focus in geometrycontrols.js specially in: GeometryControls.prototype.saveData = function(opts){
var me = this;
if(opts.allData === true){
//me.saveAllData();
} else {
//construct a json data record
var geomInfo = opts.geomInfo, index = opts.geomInfo.index;
var record = geomInfo.storage[index];
var recordJSON = {};
recordJSON.type = record.type;
recordJSON.coordinates = [];
//determine geometry type, and copy geometry appropriately
if(record.type === "point"){
recordJSON.coordinates.push({lat:record.geometry.getLatLng().lat(),lng:record.geometry.getLatLng().lng()});
alert(recordJSON.coordinates);
} else {
alert("is not point");
var vertex;
for(var i=0;i<record.geometry.getVertexCount();i++){
vertex = record.geometry.getVertex(i);
recordJSON.coordinates.push({lat:vertex.lat(),lng:vertex.lng()});
}
}
//add title and description
recordJSON.title = record.title[0];
recordJSON.description = record.description[0];
//TODO add styles
recordJSON.style = ""; //TODO} //TODO Make separate prototype function?function postData(data){
//TODO
me.debug(data);
//alert(recordJSON.coordinates);
//alert(data);
};postData(me.serialize(recordJSON));}; `
When I alert(recordJSON.coordinates), the outupt is [object Object] and i've no idea why, in theory this array contains the coordinates...
Here is some code I have used to send the data to MySQL. It uses a little bit of jQuery to do the ajax magic (the line starting with the dollarsign is jQuery).
function postData(data){
me.debug(data);
var dataString = JSON.stringify(data);
me.debug(dataString);
$.post('storage.php', { data: dataString });
};
postData(recordJSON);
As you can see I've modified the way the 'recordJSON' object gets sent to the postData function a bit too: I've removed the serialise function.
Next, create a PHP file (called 'storage.php' in my case) and put this in it:
<?php
$received = json_decode($_POST['data'], true);
echo "just received " . $received['name'];
?>
You now have an array in PHP that you can do with as you please.
In the examplecode above I've modified the jQuery post function a bit, so if it doesn't work, look there.
The data is stored in JSON format in this file: http://gmaps-utility-library-dev.googlecode.com/svn/trunk/geometrycontrols/examples/data/testdata.js -- it's pretty much self-documenting, just follow the example to set your coordinates.
Note that if you need to find the latitude and longitude for a given address this is a good site: http://itouchmap.com/latlong.html