Dynamical creating dropdown from database data in PHP & Ajax - javascript

I am trying to make dynamical dropdown that will be populated by data collected from database. I am stuck at parsing data from multidimensional array sent by PHP file. My code:
Part of HTML file (only the responsible JavaScript (Ajax function))
function mentor() {
// 1. Create XHR instance - Start
var oblast = document.getElementById("oblast").value; //previous dropdown from which I need to create next one
document.getElementById("mentorr").innerHTML = ""; //emtpy the dropdown I need to create
instancee();
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
var val = xhr.responseText;
alert(val); //just a check to see does it get correct data, and it get, everything is OK so far
var jsonData = JSON.parse(val);
var selectList = document.getElementById('mentorr'); //id of the dropdown I need to create
for (var i in jsonData) {
var option = document.createElement('option');
//$response[$i]['name'];
option.value = jsonData['id'][i];
option.text = jsonData['name'][i];
selectList.appendChild(option);
}
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'ajax.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("oblast=" + oblast);
}
Part of ajax.php file that fetches data and sends to HTML:
$queryData1 = mysql_query("SELECT * FROM profesori WHERE idprof = '$prof'");
while($result2 = mysql_fetch_array($queryData1)) {
$id=$result2['idprof'];
$profesor=$result2['ime']. " ".$result2['prezime'];
$data = array
(
'id' => array($id),
'name' => array($profesor)
);
echo json_encode($data);
}
alert(var) line of code gives this:
So data is corretly fetched from database and sent to HTML. But the problem is in populating dropdown menu (parsing data). Error in console in "unexpected token {" in the line
var jsonData = JSON.parse(val);
Does anyone know how to fix this?

for (var i = 0; i < jsonData.length; i++) {
var option = document.createElement('option');
option.value = jsonData[i].id;
option.text = jsonData[i].name;
selectList.appendChild(option);
}
Should do the trick, JSON.parse returns json objects, you can loop through the objects using an index and fetch properties of an object like this "object.property".

Related

Passing javascript object containing another array of objects to localStorage and then to java servlet using ajax

I am trying to work out how to store a javascript object in local storage that has a few items as well as an array of objects, if that is possible. To then extract the data from the local storage and send to a java servlet using ajax, then extract the data from the java HttpServletRequest. Here is some of the code I have written. It's a bit too complex to put the entire code base here. I have multiple forms which a user completes and as they move between forms I store the data entered into local storage.
const object = localStorage.getItem(scenarioName);
let scenarioObject = JSON.parse(object);
if (formIsValid) {
scenarioObject.SUPER_BALANCE = 420000;
scenarioObject.SUPER_INVESTMENT_FEES = 0.14;
scenarioObject.SUPER_ADMIN_FEES = 120;
scenarioObject.LIFE_INSURANCE = 200000;
scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION = 1500;
let objectString = JSON.stringify(scenarioObject);
localStorage.setItem(scenarioName, objectString);
}
To extract the data from local storage I do the following:
const object = localStorage.getItem(activeScenario);
const jsonString = JSON.parse(object);
const yourSuperBalance = jsonString.SUPER_BALANCE;
$("#your-super-balance").val(yourSuperBalance);
const yourInvestmentFees = jsonString.SUPER_INVESTMENT_FEES;
$("#super-investment-fees").val(yourInvestmentFees);
const yourSuperAdminFees = jsonString.SUPER_ADMIN_FEES;
$("#super-admin-fees").val(yourSuperAdminFees);
const yourInsurance = jsonString.LIFE_INSURANCE;
$("#life-insurance").val(yourInsurance);
const yourAnnualSuperContribution = jsonString.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION;
$("#your-annual-lump-sum-super-contribution").val(yourAnnualSuperContribution);
This all works fine, but now I wanted to add an array of objects from a table. I could not figure out a way to add this so I ended up storing two items in local storage. One for all the form data and one for the table data. I didn't like this approach but couldn't get it to work otherwise. Here is how I did the table:
function getSuperContributionsTableDataString(table) {
let yourSuperContributionsTableData = [];
let jsonData;
// commence for loop at 1 because the first row will be the header row and we want to skip that
for (let i = 1; i < table.rows.length; i++) {
let row = table.rows[i];
// first check all cells in row have a value, if not ignore
if (row.cells[0].innerText !== "" && row.cells[1].innerText !== "" && row.cells[2].innerText !== "") {
// As we are pushing the last element pushed becomes the first element in the array
// therefore, we push the before or after tax first and age last
jsonData = {};
jsonData[SUPER_TAXATION_CONTRIBUTION] = row.cells[2].innerText;
jsonData[SUPER_AMOUNT_CONTRIBUTION] = row.cells[1].innerText;
jsonData[SUPER_AGE_CONTRIBUTION] = row.cells[0].innerText;
yourSuperContributionsTableData.push(jsonData);
}
}
return JSON.stringify(yourSuperContributionsTableData);
}
let superContributionsTableDataString = getSuperContributionsTableDataString(
document.getElementById("your-extra-super-contributions-table"));
localStorage.setItem(scenarioName+ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION, superContributionsTableDataString);
This all worked but then I had to figure out how to send this data to the server using ajax. Without the table, everything was working fine as follows:
function sendScenarioDetailsToServer() {
let activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
let item = localStorage.getItem(activeScenario);
let passedData = JSON.parse(item);
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: passedData,
success: function (data) {
const SUCCESS_INT = data.length - 1;
if (data[SUCCESS_INT].SUCCESS === FAIL) {
displayPopupMessage("Error saving scenario ", "Save Scenario");
}else {
displayResult();
}
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
}
I modified this function as follows to add the table data and everything in the java servlet code went wrong.
function sendScenarioDetailsToServer() {
let activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
let item = localStorage.getItem(activeScenario);
let passedData = JSON.parse(item);
// superannuation table
const superTable = activeScenario+ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION;
// this is already stringified
const superTableItem = localStorage.getItem(superTable);
const superTableData = '&' + ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION + "=" + superTableItem;
const formData = passedData + superTableData;
console.log("formData " + formData);
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: passedData + superTableData,
success: function (data) {
const SUCCESS_INT = data.length - 1;
if (data[SUCCESS_INT].SUCCESS === FAIL) {
// TODO display messages
displayPopupMessage("Error saving scenario ", "Save Scenario");
}else {
displayResult();
}
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
}
Can anyone advise how best to store a javascript object in local storage that has an item inside the object which is an array of objects for a table? How do I store this in local storage, retrieve it from local storage, send it to the java servlet using ajax and then retrieve it from the HttpServletRequest. Any assistance would be much appreciated.
I worked out a way to do this. I shall fully explain the situation and then my solution to the problem. Not sure if this is the best solution but it does work.
The situation is that I have multiple forms where the user enters data for calculations, including a table of data. I wanted to store this data on local storage for later retrieval next time the user uses the website. The calculations are done in Java on the server so when the user clicks on something like "calculate" the data in local storage is then sent to the server to perform the calculations and the result is sent back.
I needed to store a javascript object containing some elements plus a table, so basically a javascript object with an array inside it.
Collect data from the table
function getSuperContributionsTableDataString(table) {
let yourSuperContributionsTableData = [];
let jsonData;
// commence for loop at 1 because the first row will be the header row and we want to skip that
for (let i = 1; i < table.rows.length; i++) {
let row = table.rows[i];
// first check all cells in row have a value, if not ignore
if (row.cells[0].innerText !== "" && row.cells[1].innerText !== "" && row.cells[2].innerText !== "") {
// As we are pushing the last element pushed becomes the first element in the array
// therefore, we push the before or after tax first and age last
jsonData = {};
jsonData[SUPER_TAXATION_CONTRIBUTION] = row.cells[2].innerText;
jsonData[SUPER_AMOUNT_CONTRIBUTION] = row.cells[1].innerText;
jsonData[SUPER_AGE_CONTRIBUTION] = row.cells[0].innerText;
yourSuperContributionsTableData.push(jsonData);
}
}
return yourSuperContributionsTableData;
}
Where I went wrong with this originally was I stringified the array. As the entire javascript object is going to be stringified this was unnecessary.
Create javascript object and store in local storage
The first step is to extract the item from local storage to update it with the new data from the user. Notice we must parse the object because it was originally stringified.
Secondly set the user entered data on the javascript object. You will notice the call to the function above that retrieves the table data. That table data is set as a key value pair in the javascript object.
const scenarioName = localStorage.getItem(ACTIVE_SCENARIO_KEY);
const object = localStorage.getItem(scenarioName);
let scenarioObject = JSON.parse(object);
isValid = validateYourSuperannuationForm();
if (isValid) {
let superContributionsTableDataString = getSuperContributionsTableDataString(
document.getElementById("your-extra-super-contributions-table"));
scenarioObject.SUPER_BALANCE = $("#your-super-balance").val();
scenarioObject.SUPER_INVESTMENT_FEES = $("#super-investment-fees").val();
scenarioObject.SUPER_ADMIN_FEES = $("#super-admin-fees").val();
scenarioObject.LIFE_INSURANCE = $("#life-insurance").val();
scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION = $("#your-annual-lump-sum-super-contribution").val();
scenarioObject.EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA = superContributionsTableDataString;
let objectString = JSON.stringify(scenarioObject);
localStorage.setItem(scenarioName, objectString);
}
Send item in local storage to server
I discovered trying to stringify the entire javascript object caused problems at the server. What I had to do was create a new object for the formData to be sent to the server, BUT I had to stringify only the table data, not the entire object. I had to retrieve each item from local storage and set it on the formData object to be passed to the server.
function sendScenarioDetailsToServer() {
const activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
const item = localStorage.getItem(activeScenario);
const scenarioObject = JSON.parse(item);
// We must do this because if superContributionsTableData == "" and we then stringify this it will
// end up with a value of """", which will cause an error.
const superContributionsTableData = scenarioObject.EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA;
let superContributionsTableDataString = "";
if (superContributionsTableData !== ""){
superContributionsTableDataString = JSON.stringify(superContributionsTableData);
}
const formData = {
SCENARIO_NAME: scenarioObject.SCENARIO_NAME,
DATE_OF_BIRTH: "",
IS_SINGLE: scenarioObject.IS_SINGLE,
IS_RETIRED: scenarioObject.IS_RETIRED,
RETIREMENT_DATE: scenarioObject.RETIREMENT_DATE,
IS_HOMEOWNER: scenarioObject.IS_HOMEOWNER,
FORTNIGHTLY_RENT: scenarioObject.FORTNIGHTLY_RENT,
DATE_RENT_CEASES: scenarioObject.DATE_RENT_CEASES,
IS_SINGLE_AND_SHARING: scenarioObject.IS_SINGLE_AND_SHARING,
SPOUSE_DATE_OF_BIRTH: scenarioObject.SPOUSE_DATE_OF_BIRTH,
IS_SPOUSE_RETIRED: scenarioObject.IS_SPOUSE_RETIRED,
SPOUSE_RETIREMENT_DATE: scenarioObject.SPOUSE_RETIREMENT_DATE,
SUPER_BALANCE: scenarioObject.SUPER_BALANCE,
SUPER_INVESTMENT_FEES: scenarioObject.SUPER_INVESTMENT_FEES,
SUPER_ADMIN_FEES: scenarioObject.SUPER_ADMIN_FEES,
LIFE_INSURANCE: scenarioObject.LIFE_INSURANCE,
ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION: scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION,
EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA: superContributionsTableDataString
}
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: formData,
success: function (data) {
// do stuff here
{
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
In the Java Servlet the data is then extracted from the HttpServletRequest passed to the doPost method. It is retrieved in the usual way by calling HttpServletRequest.getParameter. Converting the table data is a little more complex because it is an array that was converted to a string. I am including an extract of that code in case it is of use to someone.
ArrayList<LumpSumSuperContribution> superContributionsList = new ArrayList<>();
String superContributionsTableData = request.getParameter(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA);
// Array superContributionsArray = request.getParameter(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA);
JSONObject superContributionsMessage = new JSONObject();
boolean errorOccurred = false;
if (superContributionsTableData != null && superContributionsTableData.length() > 0) {
try {
JSONArray superContributionsArray = new JSONArray(superContributionsTableData);
int i = 0;
while (i < superContributionsArray.length()) {
JSONObject contributionObj = (JSONObject) superContributionsArray.get(i);
String ageString = (String) contributionObj.get(SUPER_AGE_CONTRIBUTION);
Validator.WholeNumberResult result6 = Validator.validateMandatoryWholeNumber(ageString, 18, 99,
"Lump Sum Super Contribution age for row " + (i + 1));
if (!result6.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result6.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
Integer age = result6.getNumber();
String contributionAmountString = (String) contributionObj.get(SUPER_AMOUNT_CONTRIBUTION);
Validator.WholeNumberResult result7 = Validator.validateMandatoryWholeNumber(
contributionAmountString, 1, 9999999,
"Lump Sum Super Contribution amount for row " + (i + 1));
if (!result7.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result7.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
Integer amount = result7.getNumber();
String beforeAfterTaxString = (String) contributionObj.get(SUPER_TAXATION_CONTRIBUTION);
Validator.TextResult result8 = Validator.validateMandatoryText(beforeAfterTaxString,
"Lump Sum Super Contribution Before or After Tax for row " + (i + 1), 5, 6);
if (!result8.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result8.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
String beforeAfterTax = result8.getText();
LumpSumSuperContribution superContribution = new LumpSumSuperContribution(age, amount, false,
LumpSumSuperContribution.YOUR_CONTRIBUTION, beforeAfterTax);
superContributionsList.add(superContribution);
i++;
}
if (!errorOccurred) {
scenario.setAllYourSuperContributions(superContributionsList);
// superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, SUCCESS);
} else {
fail = true;
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, FAIL);
messageArray.put(superContributionsMessage);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}else {
scenario.setAllYourSuperContributions(null);
}
}
Summary
Create a javascript array. Then loop through the table data and create a javascript object for each row of the table and push onto the array.
Create or retrieve javascript object stored in local storage. If already in local storage, this object must be parsed using JSON.parse(object).
Set the details on the object entered by the user.
Stringify the javascript array and add the string to the object as a key value pair.
To send the data to the server retrieve the item from local storage and parse the item to extract details from it.
Set the extracted details on a newly created formData object.
Stringify the table data and set as a key value pair in formData.
Using ajax Post the data to the server.
I hope this helps someone in the future. It took me a while of trying different things to find a way to get this to work. If anyone has a better solution please post it.

uilocations is declared but its value is never read

I'm building a price prediction model using Python, Flask Server, HTML, and CSS. I've implemented the HTML and CSS code but I'm having issues getting my dropdown button to read all my locations via a JavaScript call (all the locations are saved in a json file). Concerning 'uilocations' it keeps showing 'uilocations is declared but its value is never read. Below is my javascript code:
function onClickedEstimatedPrice(){
var uiBathrooms = document.getElementsByName("uiBathrooms");
for(var i in uiBathrooms) {
if(uiBathrooms[i].checked) {
return parseInt(i)+1;
}
}
return -1;
}
function getBHKValue() {
var uiBHK = document.getElementsByName("uiBHK");
for(var i in uiBHK) {
if(uiBHK[i].checked) {
return parseInt(i)+1;
}
}
return -1; // The above functions iterate through the buttons and return the values
}
function onClickedEstimatedPrice() {
console.log("Estimated price button clicked");
var sqft = document.getElementById("uilocations");
var bathrooms = document.getElemenbtById("uiEstimatedPrice");
var estPrice = document.getElementById("uiEstimatedPrice")
var url = "http://127.0.0.1:5000/predict_home_price"; //url for the price prediction endpoint
$.post(url, { //This is a jquery POST call that makes a POST call to the url, we will get our output back in 'data'
total_sqft: parseFloat(sqft.value),
bhk: bhk,
bath: bathrooms,
location: location.value
},function(data, status) {
console.log(data.estimated_price);
estPrice.innerHTML = "<h2>" + data.estimated_price.toString() + " Lakh</h2>";
console.log(status)
}
)
}
function onPageLoad() {
console.log( "document loaded" );
var url = "http://127.0.0.1:5000/get_location_names"; //Here we make our HTTP Call
$.get(url,function(data, status) { //This is a jquery GET call that makes a GET call to the url, we will get our response back in the 'data'
console.log("got response for get_location_names request");
if(data) {
var locations = data.locations; //This will be our list of locations
var uilocations = document.getElementById("uilocations");
$("#uilocations").empty();
for(var i in locations) {
var opt = new Option(locations[i]);
$("#uilocations").append(opt);
} //The above goes through our locations one by one and adds them to our dropdown
}
});
}
window.onload = onPageLoad; //This will be used to load our HTML page and load the locations
I tried the code above, i expected my dropdown button to pick more locations but whenever i refresh the page on my browser, i don't get the expected output

Sum of sharepoint list items in particular field

I have one list with cost field,and I have multiple items in my list .I have to get the sum of cost field in my aspx page. If I add new item then also the aspx page should calculate the sum of cost field ...how can i achieve it using javascript...anyone please help me...
You could use OOB sum feature for your list view.
Demo:
Or, load list items and then calculating by JSOM script.
Demo:
window.onload=function (){
var url=_spPageContextInfo.webAbsoluteUrl;
var ctx = new SP.ClientContext(url);
var TotalCost=0;
//Get the web
var web = ctx.get_web();
//Get the List based upon the Title
var list = web.get_lists().getByTitle("Store Items");
//The Query object. This is used to query for data in the List
var query = new SP.CamlQuery(); ctx.load(list);
query.set_viewXml('<View></View>');
var items = list.getItems(query);
//Retrieves the properties of a client object from the server.
ctx.load(list);
ctx.load(items);
ctx.executeQueryAsync(
Function.createDelegate(this, function () {
var enumerator = items.getEnumerator();
while (enumerator.moveNext()) {
var currentListItem = enumerator.get_current();
//console.log(currentListItem.get_item("Price"));
TotalCost+=currentListItem.get_item("Price");//cost field
}
console.log("-------------------------------")
console.log("TotalCost:"+TotalCost);
}),
Function.createDelegate(this, fail)
);
}
function fail(){
console.log("fail")
}
You can use the below Java script code from the asp.net application, after connecting to the the SharePoint list through the context object, need to get the list items. You can refer the below Java script code to do the sum up functionality.
for (var i = 0; i < monthChoices.length; i++){
chartSeries[i] = [];
var monthTotal = 0;
for(var j= 0; j< arrItems.length; j++ ){
if(monthChoices[i]==arrItems[j].get_item("Month") && arrItems[j].get_item("Duration")!= ""){
monthTotal += arrItems[j].get_item("Duration");
}
}
chartSeries[i].push([monthChoices[i], monthTotal]);
console.log(chartSeries[i]);
}
Reference URL :
SharePoint List : Sum of Column Values using JavaScript Client Object Model
Or
The below code :
function onItems(sender, e)
{
var iterator=myTotalTimeItems.getEnumerator();
var sum=0;
while(iterator.moveNext()){
var item=iterator.get_current();//retrieves current item from the collection.
var num=item.get_item("Estimated_x0020_Time_x0020__x002");
if(isNaN(num)) continue;
else
sum+=Number(num);
}
alert("Total estimated time:"+sum);
}
Reference URL :
https://social.msdn.microsoft.com/Forums/office/en-US/6370dbf7-4494-4d79-b02a-647f7442cc6e/sum-column-value-with-javascript?forum=sharepointdevelopment
If you want to display the sum value on a page, first create a 'Scripteditor' webpart on that page. You can do this by editing the page, clicking 'add a webpart', choose the 'Media and content' category and then selecting 'Scripteditor'.
Once it is created, edit the following code so the 'listName' variable contains the name of your list and I assumed here you have a column named 'Cost'. If your column name is different, change that also.
<p id="SumPrices"></p>
<script type="text/javascript">
var listName = 'LISTNAME';
var xhr = new XMLHttpRequest();
xhr.open('GET', _spPageContextInfo.webAbsoluteUrl + '/_api/web/lists/GetByTitle(\'' + listName + '\')/items?$select=Cost');
xhr.setRequestHeader('Accept', 'application/json; odata=verbose');
xhr.onload = function(){
if (xhr.status === 200) {
var results = JSON.parse(xhr.responseText);
results = results.d.results;
var sum = 0;
for (var i = 0; i < results.length; i++){
sum += results[i].Cost;
}
document.getElementById('SumPrices').innerText = sum;
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
</script>
Now click on 'EDIT FRAGMENT' in the bottom right corner of the webpart (in edit page mode) and paste the code there. Click on 'Insert' and close the edit page mode. You will now see the sum of all the prices on your page.

ServiceNow auto-populate Script not being called

I have a table in ServiceNow that contains Store and a corresponding Tier that is associated with the Store.
I am trying to auto-populate a record producer, once Store is selected. and my script is not running.
The table is a custom table created in a scoped application which is new to me so not sure what I am doing wrong in the scripting. Any advice?
//Catalog Client Script (runs on [Store] Record Producer Change)
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
// new GlideAjax object referencing store of AJAX script include
var ga = new GlideAjax("HRProfileAjax");
// add store parameter to define which function we want to call
// method store in script include will be getFavorites
ga.addParam("sysparm_store", "getHRProfile");
ga.addParam("sysparm_tier", "getHRProfile");
// submit request to server, call ajaxResponse function with server response
ga.getXML(ajaxResponse);
function ajaxResponse(serverResponse) {
// get result element and attributes
var result = serverResponse.responseXML.getElementsByTagstore("result");
var message = result[0].getAttribute("tier");
//check for message attribute and alert user
//if(message)
//alert(message);
//build output to display on client for testing
// get favorite elements
var favorites = serverResponse.responseXML.getElementsByTagstore("favorite");
for(var i = 0; i < favorites.length; i++) {
var store = favorites[i].getAttribute("store");
g_form.setValue(store);
var tier = favorites[i].getAttribute("tier");
//output += store + " = " + tier + "\n";
g_form.setValue(store,tier);
}
//g_form.setValue('number',output);
}
//Script #2 HR PROFILE AJAX
/*
* HRProfileAjax script include Description - sample AJAX processor returning multiple value pairs
*/
var HRProfileAjax = Class.create();
HRProfileAjax.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
/*
* method available to client scripts call using:
* var gajax = new GlideAjax("HRProfileAjax");
* gajax.addParam("sysparm_store", "getFavorites");
*/
getHRProfile : function() {
// build new response xml element for result
var result = this.newItem("result");
var store = this.getParameter('store');
var hrPro = new GlideRecord('x_hiring_gri_hr_storetier');
hrPro.addQuery('store',store);
hrPro.query();
if(hrPro.next()){
result.setAttribute("message", "returning all favorites");
this._addFavorite("tier", hrPro.tier);
}
},
_addFavorite : function(store, value) {
var favs = this.newItem("favorite");
favs.setAttribute("store", store);
},
type : "HRProfileAjax"
});

Passing array from php to javascript through ajax response

This is my first post in stackoverflow. I have always got my answers from previously posted questions. This problem has been bugging me and all the solutions I tried have not worked.
I have a js function which makes an ajax request to get weather info of town passed:
var _getWeatherInfo = function(ntown){
var town = ntown;
var url = "PHP/weather.php?town=" + town;
request1.onreadystatechange = _refreshWeatherList();
request1.open("GET", url, true);
request1.send("");
}
I am using the following php code to return the sql results stored in array:
<?php
//Connection to the database
$mysql = mysql_connect("localhost","xuvaz","x");
//Selecting Database
$db = mysql_select_db("weather");
$town = $_GET['town'];
$tarray = array();
$sql1= mysql_query("SELECT * FROM weather WHERE town='$town'");
while($row = mysql_fetch_assoc($sql1)) {
$tarray = array('town' => $row['town'],'outlook' => $row['outlook']);
}
echo json_encode($tarray);
?>
Then I have a function that is called when the request is completed:
var _refreshWeatherList = function() {
var weather_info = request1.responseText;
for(var i = 0; i < weather_info.length; i++){
var wtown = weather_info[i].town;
var woutlook = weather_info[i].outlook;
var wmin = weather_info[i].min_temp;
var wmax = weather_info[i].max_temp;
}
var wLine = new WLine(wtown, woutlook, wmin, wmax);
_weather.push(wLine);
_refreshWeatherDisplay();
}
The problem is I cant access the array values.
I can see the values as {"town":"Christchurch","outlook":"fine"} in firebug under response.
Even when I use JSON parse it gives error in the firebug , JSON.parse: unexpected end of data. If
I can just access the data my whole project would be completed.
Your PHP code is returning an object (last row from your loop) rather than an array of objects, but your JavaScript is expecting an array.
Change your PHP to the following to appand to $tarray:
while($row = mysql_fetch_assoc($sql1)) {
$tarray[] = array('town' => $row['town'],'outlook' => $row['outlook']);
}
Your JavaScript needs to wait for readyState = Loaded and JSON-decode the responseText:
var _refreshWeatherList = function() {
if(request1.readyState == 4) {
var weather_info = JSON.parse(request1.responseText);
....
}
}
If the parse is failing, trying logging it to the console to make sure the PHP isn't returning extra characters.
var _refreshWeatherList = function() {
var weather_info = eval("("+request1.responseText+")");
for(var i = 0; i < weather_info.length; i++){
var wtown = weather_info[i].town;
var woutlook = weather_info[i].outlook;
var wmin = weather_info[i].min_temp;
var wmax = weather_info[i].max_temp;
}
var wLine = new WLine(wtown, woutlook, wmin, wmax);
_weather.push(wLine);
_refreshWeatherDisplay();}
'request1.responseText' must be 'object' use eval() --! my english not well
Thank you for all your help. I found the fault. I forgot to include these two lines.
if (request1.readyState == 4) {
if (request1.status == 200){

Categories

Resources