How to create jquery array from ajax data? - php

I wanna create array from ajax response. I took array from ajax and i have to create dynamic data for chips
materializecss autocomplete
response from ajax
var tag = '';
$(document).on('keyup', '.tags', function() {
var _this = $(this).val();
if(_this.length > 1) {
$.ajax({
url: '/story/searchTags',
type: 'POST',
dataType: 'JSON',
data: {
tag: _this
},
success: function(tags) {
tag = tags;
}
});
}
});
$('.chips-placeholder').chips({
placeholder: lang_('Your tag'),
secondaryPlaceholder: '+ tag',
autocompleteOptions: {
// I need data like this from response
data: {
'Google', null
'Googol', null
},
limit: 5,
minLength: 2
}
});
<div class="chips chips-placeholder chips-autocomplete input-field" style="background:#fff">
<input class="input tags" placeholder="tag" autocomplete="off" />
</div>
that's my code
Finally, thanks to #Vel to find right answer.
jsfiddle - work code

You need to do like this.
var tag = '';
$(document).on('keyup', '.tags', function() {
var _this = $(this).val();
if(_this.length > 1) {
/*$.ajax({
url: '/story/searchTags',
type: 'POST',
dataType: 'JSON',
data: {
tag: _this
},
success: function(tags) {
tag = tags;
}
});*/
// ['google', 'googol'] <- this array I take from ajax
tag = ['google', 'googol'];
var obj = {};
$(tag).each(function (index, value) {
obj[value] = null;
});
$('.chips').chips({
secondaryPlaceholder: '+ tag',
autocompleteOptions: {
data:obj,
}
});
}
});
fiddle link

Related

pass two variables with ajax after push to array

I'm trying to make this code to work but it look I'm doing something wrong when passing the two variables with ajax, please help, here is the code, basically is a drag and drop code to move items between boxes and organize inside each box.
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data,
page: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
You can make it using this way:
$('.spremiUredivanje').click(function(){
ai = document.getElementById('ai_mjerila_edit').value;
broj_mjerila = document.getElementById('broj_mjerila_edit').value;
adresa = document.getElementById('adresa_edit').value;
stanje = document.getElementById('stanje_edit').value;
$( "#datum_edit" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
datum = document.getElementById('datum_edit').value;
operater = document.getElementById('operater_edit').value;
$.ajax({
url: 'test.php',
type: 'POST',
data: {
post1: broj_mjerila, post2: adresa, post3:stanje, post4: datum, post5: operater, post6:ai
},
beforeSend: function(){
$('#loaderEdit').show();
},
So your php file should look like this:
$broj_mjerila = $_POST['post1'];
$adresa = $_POST['post2'];
$stanje = $_POST['post3'];
$datum = $_POST['post4'];
$operater = $_POST['post5'];
$ai = $_POST['post6'];
To control your response use success inside ajax call:
success: function(response) {
if(response == 1) {
//alert("success!");
$('#editUspjesan').show();
$('#loaderEdit').hide();...
Can you explain your requirement clear. Are you trying to get page number and id in 2 separate array?
// If page no and id need to be in separate array
var position = [], pages = [];
$('.sortable-list>li').each(function() {
position.push($(this).attr("id"));
pages.push($(this).attr("pagenum"));
});
updateOrder(position, pages);
function updateOrder(position, page) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: position,
page: page
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
// If page no and id can be combined use objects
var selectedData = [];
$('.sortable-list>li').each(function() {
selectedData.push({id: $(this).attr("id"), page: $(this).attr("pagenum")})
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data.id,
page: data.pagenum
},
dataType:'json',
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
Let's try this one

loop Ajax Response in select Option tag

i have to select multiple tests and date and when clicked on submit based on the test,laboratory names are loaded in select option
Ajax script
$('[name=submits]').click(function(e)
{
e.preventDefault();
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
var testdate = $("#appointmentdate10").val();
//here make your ajax call to a php file
$.ajax({
type: "POST",
url: "http://localhost/refer/index.php/details",
data: { laboratory_tests: array, testdate: testdate },
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
for (i=0;i<data.length;i++)
{
var id = data[i]['laboratory_id'];
var val = data[i]['laboratory_name'];
selOpts += "<option value='"+id+"'>"+val+"</option>";
}
$('#yourSelect').append(selOpts);
}
});
});
Ajax success response is:
[
{"laboratory_id":"19","laboratory_name":"ghc","laboratory_address":"cgc","laboratory_place":"jhggj","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"20","laboratory_name":"BBNB","laboratory_address":"sdfds","laboratory_place":"sdfsd","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"22","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"}
]
html
<select class="form-control" id="yourSelect">
</select>
but i am not able to display in select tag
$.ajax({
url: config.routes.profitsReport,
type: "POST",
dataType: 'json',
success: function (result) {
$.each(result, function (i, value) {
$('#category_profit').append('<option id=' + JSON.stringify(value.id) + '>' + JSON.stringify(value.name) + '</option>');
});
},
error: function (request, status, error) {
alert(request.statusText + "[" + request.status + "]");
alert(request.responseText);
$('button#form_salesReport_button').html(config.messages.searchReport);
}
});
Try to loop through the result like this:
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
$.each(data, function(k, v)
{
var id = data[k].laboratory_id;
var val = data[k].laboratory_name;
selOpts += "<option value='"+id+"'>"+val+"</option>";
});
$('#yourSelect').append(selOpts);
}
You can loop
[
{"laboratory_id":"19","laboratory_name":"ghc","laboratory_address":"cgc","laboratory_place":"jhggj","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"20","laboratory_name":"BBNB","laboratory_address":"sdfds","laboratory_place":"sdfsd","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"22","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"}
]
via
var options = "";
for (let item in array) {
options += `<option value=${item.id}>${item.laboratory_name}</option>`;
}
document.getElementById("yourSelect").innerHTML = options;
If it's a String, you can convert it to an array via JSON.parse.
If you are expecting json data from ajax request then you need to require to add dataType as json.
$('[name=submits]').click(function(e)
{
e.preventDefault();
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
var testdate = $("#appointmentdate10").val();
//here make your ajax call to a php file
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/refer/index.php/details",
data: { laboratory_tests: array, testdate: testdate },
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
for (i=0;i<data.length;i++)
{
var id = data[i]['laboratory_id'];
var val = data[i]['laboratory_name'];
selOpts += "<option value='"+id+"'>"+val+"</option>";
}
$('#yourSelect').append(selOpts);
}
});
});

Passing Variable Value from PHP to Ajax and Changing Attribute Value in HTML

My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}

jQuery use ajax and json to switch page with button

Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }

Select2 in a complex form as abstract class

I need to use the select2 object in my form. This is my form
http://i.stack.imgur.com/jVILq.jpg
There are many select html objects.
For instance If I would like to change the Customers select box into a Select2 object I have written this little snipped of code posted at jsfiddle.net but I cannot create a copy of this function for each select because it too difficult to maintain.
How have I to abstract it?
I have posted a sample here: http://jsfiddle.net/GcJgU/7/
I have already found a potential solution from the user Flip but it is not complete because I need to apply this JQuery object to all the input hidden html objects in the page.
This is an example:
$(".select2").select2({
ajax: {
url: $(this).attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = $(this).attr("field-id");
var fieldname = $(this).attr("fields-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
formatResult: function (object, container, query) {
console.log(object);
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = $(element).attr("field-id");
var fieldname = $(element).attr("fields-data");
$.ajax($(element).attr("url-searchid") + "/term/" + id, {
dataType: "json"
}).done(function (items) {
var data = {
id: items[0][fieldid],
text: items[0][fieldname]
};
callback(data);
});
}
});
Seems that $(this).attr("url-search") is not read and the search process doesn't start. I don't understand why.
Thanks guys
function select2Factory(select2) {
return {
minimumInputLength: 3,
ajax: {
url: select2.attr("callback-url"),
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var $this = $(this);
var id = select2.attr("field-id");
var fieldname = select2.attr("field-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var fieldname = select2.attr("field-data");
$.ajax("/admin/customers/searchbyid/term/" + id, {
dataType: "json"}).done(function(items) {
var data = {id: items[0][fieldid], text: items[0][fieldname] };
callback(data);
});
}
}
}
$el = $("#customer_id");
$el.select2(select2Factory($el));
I have solved in this way thanks to Flip:
http://jsfiddle.net/GcJgU/10/
HTML:
<input type="hidden" id="customer_id" title="" required="1" class="form-control select2 select2-offscreen" url-searchid="/admin/customers/searchbyid" url-search="/admin/customers/search" fields-data="lastname firstname ( company )" field-id="customer_id" value="12" name="customer_id" tabindex="-1">
JQUERY:
function select2Factory(select2) {
return {
ajax: {
url: select2.attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = item[mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
results.push({
id: item[id],
text: output
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
$.ajax(select2.attr("url-searchid") + "/term/" + id, {
dataType: "json"}).done(function(items) {
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = items[0][mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
var data = {id: items[0][fieldid], text: output };
callback(data);
});
}
};

Categories