I would like to disable cache on getting a request in vue environment. I already tried this but it does not work.
api.js (file)
getCall: () => {
return performAsyncGet(apiConfig.getCall.url,
requestConfigJSON, _REQUEST_TOKENS.getCall, apiConfig.getCall.cache)
.then(
response => response.data
);
},
(apiConfig.js) (file)
getCall: {
url: `${servicePathPrefixOrDomain}/api/getCall`
cache: false
}
Does anybody know how to disable the cache, when making a get request in vue.js?
Thanks in advance!
To avoid caching you can make your url unique by appending timestamp as a querystring parameter like this:
getCall: {
url: `${servicePathPrefixOrDomain}/api/getCall?_t={new Date().getTime()}`
cache: false
}
In this way for every ajax call the url will be unique due to different timestamp and browser will not cache the response.
Is solved adding the next code in the header:
const requestConfigJSON = {
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
}
};
Related
This was my jQuery code before. Now I want to change it to fetch.
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val(), pcat: jQuery('#cat').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
I have changed the code to this now but I am getting bad request 400 status code
document.querySelector('#keyword').addEventListener('keyup',()=>{
let data = {
action: 'data_fetch',
keyword: document.querySelector("#keyword").value
};
let url = "<?php echo admin_url('admin-ajax.php'); ?>";
fetch(url, {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.text())
.then((data) => {
document.querySelector("#datafetch").innerHTML = data;
})
.catch((error) => {
console.error('Error:', error);
});
})
Am I missing something? It is from WordPress if this helps somehow.
You forgot the pcat property in the data object
jQuery, by default, sends form encoded data, not JSON encoded data. Use a URLSearchParams object instead of a string of JSON and omit the content-type header (the browser will add the correct one for you).
In your jQuery code you defined data as
data: { action: 'data_fetch', keyword: jQuery('#keyword').val(), pcat: jQuery('#cat').val() },
and in fetch you defined it as
let data = {
action: 'data_fetch',
keyword: document.querySelector("#keyword").value
};
so, you are not passing some value which was previously passed. No wonder that your server errors out. Let's change your code to
let data = {
action: 'data_fetch',
keyword: document.querySelector("#keyword").value,
pcat: document.getElementById("cat").value
};
and try this out. If it still works, then you will need to find out what differs in the request and make sure that the request you are sending via fetch is equivalent to the request you formally sent via jQuery, then it should work well, assuming that the client-side worked previously with jQuery and the server-side properly handled the requests.
I am calling axios.post with the url:
/constituents/941802/activities/rid/941802/rtype/Constituent/to/2021-10-01/type/Vol%2E%20Time?format=json
But it sends
/constituents/941802/activities/rid/941802/rtype/Constituent/to/2021-10-01/type/Vol.%20Time?format=json
How do I prevent this?
Using Axios 0.21.1
I have seen the suggestion of adding a trailing '/' at the end of the path, but that does not prevent the conversion and the server still finds the format to be illegal.
Sample:
post(url) {
return axios.post(
url,
{},
{responseType: 'json', headers: { 'Content-Encoding': 'gzip' }}
)
}
I'm trying to send form data from a NativeScript app to a TYPO3-Webservice.
This is the JavaScript I'm using:
httpModule.request({
url: "https://my.domain.tld/webservice?action=login",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({
username:username,
password:password
})
}).then((response) => {
console.log("got response");
console.log(response.content);
//result = response.content.toJSON();
callback(response.content.toJSON());
}, (e) => {
console.log("error");
console.log(e);
});
But I can't read this data in the controller. Even with this:
$rest_json = file_get_contents("php://input");
$postvars = json_decode($rest_json, true);
$postvars is empty. $_POST is empty, too (which is - according to some docs - because the data is sent as JSON and thus the $_POST-Array isn't populated.
Whatever I do, whatever I try, I can't get those variables into my controller.
I tried it with fetch as well as with formData instead of JSON.stringify, same result.
I might have to add, that when I add the PHP-part in the index.php of TYPO3, $postvars is being populated. So I guess something goes missing, until the controller is called.
Any ideas?
the nativescript part seems ok, your problem must be corrected in the server side.
i use similare call and its works
// send POST request
httpModule.request({
method: "POST",
url: appSettings.getString("SERVER") + '/product/list',
content: JSON.stringify(data),
headers: {"Content-Type": "application/json"},
timeout: 5000,
}).then(response => { // handle replay
const responseAsJson = response.content.toJSON();
console.log('dispatchAsync\n\tresponse:', responseAsJson);
}, reason => {
console.error(`[ERROR] httpModule, msg: ${reason.message}`);
});
I am to post an Axios request because using get results in a 414 error.
Here's the object:
rows= {
0 : {
"name":"Thor",
"status":"active",
"email":"somuchlightning#kaboom.io",
},
1 : {
"name":"Mesa",
"status":"active",
"email":"big-mesa#tundra.com",
},
2 : {
"name":"Jesper",
"status":"stdby",
"email":"jes#slap.net,
},
}
This is just a sample of the object's format. There is 400+ elements in the real one, thus post instead of get. I am having trouble properly building the form-data on this one. Here's what I have:
let data = new FormData();
Object.keys(rows).forEach(key => data.append(key, rows[key])); // <--- this doesn't do
data.set('target', target); // <---- this comes through just fine
axios({
method: 'post',
url: 'byGrabthorsHammer.php',
data: data,
headers: {'Content-Type': 'multipart/form-data'}
}).then(function(response) {
if (response.error) {
console.log('failed to send list to target');
console.log(response);
} else {
console.log('response: ');
console.log(response);
}
});
What comes through is just [Object][Object]' when ivar_dump($_POST);`. This is not what I want. How could I rewrite this properly so I get the data to the other side (like GET...).
Yow bro, POST Are for inserting new stuff, instead of doing a post you need a patch
axios.patch it is basically the same. And it won’t fix your issue.
To fix the issue you need to set the Content-Type to application/json, then on yow
axios.post(url, data: JSON.stringify(bigObject))
.then(Rea=>Rea)
You could try stringifying the data. JSON.stringify(data)
The below code is used to work in chrome and suddenly stopped due to chrome recent change "Disallow sync XHR in page dismissal". The recent update on Crome early April 2019, I think Chrome 73.0.3683.103 stopped this feature and they have suggested sendBeacon or fetch keepalive. I will post what I was tried so this might help someone else.
https://www.chromestatus.com/feature/4664843055398912
$(window).on('beforeunload', function (e) {
//ajax call used work in Chrome
}
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
I know there are several related posts related to the same situation, but still couldn't find a solution. I tried several ways to make a server call.
Step 1:
$(window).on('beforeunload', function (e) {
if (navigator.sendBeacon) {
navigator.sendBeacon('url', 'data');
} else {
$.ajax({
type: 'POST',
url: 'url',
data: null,
contentType: 'application/json;',
async: false
});
}
}
This did not work due to content type - application-json
Step 2:
$(window).on('beforeunload', function (e) {
var data = { ajax_data: 22 };
var blob = new Blob([JSON.stringify(data)], {type : 'application/json'});
navigator.sendBeacon('url', blob);
}
This code did not work due to sendBeacon only support these content-types
multipart/form-data
application/x-www-form-urlencoded
text/plain
Step 3:
$(window).on('beforeunload', function (e) {
if (fetch) {
fetch(url, {
method: "POST", headers: { "Content-Type": "application/json" }
}).then(function (response) {
console.log(response.statusText);
}).then(function (response) {
console.log(response.statusText);
});
return false;
} else {
$.ajax({
type: 'POST',
url: 'url',
data: null,
contentType: 'application/json;',
async: false
});
}
}
This code works!. But only when you click on a link on the page or click on the Signout button. I need to work on this server method on when the user leaves the page on clicking on a link, signout, tab close and browser close.
Step 4:
$(window).on('beforeunload', function (e) {
e.stopPropagation();
e.preventDefault();
fetch('url', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
}
This will show a popup "Leave site?", I don't want to the user to show any popup.
Step 5:
$(window).on('beforeunload', function (e) {
setTimeout(function ()
{
fetch('url', { method: 'POST', headers: { 'Content-Type': 'application/json' } });
}, 3000);
return false;
}
Also same as step 4, shows the "Leave site popup."
Now I'm running out of options and could not found a solution yet. Any help appreciated. I need a server call before page unloads by clicking on a link, logout, tab close, browser close. The above code will work if you put a breakpoint, which means it needs some time delay to send the server call before page unload. I don't mind putting a timeout if the user does not see any popup like "Leave site?"
This is an old question, but you need to use fetch with the keepalive flag set to true in the beforeunload event:
fetch(url, {
method: "POST",
keepalive: true,
headers: {
"Content-Type": "application/json"
}
});
sendBeacon does not behave the way documentation claims it does. In my testing, it did not respect the MIME type of a Blob in the request body, even if the Blob was a "supported" MIME type.
Use fetch instead. It gives you more control over the request headers, while guaranteeing that your request will be issued like sendBeacon supposedly does.
You might also need to bind the beforeunload event in the body of the page. A jQuery binding might not work for beforeunload.