Ajax and JSON arrays - javascript

I'm trying to use JSON data format together with jQuery and, well, it would be surprising if it worked.
In my remoteServiceEngine.php, I have something like this:
$jResponse[0] = json_encode(array("jAction" => "add", "jObject" => "listCountries", "jBody" => "test"));
$json_data = json_encode(array("jRequestState" => $jRequestState, "jMessage" => $jMessage, "jResponse" => $jResponse));
echo $json_data;
And this is how it is handled in JS:
success: function(remoteResponse){
switch(remoteResponse.jRequestState) {
case 0:
$("#removeServiceMessage").fadeIn(2000).html('<div class="remoteError">'+remoteResponse.jMessage+'</div>').fadeOut(2000);
break;
case 1:
$("#removeServiceMessage").fadeIn(2000).html('<div class="remoteSuccess"><B>Success:</B> '+remoteResponse.jMessage+'</div>').fadeOut(2000);
for (i = 0; i < remoteResponse.jResponse.length; i++) {
switch(remoteResponse.jResponse[i].jAction) {
case "add":
$("#"+remoteResponse.jResponse[i].jObject).fadeIn(1000).append(remoteResponse.jResponse[i].jBody);
break;
case "remove":
$("#"+remoteResponse.jResponse[i].jObject).fadeOut(1000);
break;
case "update":
$("#"+remoteResponse.jResponse[i].jObject).fadeIn(1000).html(remoteResponse.jResponse[i].jBody);
break;
default:
alert(remoteResponse.jResponse[i]);
break;
}
}
break;
}
}
The whole problem is that I cannot access successful content. With $jRequestState = 1 and the forementioned $jResponse[0], switch goes directly onto default and this is the output I get:
{"jAction":"add","jObject":"listCountries","jBody":"test"}
but I cannot figure out how to access these elements. I tried it with:
alert(remoteResponse.jResponse[i]['jAction']);
and
alert(remoteResponse.jResponse[i][0]); //yeah, that's kinda stupid solution, but well...
Since I've never used JSON with jQuery, I can't figure out how to deal with that. Help, anybody?

Like adeneo said in the comment you jsonencode twice. Your php code should look like:
$jResponse[0] = array("jAction" => "add", "jObject" => "listCountries", "jBody" => "test");
$json_data = json_encode(array("jRequestState" => $jRequestState, "jMessage" => $jMessage, "jResponse" => $jResponse));
echo $json_data;

Related

how to get the fetch method to work and the process after linking external data source?

i am a beginner at javascript, and i'm asked to build a dynamic image galleries with external data using the fetch() method for an assignment. the requirement for this is to use the fetch() method to link an image slider onto this main page, and i need to make a button to click where a random number is chosen and an external dataset is loaded. but i am having difficulty getting the code to work and i don't know how or where the mistake is, this code is given to me as an example and i need to revise it with my own external links. please help me!
this is what i have in javascript:
console.clear();
document.querySelector("button#myLanguageBTN").addEventListener(
"click",
function () {
var randomNumber = Math.floor(Math.random() * 5);
switch (randomNumber) {
case 1:
var myfetchLink = "https://codepen.io/tchau16/pen/PoaaJYG.js";
case 2:
var myfetchLink = "https://codepen.io/tchau16/pen/dyKKVGP.js";
case 3:
var myfetchLink = "https://codepen.io/tchau16/pen/jOKKGWZ.js";
case 4:
var myfetchLink = "https://codepen.io/tchau16/pen/JjZZrGQ.js";
default:
var myfetchLink = "https://codepen.io/tchau16/pen/dyKKVGP.js";
}
console.log(myfetchLink);
.then((response) => {
return response.text();
})
.then((myInformation) => {
const myReturn = JSON.parse(myInformation);
There are few mistakes in your code -
switch does not have a break statement, so it was falling to default statement every time.
Fetch was not used. Added console logs at appropriate places.
use let and const, removed var for myfetchLink.
use free apis to test your code.
Switch JS MDN link - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Free apis - https://apipheny.io/free-api/#apis-without-key
console.clear();
document.querySelector("button#myLanguageBTN").addEventListener(
"click",
function() {
let randomNumber = Math.floor(Math.random() * 5);
let myfetchLink = '';
switch (randomNumber) {
case 1:
myfetchLink = "https://www.boredapi.com/api/activity";
break;
case 2:
myfetchLink = "https://catfact.ninja/fact";
break;
case 3:
myfetchLink = "https://api.publicapis.org/entries";
break;
case 4:
myfetchLink = "https://codepen.io/tchau16/pen/JjZZrGQ.js";
break;
default:
myfetchLink = "https://api.coindesk.com/v1/bpi/currentprice.json";
}
console.log(myfetchLink);
fetch(myfetchLink)
.then((response) => {
console.log(response);
return response.text();
}).then((myInformation) => {
console.log(myInformation);
const myReturn = JSON.parse(myInformation);
});
});
<button id="myLanguageBTN">Fetch the Data</button>

traverse array of objects and show image according to a type

I have an array of objects in a state in pinia, I get this array in my component. I am trying to show an image or others according to a value that is in the object, I make a function where I go through the array here and using switch I check the type, and return the image that corresponds to the type, I do this but I only get returns the first image if I use a for, if I do it with forEach it returns null, I try to save the value in the function because it is the one that I command to call to show the image, how can I do this so that according to a type I show a different image?
Function where you tried to get the images
const imgSelect = () => {
for(let i = 0; i < obj.value.length; i++){
switch(obj.value[i].type){
case 'one':
return new URL('../assets/images/image1.png', import.meta.url).href
break;
case 'two':
return new URL('../assets/images/image2.png', import.meta.url).href
break;
case 'three':
return new URL('../assets/images/image3.png', import.meta.url).href
break;
default:
return null
break;
}
}
}
here I try to use the image, it is to show it on a map as a markup and show one image or another depending on the type
const imageMarker = imgSelect
As commented
You will have to use Array.map
You are only getting 1 image because you are using a return in for loop. So you return on 1st iteration and remaining iterations never gets evaluated
Sample:
const getUrl = (type) => {
switch (type) {
case 'one':
return new URL('../assets/images/image1.png',
import.meta.url).href
break;
case 'two':
return new URL('../assets/images/image2.png',
import.meta.url).href
break;
case 'three':
return new URL('../assets/images/image3.png',
import.meta.url).href
break;
default:
return null
break;
}
}
const imgSelect = () => {
obj.value = obj.value.map(
(item) => ({...item, url: getUrl(item.type)})
)
}
If you have predefined list of images based on type, you can even create a predefined map and fetch from that. No need to create for every iteration.
const URL_TYPE_MAP = {
one: new URL('../assets/images/image1.png', import.meta.url).href,
two: new URL('../assets/images/image2.png', import.meta.url).href,
three: new URL('../assets/images/image3.png', import.meta.url).href,
}
const getUrl = (type) => {
return URL_TYPE_MAP[type]
}

javascript retrieve value from a map

I am trying to develop a google script app.
Here is one function to create an array map.
function getOffices(){
var result=AdminDirectory.Groups.list({domain:"example.com"})
result=result.groups.filter(function(group){
var str=group.email;
return str.search("-office#example.com")>=0;
})
result=result.map(function(group){ return {name:group.name,email:group.email}})
return result;
}
I have created a logic piece, that I want to execute certain actions based on the results, that looks like this:
var getOrgUnitPath = (accountOffice, accountType) => {
if (accountType === 'facilitator') {
return 'Limited Accounts/Gmail Plus Calendar';
} else {
switch (accountOffice) {
case accountOffice.includes('Boston'):
return "/Standard-Access/Boston";
break;
case accountOffice.includes('New York'):
return '/Standard-Access/New York';
break;
case accountOffice.includes('Lincoln'):
return '/Standard-Access/Lincoln';
break;
default:
return '/Standard-Access';
break;
}
}
};
Lastly, I try to set the organizational unit -- which is ultimately what i am trying to do, but can't seem to get the syntax right, I have tried everything I can think of. I have hardcoded the "accountType" and it worked, so I know the formObject.accountType is functioning properly.
orgUnitPath: getOrgUnitPath(accountType, formObject.accountType),
Thanks in advance!
This is a wrong usage of switch case.
if accountOffice's would be just New York, Boston, Lincoln. Remove the complex condition and replace with
switch (accountOffice) {
case "Boston":
return "/Standard-Access/Boston";
break;
case "New York":
return "/Standard-Access/New York";
break;
case "Lincoln":
return "/Standard-Access/Lincoln";
break;
default:
return "/Standard-Access";
break;
}
If not, use if-else if you have complex condition to check rather than simple match cases
if (accountOffice.includes("Boston")) {
return "/Standard-Access/Boston";
} else if (accountOffice.includes("New York")) {
return "/Standard-Access/New York";
} else if (accountOffice.includes("Lincoln")) {
return "/Standard-Access/Lincoln";
} else {
return "/Standard-Access";
}
I rewrote the code so I could get a better understanding of it. From what I can tell, getOffices lists all offices and getOrgUnitPath returns a path including the first office that matches the ordered list of offices ['Boston', 'NY', 'Lincoln']. If that's the case, what's missing is that the first argument to getOrgUnitPath should be getOffices(), right? (Notice it is the execution of the function getOffices.)
Here's the code "simplified" to my liking. I hope it helps:
const getOffices = () => {
const bigList = x.y.list({ domain: 'example.com' }) // ?
return bigList
.filter(cur => ~cur.email.search('abc'))
.map(cur => ({
name: cur.name,
email: cur.email
}))
}
const getPath = (accOffice, accType) => {
if (accType === 'xyz')
return 'foobar'
const city = ['Boston', 'NY', 'Lincoln']
.find(cur => accOffice.includes(cur))
return `yadayada/${city}`
}
const theFinalObj = {
orgUnitPath: getPath(getOffices(), 'rightHardcodedType')
}

Transform my if conditional to switch case with regex option: javascript

I would like to transfer my if condition to switch case, because then it would look nicer in my code. (I have several switch case).
I can't set the switch parameter to true, because this will break the logic of my code.
if (/(.*)_ERROR/.test(action.type)) {
alert('ok'); //working
}
switch (action.type) {
case /(.*)_ERROR/:
alert('ok'); //not working
break;
...
}
How to write it? The idea is to enter the case only if the word "error" is in the string
Not very ideal but you can use named groups:
const reg = /(?<warning>(.*)_WARNING)|(?<error>(.*)_ERROR)|(?<info>(.*)_INFO)/; // warning, error, or info.
const match = action.type.match(reg);
if (match) {
const groupName = Object.keys(match.groups).find(group => match.groups[group] !== null);
switch (groupName) {
case 'error': // like TEST_ERROR
case 'warning': // like TEST_WARNING
case 'info': // like TEST_INFO
default:
}
}

How to pass multiple values via operator chain to map operator? In NgRx Effect

I am working on Effect, in which I load new data form REST endpoint and then dispatch action to update store with received data. Together with composing searchUrl, there is some computation of newCurrentPage.
How to pass newCurrentPage value along with search request to following operatos?
Code looks like this:
#Effect()
tablePageChanged = this.actions$
.pipe(
ofType(action.tablePageChanged ),
withLatestFrom(this.store.select('tableData')),
switchMap(([action, tableData]) => {
let newCurrentPage: number;
let searchUrl: string;
switch (action.navPage) {
case NavigationPage.First:
newCurrentPage = 1;
searchUrl = tableData.devsTable.firstUrl;
break;
case NavigationPage.Previous:
newCurrentPage = tableData.devsTable.currentPage - 1;
searchUrl = tableData.devsTable.previousUrl;
break;
case NavigationPage.Next:
newCurrentPage = tableData.devsTable.currentPage + 1;
searchUrl = tableData.devsTable.nextUrl;
break;
case NavigationPage.Last:
newCurrentPage = Math.ceil(tableData.devsTable.totalRecords / tableData.devsTable.pageSize);
searchUrl = tableData.devsTable.lastUrl;
break;
default:
break;
}
// HERE: I want to return also 'newCurrentPage', so that I can pass it to 'handleSuccessfulResponse' later
return this.http.get<UserSearchResponse>(searchUrl, {observe: 'response'});
}),
withLatestFrom(this.store.select('tableData')),
map(([response, tableData]) => {
// HERE: I want to get 'newCurrentPage' to pass it to the 'handleSuccessfulResponse' function
return this.handleSuccessfulResponse(response, tableData);
})
);
This RxJS thing is quite new for me, and I haven't quite wrapped my head around it yet, so please be explicit. Thanks!
You can move operators to the closure where this variables were defined, like this:
switchMap(([action, tableData]) => {
// ...
return this.http.get<UserSearchResponse>(searchUrl, {observe: 'response'}).pipe(
// `tableData` and `newCurrentPage` is available here
map(response => this.handleSuccessfulResponse(response, tableData))
);
})
Or use map operator to return pair of [response, newCurrentPage] so it can be used later

Categories

Resources