I am getting the data from ajax and filling the select with it. Now How can make default selections in this.
Here are my ajax
var productLists =[];
$.when(http_get('admin/offer/data/sync')).then(function(response){
//returns a products array
$.each(response.products, function(i, item){
var product = {};
product['id'] = item.id;
product['text'] = item.product_name;
productLists[i] = product;
});
});
$('#sel_product').select2({
data: productLists
});
To get seleted values I can do another ajax list
Or I can print <otpion value="" selected="selected"> in the html from php.
So here how do i make default selection with select2?
You need to move the call to .select2() into the callback, so it will be initialized after the data is retrieved.
var productLists = [];
$.when(http_get('admin/offer/data/sync')).then(function(response){
//returns a products array
$.each(response.products, function(i, item){
var product = {};
product['id'] = item.id;
product['text'] = item.product_name;
productLists[i] = product;
});
$('#sel_product').select2({
data: productLists
});
});
Related
I am building a form to process text input, multiple check boxes and 4 images. currently I am to process the check boxes using the each function to put all the values of the checkboxes in an array before sending it through ajax. Now the problem is that I can't send the images with ajax too. And also I can't access the images too.
Code:
$(document).ready(function () {
//alert("this page works");
$('#uploadProperty').on('submit',function (e){
e.preventDefault();
var hname = $('#hname').val();
var location = $('#location').val();
var htype = $('#htype').val();
var rooms = $('#rooms').val();
var price = $('#price').val();
var hdetails = $('#hdetails').val();
var feature = [];
$('.feature').each(function() {
if($(this).is(":checked")){
feature.push($(this).val());
}
});
// if (feature.length == 0)
// alert("Select atleast 1 Feature");
// else{
// feature = feature.toString();
// alert(feature);
// }
var file1 = $('#file4').val();
//alert(file1);
$.ajax({
url : 'core/upload.php',
type : 'POST',
data : new FormData(),
contentType : false,
processData : false,
success : function (ep){
alert(ep);
}
});
});
});
You need to upload images first via ajax ( ex: http://hayageek.com/docs/jquery-upload-file.php ) and after make another ajax for the form fields. But you need an ID link between Property and images. you cand add an empty record and remember the mysql_insert_id to make update with the form fields and insert images or update ( depend how is your table structure )
So if i got it right, you want to fill the FormData object. Because currently it's empty.
You can use append method:
var formData = new FormData();
var $myField = $('#myField');
formData.append('myField', $myField.val());
To append file:
var $fileField = $('#fileField');
var myFile = $fileField.get(0).files[0];
formData.append('myFile', myFile);
To append multiplie files you should set the name properly:
formData.append('myFile[]', myFileFirst);
formData.append('myFile[]', myFileSecond);
Check it here: Uploading multiple files using formData()
Also, you can grab the whole form data through constructor:
var form = $('form').get(0);
var formData = new FormData(form);
In server side I give table data from MySql and I send it with json_encode to JQuery:
<?php
include 'DB.php';
$result20 = mysql_query("SELECT * FROM Gallery WHERE Section = 'Chosen' AND ID = 19");
$array20 = mysql_fetch_row($result20);
$result19 = mysql_query("SELECT * FROM Gallery WHERE Section = 'Chosen' AND ID = 19");
$array19 = mysql_fetch_row($result19);
$data = array();
$data['Div20'] = $array20;
$data['Div19'] = $array19;
echo json_encode($data);
?>
json_encode export this arrays: {"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]}
but, in client side I need use a loop for use all arrays in events. When I use for, it's not work with multiple arrays, how to do it?
$(function() {
$.get('data.php' ,function(response)
{
var data = jQuery.parseJSON(response);
var array;
for(array in data)
{
var ImageID = data.array[0];
var ImageSrc = data.array[1];
$('#'+ImageID ).click(function(){
//some codes
})
}
})
})
Try this
$(function() {
$.get('data.php' ,function(response) {
var data = jQuery.parseJSON(response);
$.each( data, function( key, value) {
var ImageID = value[0];
var ImageSrc = value[1];
$("#"+ImageID ).click(function(){
//some codes
})
})
})
It will work if you add # to your imageid like,
$('#'+ImageID ).click(function(){
//some codes
});
I've tried some code for you,
var json={"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]};
for(div in json){
ImageID=json[div][0];
ImageSRC=json[div][1];
$('#'+ImageID)
.attr('src',ImageSRC)
.click(function(){
alert(this.src);
});
}
Demo
Replace .array with [array] in your for loop:
for(array in data)
{
var ImageID = data[array][0];
var ImageSrc = data[array][1];
}
"array" is not an attribute of your json object, it's just an argument of your for ... in loop. So you must use it as a dynamic value. Moreover you missed using a # to target properly the element id.
var data = {"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]};
for(array in data)
{
var ImageID = "#"+data[array][0];
var ImageSrc = data[array][1];
$(ImageID).on("click",function(){
//some codes
});
};
Avoid using $.each() loop as someone recommended above, jQuery loops are usually slower than native loops.
Try this..
$(function() {
$.get('data.php' ,function(response)
{
var data = jQuery.parseJSON(response);
$.each(data,function(k, v){
var ImageID = v[0];
var ImageSrc = v[1];
$('#'+ImageID ).click(function(){
//some codes`enter code here`
})
})
})
This is the language select box.
<select name="lang" id="lang" browser="Indicated by the browser">
<option value="en">English</option>
<option value="fr">French</option>
<option value="ch">Chinese</option>
<option value="sp">Spain</option>`enter code here`
</select>
This is script i have written.
<script type="text/javascript">
jQuery(document).ready(function() {
loadBundles('en');
jQuery('#lang').change(function() {
var selection = jQuery('#lang option:selected').val();
loadBundles(selection != 'browser' ? selection : null);
jQuery('#langBrowser').empty();
if(selection == 'browser') { jQuery('#langBrowser').text('('+jQuery.i18n.browserLang()+')');
}
});
});
function loadBundles(lang) {
jQuery.i18n.properties({
name:'Messages',
path:'bundle/',
mode:'both',
language:lang,
callback: function() {
updateExamples();
}
});
}
function updateExamples() {
var ex1 = 'Firstname';
var ex2 = 'Lastname';
var ex3 = 'Youremail';
var ex4 = 'Reenteremail';
var ex5 = 'Newpassword';
var ex6 = 'Dateofbirth';
var ex7 = 'Signup';
var ex8 = 'Itsfreeandalwayswillbe';
var ex9 = 'Birthlabel';
var ex10 = 'Termslabel';
var ex11 = 'Summarylabel';
var ex12 = 'PersonalLabel';
var ex13 = 'Interestlabel';
var ex14 = 'Addlabel';
var ex15 = 'Editlabel';
var ex16 = 'Deletelabel';
var spreadsheet_label = 'Spreadsheetlabel';
var invite_google_label = 'Invitegooglelabel';
var invite_facebook_label = 'Invitefacebooklabel';
var upload_label = 'Uploadlabel';
var subBut='Submit';
var dialogTitle = 'DTitle';
jQuery("#first_name_label").text(eval(ex1));
jQuery("#first_name_label1").text(eval(ex1));
jQuery("#last_name_label").text(eval(ex2));
jQuery("#last_name_label1").text(eval(ex2));
jQuery("#email_label").text(eval(ex3));
jQuery("#email_label1").text(eval(ex3));
jQuery("#reenter_email_label").text(eval(ex4));
jQuery("#new_password_label").text(eval(ex5));
jQuery("#date_of_birth_label").text(eval(ex6));
jQuery("#date_of_birth_label1").text(eval(ex6));
jQuery("#sign_up").text(eval(ex7));
jQuery("#label1").text(eval(ex8));
jQuery("#button").val(eval(ex7));
jQuery("#birth_label").text(eval(ex9));
jQuery("#terms_label").text(eval(ex10));
jQuery("#summary_label").text(eval(ex11));
jQuery("#personal_label").text(eval(ex12));
jQuery("#interest_label").text(eval(ex13));
jQuery("#add_label").text(eval(ex14));
jQuery("#edit_label").text(eval(ex15));
jQuery("#delete_label").text(eval(ex16));
jQuery("#spreadsheet_label").text(eval(spreadsheet_label));
jQuery("#invite_google_label").text(eval(invite_google_label));
jQuery("#invite_facebook_label").text(eval(invite_facebook_label));
jQuery("#upload_label").val(eval(upload_label));
jQuery("#submit_button").val(eval(subBut));
jQuery("#ui-dialog-title-dialog").text(eval(dialogTitle));
}
</script>
Everything is working fine for the labels. But in the case of dynamic drop down i got problem. How to localize the dynamic drop down data when the user selected the language.
The data in the drop down is coming from the database.
I have a language select drop down box, after selecting one language from dropdown list am able to change the text filed names and all other text in the language that is selected.
At the same time i have another dropdown, in that data is generated dynamically form the database. After the user selecting the language from dropdown list i have to change the data in this drop down list also. please suggest me if u have any idea.
Thank you.
I suggest you to use ajax for this issue.
You can bind ajax to first drop down and then fill secound dropdown by data which you get from back-end.
You can do something like this :
<select name='lang'>
<option value='eng'>Eng</option>
<option value='french'>French</option>
</select>
<!-- below div is another div whose data changes as per the language selected -->
<div id="another_div"></div>
JS:
$("select[name='lang']").live({
change: function(e){
var selected_lang = $("select[name='lang'] option:selected").html();
data = {}
data['selected_lang'] = selected_lang;
$.ajax({
url: "required url",
data: data,
success: function(res){
$("#another_div").text(res); // if result is a direct text sent from server
// or
$("#another_div").text(res.content); //if result is an object with the required content present in the key 'content'
},
error: function(err){
alert("error occured");
}
});
}
});
I would use one of the many Cascading jQuery Dropdowns:
http://www.ryanmwright.com/2010/10/13/cascading-drop-down-in-jquery/
I am trying to make autosuggest in Jquery,ajax and json to search cities when user register to website.
So far I am able to get results from database.And i appended to list.but now i need to select data using up down and enter keys.
Key down event is adding class to first city. But I want to loop through all results using key up and down and add value to city textbox if user hits enter. I limit data by 5 in php so 5 results are coming in list item.
Here is my code:
$('#city').keyup(function (event) {
var input_query = $(this).val();
$.post("get_city.php", {
"query": input_query
}, function (data) {
$('#cityres').html("");
$.each(data, function (i, item) {
$('#cityresults').append("<li>" + item.city + "</li>");
});
}, "json");
//below code is for key event
var key = gtKeycode(event);
if (key == 40) {
// I am not sure i need to do this way
$('li').first().addClass('SelectedCity');
}
});
function gtKeycode(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
return code;
}
i think i have now the solution for your problem hope this will help you..!
I made a php file that echo out json encode just list this:
//PHP "action.php?action=show"
e.g $option[] = array(
'option0'=>".Choose an option",
'option1'=>'somepage1',
'option2'=>'somepage2',
'option3'=>'somepage3');
echo json_encode(array('options'=>$option));
I made up html that will be the handler of the output, then will append
<select class="myoptions">
</select> | <span class="optcap"></span>
JS
function selectedOption()
{
var myoptions = $(".myoptions");
$.ajax({
type:'GET',
url:'action.php?action=show',
dataType:'JSON',
success:function(data){
if(data.s==1){
myoptions.empty();
$.each(data.options, function(x,val){
myoptions.append("<option class='option' value='"+val.option0+"'>"+val.option0+"</option>"
+"<option class='option' value='"+val.option1+"'>"+val.option1+"</option>"
+"<option class='option' value='"+val.option2+"'>"+val.option2+"</option>"
+"<option class='option' value='"+val.option3+"'>"+val.option3+"</option>");
});
}
}
});
}
$(document).ready(function(){
selectedOption();
$(".myoptions").keyup(function(){
var option = [];
$("option.option:selected").each(function(x){
option[x] = $(this).val();
});
$(".optcap").html("["+option+"]");
});
});
How can I send multiple values to be picked up like this using JSON?
foreach($_POST['listItem'] as $key => $values){
list($eventDate, $eventTitle) = $values;
}
At the moment the values are sent as follows. But this doesn't appear to work properly as it is only sending some of the string. I also can't figure out where/how to send the caltitle value.
This is sending me crazy. Any help would be great.
var txt = $("#listbox");
var caltitle = copiedEventObject.title
var dtstart = $.fullCalendar.formatDate(copiedEventObject.start, 'yyyyMMdd');
var txt = $('#listbox');
txt.append("<li class ='listItem'> " + dtstart + "</li>")
// remove the element from the "Draggable Events" list
$(this).remove();
}
});
$('#calendarform').submit(function(e) {
var form = $(this);
var listItems = $('.listItem');
listItems.each(function(index){ //For each event do this:
var listItem = $(this);
$("<input type='hidden'/>").val(listItem.text()).appendTo(form).attr('name', 'listItem[' + index + ']');
});
//Get text information from elements
});
EDIT:
(using JSON)
$('#calendarform').submit(function(e) {
var form = $(this);
var going_to_be_json = [];
list.each(function(i, item) {
going_to_be_json.push({
'id':'test',
'title': 'test'
});
});
$('#stuff').val( JSON.stringify(going_to_be_json) );
});
Prepare the data into an array of objects then convert that array to JSON using JSON.stringify() and set the hidden form value to said string (or use XHR to submit it to the server).
Here is a very limited example of how to prepare the data:
var going_to_be_json = [];
list.each(function(i, item) {
going_to_be_json.push({
'id':item.id,
'title': item.title,
'date': (new Date()).now()
});
});
hidden_form_element.val( JSON.stringify(going_to_be_json) );
and on the server
<?php
$json_data_string = $_POST['hidden_form_field_containing_json_data']; // sanitize however
$array_data = json_decode($json_data_string);
More can be ready about JSON (Javascript Object Notation) from json.org and the Tag Wiki (although the tag wiki just shows you more examples and links)
it seems you needed a little more direction. I was hoping you wouldn't just copy and paste what I had and you would read and attempt to understand what it is doing....
$('#calendarform').submit(function(e) {
var form = $(this),
listItems = $('.listItem'),
data = [],
hidden = $('<input />'); // create a hidden field for the form.
// or just select the hidden form element from the page
hidden[0].type = 'hidden'; // set the type
hidden[0].name = 'some_name_for_php_to_recognize'; // and name
listItems.each(function(i,el){
data.push({'index': i, 'text': $(el).text()});
});
hidden.val(JSON.stringify(data));
$(this).append(hidden); // not needed if the hidden element is already in the DOM
});
send it with jQuery Post or Get method and fetch it by php you can send multiple values
use $.post or $.get