HTTP GET request to server only occasionally works - javascript

I am using jQuery Ajax to make a GET request. Sometimes It works perfectly, but other times I get a 403 forbidden when I look at the chrome dev tools console. Is this a server issue or my code?
When I sign in, I get the encrypted password, username and ID back from the server. I then store that in LocalStorage since the request I am trying to get working is on another page. I am also required to make a client token from those fields using AES encryption. For that, I am using CryptoJS. For my request, I am required to send in the password, username, ID and client token that has been retrieved from LocalStorage. I realize that may not be a good way to go about it, but I do not have control of the server side.
Edit: Here is my Ajax call to the service:
$("#system-form").submit(function (e) {
$.ajax({
type: "GET",
url: "myurl",
data: "User.Username=" + localStorage.getItem("guid") + "&User.Password=" + localStorage.getItem("password") + "&User.SecUser=" + localStorage.getItem("secUser") + "&ClientAppID=" + localStorage.getItem("ClientAppId") +"&"+ $(this).serialize(),
})
.done(function(data) {
//parse data
})
.fail(function (xhr, textStatus, error) {
console.log(JSON.stringify(xhr.responseText));
});
e.preventDefault();
});

I realized my issue was that I need to URL encode my auth parameters. I fixed this by using encodeURIComponent.

Related

PHP Session ID / Session variable value changing on every request from react axios / ajax call

I have just started working with react js and started facing some issue from some client side systems. while posting data to a php file from react js with (axios or ajax) session_id() resetting and regenerating on every request/call. also session variable resetting. i have tried some solutions from stackoverflow but nothing worked.i have faced this issue from my localhost and some other systems. but working with some others systems too. it's like working with 50% system and not working with 50% system.
But if i do this same thing without react js from normal html file with ajax to php file. session id is not resetting or regenerating.
PHP FILE
<?php
session_start();
$session_val = session_id();
header("Access-Control-Allow-Origin: *");
echo $session_val;
?>
AJAX CALL FROM REACT JS
$.ajax({
url: "http://localhost/test.php",
type: "POST",
data: {
action: action,
},
success: function (data) {
},
error: function (jqXHR, text, errorThrown) {
console.log(jqXHR + " " + text + " " + errorThrown);
},
});
AXIOS CALL
axios
.post('http://localhost/test.php', this.state)
.then(response =>{
console.log(response.data);
})
.catch(
error => {
console.log(error)
});
Looks like your browser isn't sending the Cookie header with the AJAX request (they do this by default, but I can't figure out why it's not sending it).
When your PHP server sees that there's no Cookie header, it assumes that the SESSONID is not set and creates a new one and instructs your client to store the new SESSIONID in its cookies. Since this new SESSIONID is not sent in the next request, your server again assumes the same thing, and again creates a new SESSIONID. And this process happens everytime.
To learn more about how cookies work, you could refer Using HTTP Cookies.
You can manually get your cookies and add it as a Header to your AJAX request in JQuery like so:
$.ajax({
url: "http://localhost/test.php",
type: "POST",
headers: {"Cookie": document.cookie},
data: {
action: action,
},
success: function (data) {
},
error: function (jqXHR, text, errorThrown) {
console.log(jqXHR + " " + text + " " + errorThrown);
},
});
headers attribute of the AJAX object is used to add extra headers to your HTTP Request. Here we're getting the cookies the browser has stored using document.cookie and adding it to the Cookie header in the request headers.
Let me know if this solves your issue.
As per Shreyas Sreenivas comment i used xhrFields: { withCredentials: true } for ajax and
axios.post('https://example.com/file.php', this.state,{withCredentials: true});
for axios and it worked. But some Cross-Origin Request Blocked error occurred which needs to be fixed.

Permission Denied on Ajax xml call, Dynatrace Dashboard

I've been trying to get an XML response from a Dynatrace server using REST api. I have no trouble getting an XML response when I put the url through Postman, and I am able to receive a 'text' datatype response from ajax, but not an 'xml' response. I plan to parse this data into json for future use.
The code I am using so far is:
function getXML() {
basicAuth = "Basic " + id + ":" + password;
$.ajaxSetup({
async: false
});
$.ajax({
type: 'GET',
url: dynUrl, //this is the function we defined above
dataType: 'xml',
headers: {
'Authorization': basicAuth //this is for basic authentication, you've already provided UID and PWD above.
},
//when we succeed, the function below will be called.
success: function(respt)
{
data = respt;
}
});
}
This is called in the following function.
function XMLRespond()
{
getXML();
//dom = parseXml(data);
//json = xmlToJson(dom);
return data;
}
data is called and displayed by an html hosted on localhost. However, when I run this, I get a blank screen and the console says "Permission Denied". My debugger gives me:
Failed to open http://localhost:8080/api/Test.html
Any help on this issue would be greatly appreciated!
Solved the issue. Turns out IE (and I suspect other Browsers) can't straight up display data. Converting data to a string bypassed this problem.

jquery $.ajax gives 404 not found. Im using node.js with express

This jquery:
$.ajax({
method: "post",
data: JSON.stringify(data),
contentType: "application/json",
url: "http://localhost:3000/ajax"
});
is giving error 404 not found. Here is my server side:
router.get('/ajax', function(req, res ,ext){
var strings = ["rad", "bla", "ska"]
console.log('body: ' + JSON.stringify(req.body));
console.log("AJAX RECEIVED");
res.send(strings);
});
so i do have the /ajax route. When i go to http://localhost:3000/ajax im able to acccess the site . However, when I try to access it with the ajax method I get the 404 error. So im wondering if the error could be with my code, or if it could be the firewall on my computer. Im actually using a company computer that has a firewall that blocks certain sites and I cannot disable it.
If you want to do a HTTP POST, use router.post, not router.get.
your $.ajax call is using POST but your route in express.js is only listening for GET requests.
When you hit the URL through the browser it's doing a GET, so it worked.
You would need to set up a route for POST with router.post('/ajax', ...)

Getting a parseerror from jQuery $.ajax post return using jsonp from Trakt.tv api

Working with the Trakt.tv API. It looks like I'm sending valid json as I'm able to authenticate but the return I receive is a parse error.
Resource interpreted as Script but transferred with MIME type text/html:
http://api.trakt.tv/recommendations/shows/myApiKeyCompleteNumbers?callback=jQuery111000155555475132972_1397674204444&{%22username%22:%22userName%22,%22password%22:%22mySha1PassComplete%22}&_=1397674207093
Uncaught SyntaxError: Unexpected identifier
The return says:
Disallowed Key Characters.
I'm using:
jQuery 1.11.0
Thanks in advance for any help or guidance
$(document).ready(function () {
function success(data) {
alert('data: ' + data);
}
var traktUser = 'myUserName';
var traktHash = 'mySha1Password';
var traktApi = 'myApiKey';
var data = {
'username': traktUser,
'password': traktHash
};
var postData = JSON.stringify(data);
var apiUrl = 'http://api.trakt.tv/recommendations/shows/' + traktApi;
$.ajax({
type: 'POST',
url: apiUrl,
data: postData,
contentType: 'application/json',
dataType: 'jsonp',
}).
done(success);
}); //document ready
You can't make a POST request using JSONP, jQuery is ignoring the POST instruction and making a GET request.
Your data is being placed in the query string and is not properly URL Encoded.
The server is responding with an HTML document containing an error message instead of a JavaScript script formatted according to JSONP rules.
It looks like the API you are trying to use does not support JSONP at all. Since you are passing your own user credentials in the request, this makes sense. JSONP is a hack to work around the Same Origin Policy that is implemented by browsers (these days we can use CORS instead) and there is no point in using it unless you want end user browsers to access the API directly. Since end user browsers couldn't access it without being given your username and password, it doesn't seem likely to be intended to be used that way.
Process the data from the API on your server instead.

Send a request to a route in Symfony2 using Javascript (AJAX)

I have a working prototype Symfony2 RESTful webservice which I am still working on and I am trying to figure out how a client can send JSON or consume JSON data from the webservice. All I need is an example(s) on how to send a request or post data to it and I can figure out the rest. From my browser, if I visit http://localhost/app_dev.php/users.json, I get the correct result from my database as JSON, e.g.
[{"id":1,"username":"paulo","username_canonical":"paulo","email":"a#ymail.com","email_canonical":"a#ymail.com","enabled":true,"salt":"66r01","password":"UCxSG2v5uddROA0Tbs3pHp7AZ3VMV","last_login":"2013-12-03T13:55:15-0500","locked":false,"expired":false,"roles":[],"credentials_expired":false,"first_name":"Monique","last_name":"Apple"}, ... etc.
All other routes are working correctly and I can get the same result by using httpie or cURL. Now, the problem I am trying to solve is to get the same JSON data using AJAX (and mobile iOS, Android, etc later). Here is my attempt at using AJAX JS:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$.ajax({
dataType: "json",
type: "GET",
url: "http://192.168.1.40/symfony/web/app_dev.php/users.json",
success: function (responseText)
{
alert("Request was successful, data received: " + responseText);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
</script>
The AJAX alerts the following results which indicates an error:
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
What am I doing wrongly and how can I solve the problem. Kindly give an example.
This is a cross-domain request issue. You need to make the request to the same domain you are on. This is a browser-level security feature.
For example, you can only request URLs on http://192.168.1.40 if you are currently ON http://192.168.1.40. This means that a request from http://192.168.1.39 (for example) won't work

Categories

Resources