Jquery - split returned array(Json) - javascript

ajax i have this snippet:
$("input#search_field").keyup(function(){
var searchText = $("input#search_field").val()
if(searchText.length > 1){
$.ajax({
url: 'search.php',
data: {data: JSON.stringify(searchText)},
type: 'POST',
dataType: "json",
success: function (data) {
if(data.result == 1) {
console.log(data.error);
}
if(data.result == 0) {
console.log(data.error)
}
}
});
}
});
When data.result is = 1, than the returned data.error is an array, in my console:
["string"]
My question is how get every string in my array into a different variable so i can use it later?
Because returned array could be also:
["string","string2","string3"]
Anyone knows?? Greetings!

I split the array as folow
var string = $('#uInput').val();
var array = string.split('\n');
for($i = 0; $i < array.length; $i++){
var dateAndText = array[$i].split(',');
$('#spota').append(dateAndText[0] + '<br>');
$('#spotb').append(dateAndText[1] + '<br>');
Hope this helps.

Related

JQuery Ajax loop delay

i am trying to make a delay in my ajax data so the loop become a little bit slower !
and here is my code
$(document).ready(function (){
$('#button').click(function(){
$('#hide').show();
var data = $('#textarea').val();
var arrayOfLines = data.split("\n");
var track = JSON.stringify(arrayOfLines);
var item = "";
var lines = $('#textarea').val().split('\n');
here is the loop
for (var i = 0; i < lines.length; i++) {
item = lines[i];
$.ajax({
type: 'GET',
url: 'cookie.php',
dataType: 'html',
data: 'data=' + item+'&cookie='+track,
success: function(msg){
$('#results').append(msg);
}
});
}
});
Using recursion, you could put in a function sendToServer and pass through the array lines, starting index 0. The function will run from 0 to lines.length. This way you won't DDOS your server :)
If you really need some kind of arbitrary delay, you can include a timeout on the sendToServer function call - in the example it is set to 5 seconds.
var sendToServer = function(lines, index){
if (index > lines.length) return; // guard condition
item = lines[index];
if (item.trim().length != 0){
$.ajax({
type: 'GET',
url: 'cookie.php',
dataType: 'html',
data: 'data=' + item+'&cookie='+track,
success: function(msg){
$('#results').append(msg);
setTimeout(
function () { sendToServer(lines, index+1); },
5000 // delay in ms
);
}
});
}
else { sendToServer(lines, index+1); }
};
sendToServer(lines, 0);
Don't send request to server in for loop. It can take down the server. Instead of what you did , you can do this :
for (var i = 0; i < lines.length; i++) {
item = lines[i];
}
$.ajax({
type: 'GET',
url: 'cookie.php',
dataType: 'html',
data: 'data=' + item+'&cookie='+track,
success: function(msg){
$('#results').append(msg);
}
});
Use like this:
var timeDelay = 5000;
setTimeout(Function, timeDelay);

filter by a key/value from json Array

here is my code, and i would like to only display items which has "assistance" as tag and no the other. I really don't know how can i do that.
function displayall(newid){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/"+newid+"/tickets/requested.json",
type: 'GET',
cors: true,
dataType: 'json',
contentType:'application/json',
secure: true,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
var sortbydate = data.tickets.sort(function(a,b){ return new Date(b.created_at)- new Date(a.created_at); });
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var ticketid = data.tickets[i].id;
var tag = data.tickets[i].tags[0];
$("#mylist").append('<li class="row col-md-12 listing" id="newlist" value="'+ticketid+'" onclick="ticketcontent('+ticketid+","+newid+')">'+ '<span class="class_'+status+' otherClasses">' + status + '</span>'+'<div class="identifiant fixed col-md-2">'+" #"+ ticketid +'</div>'+'<div class="identifiant col-md-2">'+tag+'</div>'+'<div class="identifiant col-md-4">'+mytitle +'</div>'+'<div class="identifiant datefixed col-md-2">'+created+'</div>'+'</li>');
}
}
})
}
and if i do console.log(data.ticket[i]) this is what i get:
What you're looking for is:
var filteredTickets = data.tickets.filter(function(ticket) {
return ticket.tags.indexOf('assistance') >= 0;
});
Try using data.tickets.filter():
data.tickets = data.tickets.filter(function(ticket){
return ticket.tags[0] === 'assistance';
});

how receive json in jquery success method and use that json to build html content

I am working on an java spring application that requires the controller to return json. By receiving that json in jquery success method, I want to make html out of it.
controller returns a json like below:
return "[{\"Id\": \"1\", \"Name\": \"Apples\"}, {\"Id\": \"2\", \"Name\":\"Mangoes\"}]";
jquery used to hit that controller and then receive the json in success method:
var content;
$(document).ready(function(){
$("#submitButton").click(function(e){
var formData = getFormData();
if(formData!=false){
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {jsonData: JSON.stringify(formData)},
dataType: 'json',
success: function(response){
for (var x = 0; x < response.length; x++) {
content = response[x].Id;
content += "<br>";
content += response[x].Name;
content += "<br>";
$(content).appendTo("#Fruits");
}
},
timeout: 10000,
error: function(xhr, status, err){
if(response.status=='timeout')
{
alert('Request time has been out','');
}
console.log(status,err);
}
}); }
});
});
below is the HTML div where I want to use above content to append:
<div id="Fruits">
fruits :
</div>
it is reaching to the controller. and also returning json. but I am not able to use that json.
Replace your for loop with
for (var x = 0; x < response.length; x++)
{
content = "<div class='fruit'><div>" + response[x].Id + "</div>";
content += "<div>" + response[x].Name + "</div></div>";
$(content).appendTo("#Fruits");
}
Your error message correctly explained that you were not appending the correct expression into the fruits
try below code
$(document).ready(function() {
$("#submitButton").click(function(e) {
var formData = getFormData();
if (formData != false) {
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {
jsonData: JSON.stringify(formData)
},
dataType: 'json',
success: function(response) {
for (var x = 0; x < response.length; x++) {
var fContent = $("<div></div>");
var id = $("<span></span>").text(response[x].Id);
var name = $("<span></span>").text(response[x].Name);
fContent.append(id)
fContent.append(name);
$("#Fruits").append(fContent);
}
},
timeout: 10000,
error: function(xhr, status, err) {
if (response.status == 'timeout') {
alert('Request time has been out', '');
}
console.log(status, err);
}
});
}
});
});

Angular ng-grid : how to load multiple api data?

I have a 'ng-grid' table that have 2 types of data source. One is from my database using a function called getContributors(), and another one is from a list of api(s).
The getContributors function is like the default function in the ng-grid tutorial.
function getContributors() {
var deferred = $q.defer();
$http.get(contributorsFile)
.then(function(result) {
contributors = result.data;
deferred.resolve(contributors);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
My method for loading the multiple api data is to load the database data first, and then after all the database data is all loaded it will make a request to the api using a parameter from the database data
var ajax_wait_count = 0;
gridService.getContributors().then(function(data) {
// Looping each data with angular.forEach()
angular.forEach(data, function(value, key){
var this_uid = value['uid'];
// if(ajax_wait_count==0)
// {
$timeout(function(){
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getrank.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['ranked_tier'] = json;
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlevel.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['level'] = json['level'];
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getsummonercreate.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != 0) {
var date_c = json[0]['create_date'];
date_c = date_c.replace(' ', 'T');
new_date = new Date(date_c);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['summoner_create_date'] = datestring;
}
else if (json == 0) {
data[key]['summoner_create_date'] = "";
}
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlastplayed.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != "null" && json != null) {
var datedatas = json;
var datearray = [];
var thedatestr = "";
var loopidx = 1;
now_date = new Date();
now_date.setHours(0);
now_date.setMinutes(0);
now_date.setSeconds(0);
now_date.setDate(now_date.getDate() - 2);
next_date = new Date();
next_date.setHours(23);
next_date.setMinutes(59);
next_date.setSeconds(59);
// next_date.setDate(next_date.getDate());
angular.forEach(datedatas, function (value3, key3) {
datearray[key3] = parseInt(value3['createDate']);
});
datearray.sort();
datearray.reverse();
var count_played_today = 0;
angular.forEach(datearray, function (value2, key2) {
if (loopidx == 1) {
thedatestr = value2;
}
date_compare = new Date(parseInt(value2));
if (date_compare.getTime() >= now_date.getTime() && date_compare.getTime() < next_date.getTime()) {
count_played_today++;
}
loopidx++;
});
// var date_c = json[0]['create_date'];
// date_c = date_c.replace(' ','T');
var dateinsert = parseInt(thedatestr);
new_date = new Date(dateinsert);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['last_played_date'] = datestring;
this_date = new Date();
date_diff = dateDiff(new_date.toString(), this_date.toString());
data[key]['last_played_date_qty'] = date_diff.d + " days " + date_diff.h + " hours " + date_diff.m + " minutes";
data[key]['count_played'] = count_played_today;
}
else if (json == "null" || json == null) {
data[key]['last_played_date'] = "";
data[key]['last_played_date_qty'] = "";
data[key]['count_played'] = 0;
}
},
error: function () {
// alert("Error");
}
});
},1500);
ajax_wait_count=0;
// }
ajax_wait_count++;
});
$scope.myData = data;
});
Now, the problem that emerges is :
The loading time for the api data is very long, and because of ajax asynchronous request, I can't make a loading function to delay the data
It appends the api data after the database data, which sometimes confuses the user whether the data is loaded or not
Sometimes in Chrome, the request is too much and it returns "err_insufficient_resources"
My question is,
Can my method of loading the api data be changed so it will make the loading time much faster and more efficient?
To make users less confused about the high amount of data, how can I make the progressbar (angular progress bar) wait for the database data + the api (AJAX) data?
Thank you in advance

Sending Arrays from View to Controller in MVC

I am trying to send the following values from view to controller
var ParamAliasArray = new Object();
for (var i = 1; i <= 1; i++) {
ParamAliasArray[i] = $("#txtParamAlias" + i).val();
}
var ParamValueArray = new Object();
for (var i = 1; i <= 4; i++)
{
ParamValueArray[i] = new Array();
for (var j = 1; j <= 1; j++) {
ParamValueArray[i][j] = $("#txtParamValue" + i).val();
}
}
one is 1D array and other is 2D array I am passing as
jQuery.ajaxSettings.traditional = true
$.ajax({
type: 'Post',
dataType: 'json',
url: 'Register/GetRegDataFromuser',
data: JSON.stringify({ GloabalAppID: GlobalAppID,
TransactionID: TransactionID,
OwnerID: OwnerID,
ParamAliasArray: ParamAliasArray,
ParamValueArray: ParamValueArray }),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
console.debug(data);
},
error: function (data) {
console.debug(data);
}
});
I have written Action method as in
public ActionResult GetRegDataFromuser(int GloabalAppID, int TransactionID, string OwnerID, string[] ParamAliasArray, string[][] ParamValueArray)
{
---some logic--
}
So,I am not able to pass the array to the action method from View..Please help me out.
Thanks in advance.
you need to add ParamValueArray[i][j]=new Array(); this line.

Categories