I have the following code which basically does the following:
When the user clicks the button, an encoded text is sent to an
API
which takes care to decode it. Then the decoded text is set as a query on a Google link which is opened on a new tab.
JAVASCRIPT
// Reference:
// https://base62.io/
let message_encoded = 'T8dgcjRGkZ3aysdN'; // base62('Hello World!'')
let way = 1;
$(function () {
$('.button_test').click(async function() {
let url_api = 'https://api.base62.io/decode';
let response;
switch (way) {
case 1: /* this works */
response = await jQuerySyncPost(url_api, { data: message_encoded });
break;
case 2: /* this DOES NOT work */
response = await fetchSyncPost(url_api, { data: message_encoded });
break;
case 3: /* this DOES NOT work */
response = await axios.post(url_api, { data: message_encoded });
break;
}
alert('Next, let\'s look on Google for: "' + response.data.decoded + '"');
let message_decoded = response.data.decoded;
let url_google = 'https://www.google.com/search?q='+encodeURIComponent(message_decoded);
openNewTab(url_google);
});
});
function jQuerySyncPost(url, params) {
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: params,
async: false,
success: function (response) {
response = {
data: response
};
resolve(response);
},
error: function (jqXHR, textStatus, errorThrown) {
reject({
jqXHR: jqXHR,
textStatus: textStatus,
errorThrown: errorThrown
});
}
});
});
}
function fetchSyncPost(url, params) {
return new Promise((resolve, reject) => {
let config = {
headers: {
'content-type': 'application/json; charset=UTF-8',
},
body: JSON.stringify(params),
method: 'POST',
};
fetch(url, config)
.then(response => response.json())
.then(response => {
let result = {
data: response,
};
resolve(result);
});
});
}
function openNewTab(url) {
window.open(url, '_blank');
}
HTML
<button class="button_test">Click Here</button>
CSS
.invisible {
visibility: hidden;
}
.button_test {
margin-left: 200px;
margin-top: 100px;
font-size: 50px;
}
The code above is working fine with the jQuery
Ajax call (through custom function):
let response = await syncPost(url_api, { data: message_encoded });
But, in the other hand, if I use axios
, then I get a popup blocked
alert on the browser which prevents the new tab to get opened:
let response = await axios.post(url_api, { data: message_encoded });
Here you have the JSFiddle
: https://jsfiddle.net/otyzadju
where { way=1 }
works, but { way=2, way=3 }
don't.
On both cases the call to the API
via Ajax is done synchronously but the problem is that it seems that axios
is disconnecting what happens next from user's action when called after clicking a button.
Any idea on how to make this work with axios
?
If possible, please, provide your solution on a forked JSFiddle
link.
Thanks!