Reload web page on mysql table update using ajax call - javascript

that is my ajax call:
function getEle(id) {
var element = new Array();
$.ajax({
async: false,
url: "map.php",
type: "POST",
dataType: 'json',
data: {
"id": id
},
success: function (data) {
var resultArr = new Array();
var resultArr = data;
var state = new Array();
for (var s = 0; s < resultArr.length; s++) {
state[s] = resultArr[s];
element[s] = id;
element[s] = state[s];
}
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
return element;
}
Have some solution kindly post it..... thanks in advance....

you can use window.location in javascript.
success: function (data) {
var resultArr = new Array();
var resultArr = data;
var state = new Array();
for (var s = 0; s < resultArr.length; s++) {
state[s] = resultArr[s];
element[s] = id;
element[s] = state[s];
}
window.location = "yourpage address";// add this line
}

Related

Fetching data from multiple api

I need to fetch data from multiple API and display them in the table.
What I came up with is:
var req = $.ajax({
url: "....linkhere",
dataType: 'jsonp'
});
var req = $.ajax({
url: "....linkhere1",
dataType: 'jsonp'
});
req.done(function(data) {
console.log(data);
var infoTable = $("<table />");
var arrayL = data.length;
var outputString = '';
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
});
Although, this way I can only get data from one api. How can I take it from multiple?
EDIT:
I am trying to add text input, so I can send request about specific word. I am trying to append existing table with new results. I was trying to alter code which was provided as an answer below. However, I did something work, and it does not work.
$("#inputChoice").on("blur", function() {
let choice = $(this).val();
let req = $.ajax({
url: "...APIlink"+choice,
dataType: "jsonp"
});
req.done(function (data) {
console.log(data);
var infoTable = $("<table />");
let arrayL = data.length;
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
titleCell.addClass("title-row");
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
detailCell.addClass("details-row")
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
});
Request data from endpoints and when they're all done create a table
function multiReq(...links) {
let responseCount = links.length;
const responses = [];
let handler;
function responseHandler(i) {
return data => {
responseCount -= 1;
responseCount === 0
? handler([].concat(...responses))
: (responses[i] = data)
}
}
links.forEach((link, i) => $.ajax({
url: link,
dataType: 'jsonp'
}).done(responseHandler(i)));
return {
done(callback) {
handler = callback;
}
};
}
multiReq(link1, link2).done((data) => {})
or
function multiReq(...links) {
return Promise.all(links.map(link => $.ajax({
url: link,
dataType: 'jsonp'
}))).then((...responses) => [].concat(...responses))
}
multiReq(link1, link2).then(data => {
// create table
})
or
function multiReq(...links) {
return $.when(...links.map(link => $.ajax({
url: link,
dataType: 'jsonp'
}))).then((...responses) => [].concat(...responses.map(([data]) => data)))
}
multiReq(link1, link2).done(data => {
// create table
})
or as close to your code as possible:
var req1 = $.ajax({
url: "https://wt-65edf5a8bfb22e61214c31665c92dbd2-0.sandbox.auth0-extend.com/link-1",
//dataType: 'jsonp'
});
var req2 = $.ajax({
url: "https://wt-65edf5a8bfb22e61214c31665c92dbd2-0.sandbox.auth0-extend.com/link-1",
//dataType: 'jsonp'
});
$.when(req1, req2).done(function([data1], [data2]) {
var data = data1.concat(data2); // merge data from both request into one
//console.log(data);
var infoTable = $("<table />");
var arrayL = data.length;
var outputString = '';
for (var i = 0; i < arrayL; i++) {
var tableRow = $("<tr/>");
titleString = data[i].title;
var titleCell = $("<td />", {
text: titleString
});
detailString = data[i].description;
var detailCell = $("<td/>", {
text: detailString
});
tableRow.append(titleCell).append(detailCell);
infoTable.append(tableRow);
}
$("#display-resources").append(infoTable);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="display-resources"></div>

Save Multiple Rows from table to Backend SAPUI5

I'm having issues with saving multiple rows to the back-end. I don't know how to send all the rows in batch, so I was trying to send each row at a time but it hits after it has put the last row into the oEntry.
submitButtonPress: function() {
var oModel = this.getModel();
var hasChanges = oModel.hasPendingChanges();
if (hasChanges) {
var mcJson = {};
//get only rows with changes
var modelChanges = oModel.getPendingChanges();
mcJson = modelChanges;
var mcJsonLength = Object.keys(mcJson).length;
var mcJsonKey = Object.keys(mcJson);
var officeCode = this.byId("officeCombo").getValue();
var oEntry = {};
//for each row get data
for (var i = 0; i < mcJsonLength; i++) {
var item = mcJsonKey[i];
var obj = modelChanges[item];
var estDate = this.convertDate(obj.ESTIMATE_DATE);
oEntry.MRU_ID = obj.EST_MRU_ID.toString();
oEntry.ESTIMATE_PRCT = obj.ESTIMATE_PRCT;
oEntry.INSTALL_READ = obj.INSTALL_READ;
oEntry.PLAN_ESTIMATE = obj.EST_INSTALL;
oEntry.MRU_DATE = estDate;
oEntry.OFFICE_CODE = officeCode.toString();*/
oModel.create("/MRU_ESTSet", oEntry, {
success: function(oData, response) {
sap.m.MessageBox.alert("MRU: " + oEntry.MRU_ID + " EST DATE:" + oEntry.MRU_DATE + " SAVED!");},
error: function(oError) {
sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
} else {
sap.m.MessageBox.alert("No Changes To Submit");
}
}
If you are using oDataModel V2 then what you could just simply do is:
oModel.submitChanges()
This would send all changes made to the model in a batch.
submitChanges method documentation
This is what ended up working for me.
Adding:
oModel.setUseBatch(true);
oModel.create("/MRU_ESTSet", oEntry, {
method: "POST",
success: function(oData) {
//sap.m.MessageBox.alert("success sent!");
},
error: function(oError) {
//sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
oModel.submitChanges({
success: function(oData, response) {
sap.m.MessageBox.success("Success Saving Entries!");
},
error: function(oError) {
sap.m.MessageBox.error("Error Saving Entries!!");
}
});
So the function ends up like this and only sends one confirmation instead of many:
submitButtonPress: function() {
var oModel = this.getModel();
oModel.setUseBatch(true);
var hasChanges = oModel.hasPendingChanges();
if (hasChanges) {
var mcJson = {};
var modelChanges = oModel.getPendingChanges();
mcJson = modelChanges;
var mcJsonLength = Object.keys(mcJson).length;
var mcJsonKey = Object.keys(mcJson);
var officeCode = this.byId("officeCombo").getValue();
for (var i = 0; i < mcJsonLength; i++) {
var item = mcJsonKey[i];
var obj = modelChanges[item];
var estDate = this.convertDate(obj.ESTIMATE_DATE);
var oEntry = {
MRU_ID: obj.EST_MRU_ID,
ESTIMATE_PRCT: obj.ESTIMATE_PRCT,
INSTALL_READ: obj.INSTALL_READ,
PLAN_ESTIMATE: obj.EST_INSTALL,
MRU_DATE: estDate,
OFFICE_CODE: officeCode
};
oModel.create("/MRU_ESTSet", oEntry, {
method: "POST",
success: function(oData) {
//sap.m.MessageBox.alert("success sent!");
},
error: function(oError) {
//sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
oModel.submitChanges({
success: function(oData, response) {
sap.m.MessageBox.success("Success Saving Entries!");
},
error: function(oError) {
sap.m.MessageBox.error("Error Saving Entries!!");
}
});
} else {
sap.m.MessageBox.alert("No Changes To Submit");
}
},

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';
});

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.

How to get whole data out of callback function in javascript

I have written following function which takes a json data from a url.
function getWeatherDataForCities(cityArray){
var arrAllrecords = [];
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
for(var j=1; j<=2; j++){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords[j]["cityName"] = data.list[0].city.name;
arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
} });
toDaysTimestamp = toDaysTimestamp - (24*60*60);
}
}
return arrAllrecords; //returning arrAllrecords
}
$(document ).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
var arrAllRecords = getWeatherDataForCities(cityArray);
//Print All records returned by getWeatherDataForCities(cityArray);
});
I have written some comments in above code.I have called getWeatherDataForCities function which returns all records from url.I have declared getWeatherDataForCities array in function.I want to add all returned records in that array.I have tried as above but nothing is getting into array.
In console showing j and arrAllrecords are undefined.
How to get all records in array from callback function?
you response will be highly appreciated
Your getWeatherDataForCities function won't return anything because ajax operations are asynchronous. You need to use a callback for that.
Modify your function to accept a callback function:
function getWeatherDataForCities(cityArray, callback){
var arrAllrecords = [];
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
for(var j=1; j<=2; j++){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords[j]["cityName"] = data.list[0].city.name;
arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
// call the callback here
callback(arrAllrecords);
}
});
toDaysTimestamp = toDaysTimestamp - (24*60*60);
}
}
}
And use it like this:
$(document ).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
getWeatherDataForCities(cityArray, function(arrAllrecords) {
// Do something with your data
});
});
You are trying to use the empty array. When fetching the values it will always return you undefined.
var arrAllrecords = [];
arrAllrecords[2]; //undefined
arrAllrecords[2]["cityname"]; //undefined
Better you should use array of objects.
I don't know why you have used variable j. The below code works for me.
var arrAllrecords = [];
function getWeatherDataForCities(cityArray){
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords.push({
"cityName" : data.list[0].city.name,
"weather" : data.list[0].weather[0].description
});
if(arrAllrecords.length === cityArray.length) {
callback(arrAllrecords);
}
} });
}
}
function callback(arrAllrecords) {
console.log(arrAllrecords);
}
$(document).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
cityArray[1] = "mumbai";
cityArray[2] = "delhi";
getWeatherDataForCities(cityArray);
});

Categories