Wrong additional parameters in $.ajax - javascript

I'm trying to call a web service to get some data. I need pass this URL in a GET method:
http://localhost/ecosat/ws/api.php?t=vw_motorista
But, when I look in Chrome Developer Tools, the link is:
http://localhost/ecosat/ws/api.php?t=vw_motorista&_=1397500899753
I'm not passing this parameter: &_=1397500899753
With this additional parameter, I received a 500 error. I can't change the web service to handle this.
What's going on? Is Chrome is changing my code?
This my Ajax
function get(pURL, pToken) {
var ret = null;
$.ajax({
type: "GET",
dataType: "json",
async: false,
timeout: globalTimeOut,
cache: false,
url: pURL,
headers: {"Token": pToken},
error: function(request, status, error) {
ret = null;
},
success: function(data) {
ret = data;
}
});
return ret;
}

You're probably using cache: false setting in your ajax query. It adds a _ parameter with a timestamp value, to make sure that your ajax call doesn't get cached by the browser.
Remove this setting, if you don't need it. But if you need make sure caching is disabled, you could try two things:
add your own parameter with a timestamp to your query, e.g. {ts: new Date.getTime()}, or
if possible, add headers to the web server response. See this question

Related

jQuery sending undefined "_" parameter

I am trying to write a script that gets COVID-19 numbers from the Ontario Database, but I keep getting the following error:
"invalid value \"_\""
Upon further investigation, the URL that is trying to be accessed contains the following parameter:
&_=1610496351832
As you can see in my code below, I never define such a variable:
var data = {
resource_id: '8a89caa9-511c-4568-af89-7f2174b4378c' // the resource id
};
$.ajax({
dataType: 'jsonp',
data: data,
url: 'https://data.ontario.ca/api/3/action/datastore_search'
});
Is there any way I can remove the _ object from the request?
The file I am trying to access is located at the following URL, where data is the resource_id.
https://data.ontario.ca/api/3/action/datastore_search?resource_id=8a89caa9-511c-4568-af89-7f2174b4378c
That is an automatic value generated by JQuery to avoid the cache.
Add the following to your script if you want to get rid of the underscore param:
var data = {
resource_id: '8a89caa9-511c-4568-af89-7f2174b4378c' // the resource id
};
$.ajax({
dataType: 'jsonp',
data: data,
type:'GET',
cache: true,
url: 'https://data.ontario.ca/api/3/action/datastore_search'
});
It only occurs in GET requests, you can play around with this setting. But remember, the automatic underscore param is included intentionally to avoid the request cashing.

Jquery: Probably a syntax Issue in ajax() method - Value not getting sent

I'm able to dump value of the variable message in console .
But im not able to send it off in POST Request.
AJAX call:
chat.throwmsg = function(message) {
if ($.trim(message).length != 0) {
console.log(message);
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: { method: 'throw', message: message} ,
success: function(data) {
chat.fetchmsgs();
$('textarea#entry').val('');
}
});
}
}
This maybe due to wrong syntax, but I've tried both single and double quotes, and combination as well .
With a wild assumption, you are not having any error messages in developer console and chat.php has a post handler forthese parameters
Since your data is JSON, please change the code as this way and have a try..
var temp={ method: 'throw', message: message};
var param=JSON.stringify(temp);
$.ajax({
url: 'ajax/chat.php',
type: 'post',
data: param ,
dataType: "json",
success: function(data) {
chat.fetchmsgs();
$('textarea#entry').val('');
}
});
after reviewing the code I could not find any issues that restrict the data to be sent along with ajax request,if you are having any syntax errors you should have been warned prior the request initialization, however I recommend you to check the request header in the network tab of browser console and see your sending data along with the request if it's there you probably need to check the code of getting the post data in your server-side implementations

Javascript API POST Request from URL

Forgive me if I have titled this tread wrong, I don't know the correct terminology.
I have a link with values included, they are: id and environment therefore the url it formatted such ad https://foo.com?id=1234&e=s
With this url I need to take the id and the environment (Stage or production) and create a post body to set a flag as true.
So if e=s (environment = stage) I need post to
https://services-stage.foo.com/api/account//flag
Or if e = p (production)
https://services.foo.com/api/account//flag
Where = the id in the url
With POST body:
{
"type": OptionFlag,
"flag": true //Flag should be set to true
}
My problem is I don't know where to start with my limited javascript knowledge. I have created GET requests form api's in the past but never POST and never with parameters in the URL.
I now understand how to handle the post, however I am still at a loss on how I would get the Id and the environment data from the url to then pass them to the ajax url in the function.
function CustomerId(){
//Function for getting id number from URL
}
function apiEnvironment(){
//Function for getting environment from URL
}
function OptOut(CustomerId, apiEnvironment) {
jQuery.ajax({
type: 'POST',
url: apiEnvironment + '/api/v1/account/' + CustomerId + '/optOut',
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data : data,
success: {
}
});
}
This Is what I have so far...

Using both cached and non-cached JSON from an Ajax request

I have two JSON sources: getCachedJSON.php and getNotCachedJSON.php. As suggested by the names, the client should cache the results from the first but not the second. Both of these files will issue the appropriate headers to tell the client to cache or not cache the data.
How is this best accomplished?
I came up with the following, but don't know if this is how it should be done. And if it is the right way, should the cached JSON be first requested and then the non-cached JSON, or the other way around?
$.ajax({
//cache: true,
url: "getCachedJSON.php",
dataType: "json",
success: function(cachedJSON) {
$.ajax({
//cache: false,
url: "getNotCachedJSON.php",
dataType: "json",
success: function(notCachedJSON) {
var allJSON = $.extend({}, cachedJSON, notCachedJSON);
console.log(allJSON);
}
});
}
});
Browser manages caching for you. Each time when you're making GET request the browser check if it has this resources in its cache. If it has it then request is not made. To tell browser how to control caching you have to use http headers like cache-control and max-age (try to google for details). You have to set these headers when browsers access you server. You can use chrome's dev tools (network) to inspect if there is any requests made. There you will see if resource is obtained from cache or from request.
If you want event better cache control I recommend you to use service workers or browser sql databases.
Hope I understood your question right.
If you want to make a server request and cache it on the client side, you can make use of the browser's local storage.
You could do something along the lines of this:
var allData = cached(nonCached);
function cached(callback){
var cachedData = localStorage.getItem('cached');
// if locally stored data is found, pass it to the callback
if(cachedData){
callback(JSON.parse(cachedData));
} else {
// Else get it from php script, store it, and pass to callback
$.ajax({
url: "getNotCachedJSON.php",
dataType: "json",
success: function(cachedData) {
var key = 'cached';
localStorage.setItem(key, JSON.stringify(cachedData));
callback(cachedData);
}
});
}
}
function nonCached(cachedData){
$.ajax({
url: "getNotCachedJSON.php",
dataType: "json",
success: function(nonCachedData) {
return $.extend({}, cachedData, nonCachedData);
}
});
}

How to ensure ajax call is always made (not fetched from cache)

I have the following code. The function is called multiple times depending on the user checking or unchecking checkboxes.
This works in all browsers except IE10/11. In IE, the ajax call is only made once for a particular ID. Subsequent calls are not actually sent to the server, but appear to be fetched from the cache.
In F12 developer tools, the call appears to be being made to the server, but Fiddler shows that it is not actually happening.
F12 also shows a 304 response to the call.
How do I ensure that the call is always made to the server?
function updateReportTypes(event) {
var value = event.currentTarget.value;
if (event.currentTarget.checked) {
$.ajax({
url: "/PropertySearch/Order/AddReportType?id=" + value,
dataType: 'html',
success: function (data) {
$('#reportTypes').html(data);
hideProgress();
}
});
}
else {
$.ajax({
url: "/PropertySearch/Order/RemoveReportType?id=" + value,
dataType: 'html',
success: function (data) {
$('#reportTypes').html(data);
hideProgress();
}
});
}
}
Simple set the:
cache: false
argument to $.ajax(). When you do that, jQuery will automatically add a unique paramter onto the URL which prevents any caching of the request.
Using that option would look like this:
$.ajax({
url: "/PropertySearch/Order/AddReportType?id=" + value,
dataType: 'html',
cache: false,
success: function (data) {
$('#reportTypes').html(data);
hideProgress();
}
});
jQuery doc on this option: http://api.jquery.com/jquery.ajax/
I'm not familiar with this specific issue, but if all else fails, you should be able to add a dynamic, cache-busting value, such as a timestamp, to make your URL unique:
url: "/PropertySearch/Order/RemoveReportType?id=" + value + "&" + Date.now().toString()

Categories

Resources