This code give me this error: c.apply is not a function
All code works well only if i use one function. However i am not sure about how use two functions. These lines are probably wrong :
postHandler(<?php echo get_posts($db, 0, $_SESSION['posts_start']); ?>, <?php echo get_posts1($db, 0, $_SESSION['posts_start']); ?>);
and
var postHandler = function(postsJSON, postsJSON1) {
$.each(postsJSON, postsJSON1, function(i, post, post1) {
script
first function
function get_posts($db, $start, $number_of_posts) {
//code
return json_encode($posts);
}
output:
string '[{"username":"Altitude software","foto_oferta":"thumb\/miniaturas\/oferta\/default_offer.jpg","actividades":"Some activities","id_oferta":77,"oferta":"Programador web" ...
second function
function get_posts1($db, $start, $number_of_posts) {
//code
return json_encode($posts1);
}
output:
string '[{"id_offer":77,"tags":["c++","JAVA"]},{"id_offer":76,"tags":["ajax","php"]},{"id_offer":75,"tags":["PHP","JAVA"]}]'
js
var postHandler = function(postsJSON, postsJSON1) {
$.each(postsJSON, postsJSON1, function(i, post, post1) {
var id = 'post-' + post.id_oferta;
$('<div></div>').addClass('post').attr('id',id)
.html('<div class="box_offers"><div class="rating_offer"></div><div class="post-title">'
+ post.oferta + '</div> <div class="post-box"> <a class="oferta_val bold_username">'
+ post1.tags + '</a></div><a id='+id+'hide class="post-more" >Descrição</a><div class="logo_offer">')
.appendTo($('#posts'));
$('#'+id+'hide').click(function() {
$('.'+id+'hidden').slideToggle('fast');
});
});
};
postHandler(<?php echo get_posts($db, 0, $_SESSION['posts_start']); ?>, <?php echo get_posts1($db, 0, $_SESSION['posts_start']); ?>);
I believe the problem is this line:
$.each(postsJSON, postsJSON1, function(i, post, post1) {
The generic iterator $.each() function only takes two parameters, the second of which is supposed to be a function. Similarly the callback function you provide is supposed to take two parameters.
What is your intention as far as supplying two objects to iterate over at the same time? If you can describe your data structures and explain what you want to do I could make some suggestions. (Show your JSON...)
UPDATE: OK, based on the question update both postsJSON and postsJSON1 are arrays. Given the way that you were trying to use both from inside the same function it appears that the elements within the arrays have a one-to-one relationship, that is, postsJSON[0] relates to postsJSON1[0], postsJSON[1] relates to postsJSON1[1], postsJSON[2] relates to postsJSON1[2], and so on and so forth.
If that is the case the smallest possible change to your existing code to get it to work would be this:
var postHandler = function(postsJSON, postsJSON1) {
$.each(postsJSON, function(i, post) {
var post1 = postsJSON1[i];
// the rest of your code from inside your $.each() here
});
};
That is, continue to use $.each(), but noting that it can only directly iterate over one array at a time use the provided index i to iterate over the other array in parallel by setting that up manually as the first line of the function.
Or perhaps the more obvious way to do it is with a traditional for loop:
var postHandler = function(postsJSON, postsJSON1) {
var i, post, post1;
for (i = 0; i < postsJSON.length; i++) {
post = postsJSON[i];
post1 = postsJSON1[i];
// the rest of your code from inside your $.each() here
}
};
Either way will process both arrays in parallel. Obviously this assumes the arrays are the same length and that the items at any given index number will be the items that you want to relate to each other as mentioned above - if not then you will need to provide more detail about how the arrays are related.
Related
I send the array with getJSON like this:
$.getJSON('valreceber1.php?arr'+ '&arr=' + arr, function (data6) {
});
Where the array is returned this way, when I do var_dump:
$id_utt1 = $_GET['arr'];
var_dump($id_utt1);
Data looks like this:
arr:
arr: 602,602,602,755,602,602,602
When I apply this line of code, I always get an error:
$in = str_repeat('?,', count($id_utt1) - 1) . '?';
How can I solve?
In your call to the PHP code, you are creating a blank element as you add the same variable in twice (arr)...
$.getJSON('valreceber1.php?arr'+ '&arr=' + arr, function (data6) {
});
This will mean that, as you can see there are two elements instead of just the one.
So firstly -
$.getJSON('valreceber1.php?arr=' + arr, function (data6) {
});
This is also giving you a string of comma separated numbers and not an array of values, so use something like explode() to split it into an array...
$id_utt1 = explode(',', $_GET['arr']);
ok I am trying to answer a question and learning to code. regarding an array and using foreach statements the function must remain as this "function animalNames" must stay somewhere but apparently, I am doing something wrong because I get it returned as undefined. even through it produces the correct array back could someone look at it and let me know what i have done wrong.
attached is a picture of the code and array and question that i answered. this is how i wrote my function.
const displayNames = [];
zooAnimals.forEach(function animalNames(element){
var display = "name: " + element.animal_name + ", " + "scientific: " + element.scientific_name
displayNames.push(display);
})
console.log(displayNames);
again i get the correct array back and the data looks correct...but animalNames comes back as undefined...i cannot remove this portion i am to keep it there but i do not know what to do with it.
try this, it defines a function animalNames as separate function
const displayNames = [];
const zooAnimals = [
{animal_name:"Jackel",scientific_name:"Canine"}
]
function animalNames({animal_name, scientific_name}){
return `name: ${animal_name}, scientific: ${scientific_name}`
}
zooAnimals.forEach((element)=>{
displayNames.push(animalNames(element));
})
console.log(displayNames);
I believe you are following this challenge. In this case, make sure to read the instructions properly:
The zoos want to display both the scientific name and the animal name in front of the habitats.
Use animalNames to populate and return the displayNames array with only the animal name and scientific name of each animal.
displayNames will be an array of strings, and each string should follow this pattern: "name: {name}, scientific: {scientific name}"
So from the instructions you are expected to create a function animalNames() that creates an array named displayNames and returns this array from within your function animalNames(). The array displayNames contains strings of the sturcture name: animal_name, scientific: scientific_name.
// you could set zooAnimals as a required parameter in your function
// but as it is defined in the same file you can access it directly as well
function animalNames() {
const displayNames = [];
// you have to do the forEach on zooAnimals here
zooAnimals.forEach(animal => displayNames.push(`name: ${animal.animal_name}, scientific: ${animal.scientific_name}`))
// return an array
return displayNames;
}
The way you did it, the function animalsName() is an anonymous function that only exists within the zooAnimals.forEach() call. Therefore, it is undefined.
I need to check if a number is present in an array of number that I get from PHP, and if yes render a data coming from iosocket. But for some reason this code won't work.
The array return 20, 25 and the number to check is 20 f.example
<script>
var negozi_seguiti = <?php echo json_encode($negozi_seguiti); ?>;
var post = io('http://1clickfashion.com:3002');
post.on("test-channel:App\\Events\\Post", function(message){
// increase the power everytime we load test route
alert(negozi_seguiti);
if (jQuery.inArray(negozi_seguiti, message.data.negozio) == -1) {
$('#timeline').addClass("timeline");
$('#timeline').prepend(message.data.timeline);
$('#rocket').hide();
}
});
</script>
What i'm wrong?
You misused inArray, you inverted arguments, use it like this :
var arr = [20, 21];
console.log($.inArray(20, arr))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I also suggest you tu use indexOf which works the same way but is called directly on the array reducing the risk of doing a mistake like this :
var arr = [20, 21];
console.log(arr.indexOf(20));
It makes your code clearer, you get rid of jQuery, and finally it is faster.
If you are getting proper value in your array negozi_seguiti variable then you need to change $.inArray('search_value', 'yourarray') like bellow.
var negozi_seguiti = <?php echo json_encode($negozi_seguiti); ?>;
var post = io('http://1clickfashion.com:3002');
post.on("test-channel:App\\Events\\Post", function(message) {
// increase the power everytime we load test route
alert(negozi_seguiti);
if (jQuery.inArray(message.data.negozio, negozi_seguiti) == -1) {
$('#timeline').addClass("timeline");
$('#timeline').prepend(message.data.timeline);
$('#rocket').hide();
}
});
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.
It sounds a lot more complicated than it really is.
So in Perl, you can do something like this:
foreach my $var (#vars) {
$hash_table{$var->{'id'}} = $var->{'data'};
}
I have a JSON object and I want to do the same thing, but with a javascript associative array in jQuery.
I've tried the following:
hash_table = new Array();
$.each(data.results), function(name, result) {
hash_table[result.(name).extra_info.a] = result.(name).some_dataset;
});
Where data is a JSON object gotten from a $.getJSON call. It looks more or less like this (my JSON syntax may be a little off, sorry):
{
results:{
datasets_a:{
dataset_one:{
data:{
//stuff
}
extra_info:{
//stuff
}
}
dataset_two:{
...
}
...
}
datasets_b:{
...
}
}
}
But every time I do this, firebug throws the following error:
"XML filter is applied to non-xml data"
I think you can use the JSON response as an associative array. So you should be able to go directly in and use the JSON.
Assuming you received the above example:
$('result').innerHTML = data['results']['dataset_a']['dataset_two']['data'];
// Or the shorter form:
$('result').innerHTML = data.results.dataset_a.dataset_two.data;
Understand that I haven't tested this, but it's safer to use the square brackets with a variable than it is to use parenthesis plus the name with the dot accessor.
Your example is failing because of some convoluted logic I just caught.
$.each(data.results), function(name, result) {
hash_table[result.(name).extra_info.a] = result.(name).some_dataset;
});
Now, the foreach loop goes through the variable data.results to find the internal elements at a depth of 1. The item it finds is given to the lambda with the key of the item. AKA, the first result will be name = "datasets_a" item = object. Following me so far? Now you access the returned hash, the object in item, as though it has the child key in name ... "datasets_a". But wait, this is the object!
If all else fails... write your result JSON into a text field dynamically and ensure it is formatted properly.
Why would you want to change an array into another array ?-)
-- why not simply access the data, if you want to simplify or filter, you can traverse the arrays of the object directly !-)
This works. Just dump it into a script block to test.
d = {
'results':{
'datasets_a':{
'dataset_one':{
'data':{
'sample':'hello'
},
'extra_info':{
//stuff
}
},
'dataset_two':{
///
}
///
},
'datasets_b':{
///
}
}
}
alert(d.results.datasets_a.dataset_one.data.sample)
I hope this pasted in correctly. This editor doesn't like my line breaks in code.
d = {
'results':{
'datasets_a':{
'dataset_one':{
'data':{
'sample':'hello'
},
'extra_info':{
//stuff
}
},
'dataset_two':{
///
}
///
},
'datasets_b':{
///
}
}
};
alert(d.results.datasets_a.dataset_one.data.sample)