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']);
Related
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 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 new to jQuery. Following is the data variable that contains a json dictionary.
{
"user":null,
"currency":"EUR",
"balance":0,
"translist": [
{ "trans1":"something","trans2":"something2" }
]
}
and my jQuery method receives a json/Javascript object from the Rest GET call
success: function (data){
for(x in data) {
console.log(x + ': ' + data[x]);
}
});
Is there any library that can help to parse/walk through this json object and get to some kind of objects list? I want to check some of the keys and their respective values. Problem is I don't need all the keys and values from the list and also some of the values can be null, which prevented me to apply some solutions I found using SO.
Or usually is it more common to directly start printing the HTML inside the success function?
EDIT:If it was java for example it would be a Map and I would use an iterator to walk through and see/analyse the map values, and create some array list with the values I want from it. What's equivalent of that in jQuery?
If it was java for example it would be a Map and I would use an
iterator to walk through and see/analyse the map values, and create
some arraylist with the values I want in it. What is the equivalent of that
in jQuery?
Any javascript object can be seen as an associative map.
You can for example directly access the currency as data['currency'].
You can also build an array :
var a = [];
for (var key in data) {
a.push({key:key, value:data[key]});
}
You could also build some HTML and apply functions to the data :
$(document.body).append($(
'<table>' + a.map(function(v){
return '<tr><td>'+v.key+'</td><td>'+v.value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Using jQuery can make the same iteration simpler (working directly from data) :
$(document.body).append($(
'<table>' + $.map(data, function(value,key){
return '<tr><td>'+key+'</td><td>'+value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Try using each
success: function (data){
$.each( data, function( key, value ) {
if(key === "currency")
alert( key + ": " + value );
});
});
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.
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)