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();
}
});
Related
In my application, I want to associate Country with its ID like this:
var Country = {
'France': 15,
'Canada': 26,
'Italy': 32
};
My database return to me an Associative Array and I can easily take all data I want to use.
for the moment I use that but my "push" don't want to use my variable "pays" ...
var pays = data[i].pays.nomFR;
allPays = [];
allPays.push({pays : data[i].pays.id});
Problem solved!
var pays = data[i].pays.nomFR;
allPays = new Array();
allPays[pays] = data[i].pays.id;
my push function was not the good one. That make exactly what I want!
:)
I want to give the user an option so he can write IDs of wordpress categories that are going to be shown on an specific page.
The wordpress field is going to be named the_field('categories_id') so if he enters there IDs with comma separated like this 84, 95, 10. Then all of this are shown.
I have made it work with only one id, for example if page body.term-espectaculos the show a .filter li with data-filter=".filter-84".
This is working ok using this code:
if(jQuery('body').hasClass('term-espectaculos')){
if(jQuery('.filters li').attr('data-filter=".filter-84"') !== undefined ){
jQuery(this).fadeIn()
}
}
The problem is that the user must be able to add multiple IDs so it's not going to be only one like in this example. How can I do it?
Thanks!
add a json encoded array to your data-filter by jQuery('.filters li').data('filter', jsonEncodedArray);
EDIT: In php you can encode to a json array like this:
$array = array(84,95,10);
echo json_encode($array);
In javascript:
var array = [84,95,10];
var jsonEncodedArray = JSON.stringify(array);
If I understand correctly, you'd like to only fade in the list items that have a data-filter attribute that is in your comma-seperated list:
var values = '84, 95, 10',
valArr = values.split(', ');
if(jQuery('body').hasClass('term-espectaculos')){
jQuery('.filters li').filter(function(){
var thisFilter = ($(this).attr('data-filter') || '').replace('.filter-','');
return $.inArray(thisFilter, valArr) > -1;
}).fadeIn();
}
JSFiddle
Note that this requires that your values in string form are split up by precisely a comma and a space. You may want to split on just a comma and then trim your array values:
var values = '84, 95, 10',
valArr = $.map(values.split(','), function(v){ return $.trim(v); });
I’m reading X,Y Coordinates from MySQL Database.
2 files(I can post the connection file if needed): coordinate_array, and map.php
coordinate_array: I am making a multidimensional arrays so I can then use json_encode($desk). I only need x,y values for the JS/Jqueryt part.
updated PHP code and JQuery CODE.. still does not work!?
<?php
include 'db_conn.php';
header('Content-Type: application/json');
$coordinate_sql = "SELECT x_coord, y_coord FROM coordinates";
$result = mysqli_query($conn,$coordinate_sql);
//see if query is good
if($result === false) {
die(mysqli_error());
}
//array that will have number of desks in map area
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk[] = array('x' => $row['x_coord'],
'y' => $row['y_coord']);
} //end while loop
echo json_encode($desk); //encode array
?>
The code above gives me this as the result for the array:
[{"x":"20","y":"20"},{"x":"30","y":"30"},{"x":"40","y":"40"},{"x":"50","y":"50"}]
map.php : This is the part where is not entirely working. I'm trying to get the values from json_encode with JQuery but I get no output on screen.
Don't know which of these two I should use
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
Need help here please
<canvas id="imageView" width="600" height="500"></canvas>
<script type="text/javascript">
//I have no idea how to get the encoded values
$.post('coordinate_array.php', {}, function(data) {
results = JSON.parse(data);
for(i = 0;i < results.length;i++) {
Paint(results[i].x, results[i].y);
}
});
I want to execute this function
//function to paint rectangles
function Paint(x,y)
{
var ctx, cv;
cv = document.getElementById('imageView');
ctx = cv.getContext('2d');
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
//x-axis,y-axis,x-width,y-width
ctx.strokeRect(x, y, x+100 , y+100);
}
</script>
The JSON formal definition tends to have an object (or, key-associative-array: {}) as the root of any JSON object, as opposed to an array ([]).
To wrap it inside one associative object:
$deskOutput = array("coords" => $desk);
echo json_encode($deskOutput); //encode array
Then, on the JavaScript side, you will just need to get "each(data.coords," and you'll have your array.
For that matter, it seems like you're putting unnecessary complexity in your array structure at the PHP level. How about this?
$desk[] = array("x" => $row['x_coord'], "y" => $row['y_coord']));
That will create just one object for each x/y set. I'll leave it to you to figure out how you could simplify your JavaScript accordingly.
First just make $desk like this:
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk[] = array('x' => $row['x_coord'], 'y' => $row['y_coord']);
}
echo json_encode($desk);
And call the php script like so:
$.post('coordinate_array.php', {}, function(data) {
results = JSON.parse(data);
for(i = 0;i < results.length;i++) {
Paint(results[i].x, results[i].y);
}
});
I'm going to test this really quick to make sure I got everything right.
Edit: Okay, I tested this, it works.
I need to use a variable when selecting data from a json source like this.
The json is retrieved with jquery getJSON().
"prices":[{
"fanta":10,
"sprite":20,
}]
var beverage = fanta;
var beverage_price = data.prices.beverage;
Now beverage_price = 10
var beverage = sprite;
var beverage_price = data.prices.beverage;
Now beverage_price = 20
When I try to do it like in the examples, the script tries to look up the beverage entry in prices.
Thanks a lot!!
You can access it like:
var beverage = 'fanta';
var beverage_price = data.prices[0][beverage];
As VisioN mentioned in the comment, data.prices is an array, you need to access its first element with [0] which contains prices { "fanta":10, "sprite":20}
here is the working example : http://jsfiddle.net/2E8AH/
Or else you can make data.prices an object like below : (if it is in your control)
var data = {
"prices" :
{
"fanta":10,
"sprite":20,
}
};
and can access without [0] like this : http://jsfiddle.net/Y8KtT/1/
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.