My Jquery slideshow script looks like that
$(function() {
$('#bg').crossSlide({
sleep: 3,
shuffle: true,
fade: 1
}, [
{ src: 'core/design/images/bgs/1.jpg'},
{ src: 'core/design/images/bgs/2.jpg'},
{ src: 'core/design/images/bgs/3.jpg'},
{ src: 'core/design/images/bgs/4.jpg'}
])
});
As you see, I declared the images' paths one by one. Is there any way to scan folder for images and add all at once. Maybe, it can be done with PHP?
It cannot be done with Javascript. But with a embedded server side code it should be possible (like PHP). Here is an example in php.
There exists a function called glob, which might be suitable for your purpose. Here is an example of how to use it.
$path = <absolute path for the folder where images are located>
$images = glob($path.'/*.jpg') // this returns an array of file names only doesnt contain the path
Now you have the list of arrays in php. You have to start using this in javascript
$(function() {
$('#bg').crossSlide({
sleep: 3,
shuffle: true,
fade: 1
}, [
<?php foreach($images as $filename){ ?>
{ src: 'core/design/images/bgs/<?php echo $filename.jpg ?>'},
<? } ?>
])
});
Yes. It can be done using JS / jQuery:
Works both locally and on live server without issues, and allows you to extend the delimited list of allowed file-extensions:
var folder = "core/design/images/bgs/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.jpg|\.png|\.gif/) ) {
$("body").append( "<img src='"+ folder + val +"'>" );
}
});
}
});
in your case you want to construct an array of Objects {src:"path"} so it could look like:
var folder = "core/design/images/bgs/";
$.ajax({
url : folder,
success: function (data) {
var srcArr = [];
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.jpg|\.png|\.gif/) ) {
var ob = {src : folder+val};
srcArr.push( ob );
}
});
// Now that the Array is filled with Objects send to callback
readFolderCallback( srcArr );
}
});
function readFolderCallback( srcArr ) {
$('#bg').crossSlide({
sleep: 3,
shuffle: true,
fade: 1
}, arrSrc);
}
https://stackoverflow.com/a/32940532/383904
Related
Hello all and thanks in advance,
Short story, I am using a plugin to dynamically populate select options and am trying to do it via an ajax call but am struggling with getting the data into the select as the select gets created before the ajax can finish.
First, I have a plugin that sets up different selects. The options input can accept an array or object and creates the <option> html for the select. The createModal code is also setup to process a function supplied for the options input. Example below;
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
let dueDate = {};
for (let i = 1; i < 32; i++) {
dueDate[i] = i;
}
return dueDate;
}
}
});
What I am trying to do is provide an object to the options input via AJAX. I have a plugin called postFind which coordinates the ajax call. Items such as database, collection, etc. are passed to the ajax call. Functions that should be executed post the ajax call are pass through using the onSuccess option.
(function ($) {
$.extend({
postFind: function () {
var options = $.extend(true, {
onSuccess: function () {}
}, arguments[0] || {});
options.data['action'] = 'find';
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof options.onSuccess === 'function') {
options.onSuccess.call(this, obj);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
}
});
}(jQuery));
The plugin works fine as when I look at the output it is the data I expect. Below is an example of the initial attempt.
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
$.postFind({
data: {
database: 'dashboard',
collections: {
accountTypes: {
where: {status: true}
}
}
},
onSuccess: function (options) {
let dataArray = {};
$.each(options, function (key, val) {
dataArray[val._id.$oid] = val.type;
});
return dataArray;
}
})
}
}
});
In differnt iterations of attempting things I have been able to get the data back to the options but still not as a in the select.
After doing some poking around it looks like the createModal script in executing and creating the select before the AJAX call can return options. In looking at things it appears I need some sort of promise of sorts that returns the options but (1) I am not sure what that looks like and (2) I am not sure where the promise goes (in the plugin, in the createModal, etc.)
Any help you can provide would be great!
Update: Small mistake when posted, need to pass the results back to the original call: options.onSuccess.call(this, obj);
I believe to use variables inside your success callback they have to be defined properties inside your ajax call. Then to access the properties use this inside the callback. Like:
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
myOptions: options,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof this.myOptions.onSuccess === 'function') {
this.myOptions.onSuccess.call(this);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
It's not clear to me where the problem is without access to a functional example. I would start with a simplified version of what you want to do that demonstrates the proper functionality. My guess is the callbacks aren't setup exactly correctly; I would want to see the network call stack before making a more definitive statement. A few well-placed console.log() statements would probably give you a better idea of how the code is executing.
I wrote and tested the following code that removes most of the complexity from your snippets. It works by populating the select element on page load.
The HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select data-src='test.php' data-id='id' data-name='name'></select>
</body>
</html>
<html>
<script>
$('select[data-src]').each(function() {
var $select = $(this);
$select.append('<option></option>');
$.ajax({
url: $select.attr('data-src'),
data: {'v0': 'Alligator', 'v1': 'Crocodile'}
}).then(function(options) {
options.map(function(option) {
var $option = $('<option>');
$option
.val (option[$select.attr('data-id')])
.text(option[$select.attr('data-name')]);
$select.append($option);
});
});
});
</script>
And the PHP file:
<?php
header("Content-Type: application/json; charset=UTF-8");
echo json_encode([
[ 'id' => 0, 'name' => 'Test User 0' ],
[ 'id' => 3, 'name' => $_GET['v0'] ],
[ 'id' => 4, 'name' => $_GET['v1'] ]
]);
Here's a fiddle that also demonstrates the behavior.
I have some ajax requests in my jquery code. and my php server should decide what to do. but I'm beginner in web programming I don't know how to return the exact response .
<script>
$(document).ready(function () {
$('#subButton').click(function () {
var query = "query";
$.ajax({
type: 'POST',
url: 'info.php',
datatype: 'text',
data: {query: query},
complete: function (data) {
alert(data);// it returns the whole php page!
}
})
.done(function (data) {
alert("done");
})
.fail(function () {
alert("Posting failed.");
});
});
});
</script>
and there is my php code
<?php
if ( isset( $_POST[ 'music' ] ) ) {
echo "music";
}
if ( isset( $_POST[ 'query' ] ) ) {
echo "query";
}
if ( isset( $_POST[ 'url' ] ) ) {
echo "url";
}
?>
in this jquery I want just the word "query" not whole page. and also I want to know how to set it in html through some tags.
so we've found out why your php page is returning the whole script. It had a .html extension, not a .php one. Without the php extension the server would just send back the whole lot.
how to put it into a tag? Quite easy.
suppose you have a tag on your page like this (note the id):
<h2 id="main_heading">some heading</h2>
all you need to do is ask jquery to place the response inside it like this.
complete: function (data) {
// select the object with the right ID and change its innerHTML
$('#main_heading').html(data);
}
this will replace the contents of the <h2> with whatever comes back.
update
if youre having trouble, try putting a console.log call in and check it with the browsers javascript console, this should show you whats being sent back from the server.
like this:
complete: function (data) {
console.log(data);
// select the object with the right ID and change its innerHTML
$('#main_heading').html(data);
}
I want to use the tokenfield for bootstrap: http://sliptree.github.io/bootstrap-tokenfield/ but I can't seem to find any documentation on how to do it using AJAX. I have a .php file with json data like this {"Hello", "Helium", "Hell"} and I want it to be the autocomplete values. Please note that the .php file only returns values that are similar to what is being typed. Can anyone find a way to do this? Any help would be highly appreciated. I just wanna use that gorgeous bootstrap tokenfield to autocomplete tags and disallow autocomplete if the word's don't exist there.
Thanks.
You need to implement either autocomplete from jquery-ui or typeahead from twitter, and then apply specific options.
$('#activity_tag_tokens').tokenfield({
typeahead: {
prefetch: '/tags.json',
remote: '/tags.json?q=%QUERY',
}
});
Bootstrap tokenfield - typeahead autocomplete with remote call using ajax
Prerequisitics:
= stylesheet_link_tag 'sales_crm/tokenfield-typeahead.css'
= stylesheet_link_tag 'sales_crm/bootstrap-tokenfield.css'
%script{:src => "//code.jquery.com/ui/1.10.3/jquery-ui.js", :type => "text/javascript"}
= javascript_include_tag "sales_crm/bootstrap-tokenfield.js"
= javascript_include_tag "sales_crm/typeahead.bundle.min.js"
In HAML View File:
%input#tokenfield-typeahead.form-control.add_locality_data{:type => "text", :value => "", :identifier=> "Locality"}/
1) Initialize the BloodHound search engine
var engine = new Bloodhound({
remote: {
url: '/sales_crm/leads/get_lead_associated_info?query=%QUERY&model_class='+$('.add_locality_data').attr("identifier"),
filter: function (response) {
var tagged_user = $('#tokenfield-typeahead').tokenfield('getTokens');
console.log(tagged_user)
return $.map(response.leads, function (user) {
console.log(user)
var exists = false;
// console.log("velava saranam");
for (i=0; i < tagged_user.length; i++) {
if (user.value == tagged_user[i].value) {
var exists = true;
}
}
if (!exists) {
return {
value: user.value,
label: user.label
};
}
});
}
},
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace
});
engine.initialize();
2) Then Initialize tokenfield function
$('#tokenfield-typeahead').tokenfield({
delimiter: false,
typeahead: [
{
name: 'users',
displayKey: 'label',
source: engine.ttAdapter()
}
]
})
.on('tokenfield:createtoken', function (e) {
var existingTokens = $(this).tokenfield('getTokens');
if (existingTokens.length) {
$.each(existingTokens, function(index, token) {
console.log(token)
if (token.value === e.attrs.value) {
e.preventDefault();
}else{
console.log(e.attrs.value)
}
});
}else{
console.log(e.attrs.value)
}
});
It's OK ... I find the solution
$('#tokenfield1').tokenfield();
var mots_cles = "";
$.each(e.valeur_tableau_infos_tutoriel.Mots_cles, function (index,value){
mots_cles += value.mots_cles+',';
})
$('#tokenfield1').tokenfield('setTokens', mots_cles)
}
In my footer.php I have this code which i needed for my api references
<script type="text/javascript">
/** Override ajaxSend so we can add the api key for every call **/
$(document).ajaxSend(function(e, xhr, options)
{
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
});
</script>
It works fine in my project without any error but when I started working on file upload and I'm using ajaxfileupload to upload file, I got this error whenever i upload the file.
TypeError: xhr.setRequestHeader is not a function
xhr.setRequestHeader("KEY", "123456POIUMSSD");
Here is my ajaxfileuplod program code:
<script type="text/javascript">
$(document).ready(function() {
var DocsMasterView = Backbone.View.extend({
el: $("#documents-info"),
initialize: function () {
},
events: {
'submit' : 'test'
},
test: function (e) {
e.preventDefault();
var request = $.ajaxFileUpload({
url :'./crew-upload-file',
secureuri :false,
fileElementId :'userfile',
dataType : 'json',
data : {
'title' : $('#title').val()
},
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
refresh_files();
$('#title').val('');
}
alert(data.msg);
}
});
request.abort();
return false;
}
});
var x = new DocsMasterView();
});
</script>
Can anyone here fix my problem. Any suggestion/advice in order to solve my problem.
As I understand from your comments, setRequestHeaders works fine with regular ajax calls. At the same time it is not available when ajaxFileUpload is used. Most likely that is because transport method does not allow to set headers (for instance, in case when iframe is used to emulate upload of files in ajax style) . So, possible solution is to place a key into your form data:
$(document).ajaxSend(function(e, xhr, options)
{
if(xhr.setRequestHeader) {
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
else
options.data["<?php echo $this->config->item('rest_key_name');?>"] = "<?php echo $this->session->userdata('api_key')?>";
});
Note: I'm not sure if options.data is a correct statement, just do not remember structure of options object. If proposed code does not work - try to do console.log(options) and how
to get an object with data that should be posted (it might be something like options.formData, I just do not remember exactly)
And on server side you will just need to check for key in headers or form data.
I am using Codeigniter and trying to use the jQuery autocomplete with it. I am also using #Phil Sturgeon client rest library for Codeigniter because I am getting the autocomplete data from netflix. I am return correct JSON and I can access the first element with
response(data.autocomplete.autocomplete_item[0].title.short);
but when I loop through the results
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short)
}
it acts like a string. Lets say the result is "Swingers", it will return:
Object.value = s
Object.value = w
Object.value = i
and so on.
the js:
$("#movies").autocomplete({
source: function(request, response) {
$.ajax({
url: "<?php echo site_url();?>/welcome/search",
dataType: "JSON",
type:"POST",
data: {
q: request.term
},
success: function(data) {
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
}
});
}
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
$(ul).attr('id', 'search-autocomplete');
return $("<li class=\""+item.type+"\"></li>").data( "item.autocomplete", item ).append(""+item.title+"").appendTo(ul);
};
the controller:
public function search(){
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// set var equal to results
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'));
//$this->rest->debug();
//$json_data = $this->load->view('nice',$data,true);
//return $json_data;
echo json_encode($netflix_query);
}
the json return
{"autocomplete":
{"autocomplete_item":[
{"title":{"short":"The Strawberry Shortcake Movie: Sky's the Limit"}},
{"title":{"short":"Futurama the Movie: Bender's Big Score"}},
{"title":{"short":"Daffy Duck's Movie: Fantastic Island"}}
...
any ideas?
thanks.
there are some console logs with the return
the url
in, as you've noticed, doesn't do what you'd like with arrays. Use $.each
As far as I know, for (property in object) means that you want to access each of its properties rather than accessing them via the index. If you want to access them via the index, you probably want to use the standard for loop.
for (i = 0; i <= 10; i++) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
or if you still want to use your code, try this:
for (i in data.autocomplete.autocomplete_item) {
response(i.title.short);
}
I haven't test them yet but I think you have the idea.
ok I figured out the correct format that I need to send to the autocomplete response method:
the view
$("#movies").autocomplete({
minLength: 2,
source: function(request, response) {
$.post("<?php echo base_url();?>welcome/search", {q: request.term},
function(data){
//console.log(data);
response(data);
}, 'json');
}
});
the controller:
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// Pull in an array
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'),'json');
$json = array();
foreach($netflix_query->autocomplete->autocomplete_item as $item){
$temp = array("label" => $item->title->short);
array_push($json,$temp);
}
echo json_encode($json);
what was needed was to send back to the view an array of objects. Thank you guys for all your answers and help!!