var username = 'xxxx';
var password = 'zzzz';
var xmlstring="<root><request><AADHAAR_ID>aaaaaaa</AADHAAR_ID><NAME>hhhhhhh</NAME><DOB></DOB><MOBILENO></MOBILENO><FLAG>QVVUSA==</FLAG><RESPONSE_CODE></RESPONSE_CODE><ERROR_CODE></ERROR_CODE><OTP></OTP><PIN></PIN><DEPT>aswww</DEPT><VENDORID>MTAwSFBN</VENDORID></request></root>";
function make_base_auth(username, password) {
var tok = username + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax({
type: "POST",
async: true,
dataType:"xml",
contentType: "application/xml",
url: 'http://test/test/test?reqXml='+xmlstring,
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', make_base_auth(username, password));
},
success: function(){console.log('success');
alert('success');
},
error: function(data) {console.log('error');
console.log(data);
}
});
Hi, above is my code please tell what i have missed.I'm attempting to do a simple PSTrequest from my local server and this request requires an Authorization header in order to function correctly. I have performed the POST request and retrieved the data successfully in Postman, Ajax results in a "Invalid HTTP status code 302" error and My error is XMLHttpRequest cannot load .....Response for preflight is invalid (redirect)
Why my $.ajax showing "preflight is invalid redirect error"?
Possible answer check link.
I think you have possible solution try to pass header or change http to https. please refer link for better solution.
Related
I have an AJAX POST that is sending back a successful response from my PHP file newPNRsubmit.php :
if(isset($_POST['ticketentry'])){
$_SESSION['ticketEntry'] = 1;
header("location: pnr-details?id=".$pnrid);
}
However I would like to use the AJAX response that I am receiving into window.location
This is the response:
XHR finished loading: GET "https://example.com/pnr-details?id=240".
This is my AJAX structure:
$.ajax({
type: "POST",
url: "newPNRsubmit.php",
data: {
bookingdate: bookingdate,
airline_id: airline_id
},
cache: false,
success: function(data, url) {
$('#NewPNRModal').modal( 'hide' );
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
return false;
How can I correctly parse the URL that I am receiving into window.location ?
UPDATE: This is the response from console tab. The second GET XHR is showing the link I need for window.location. Should I update the header location to send JSON data in my PHP file in order for this to work?
Either return a URL in the body instead of a header, or get the header like so:
success: function(data, URL, jqXHR) {
window.location.href = jqXHR.getResponseHeader("location");
}
i have the ajax request for fetching the information if user is still logged in or not let's say checking its session, and also i have enabled the csrf protection also and the GET is working fine in all aspects but the problem is only with POST from ajax, i have also turned off the re-generation of token and also did pass the new token to every ajax request, but still it gives me an error :
The action you have requested is not allowed.
fetching token :
var getToekn = function(){
return $('meta[name=csrf_token]').attr('content');
}
call to userLog every 1 minute:
var userLog = function () {
var formdata = new FormData();
formdata.append('csrf_',getToken);
$.ajax({
url: site_url + 'action=userCheck',
type: 'post',
dataType: 'json',
data:formdata,
processData:false,
success: function (d) {
if (d.login === 'true') {
jQuery('meta[name="csrf_token"]').attr('content', d.csrf);
console.log('loggedin: True');
} else if (d.login === 'false') {
if (jQuery('#js_login_again').legnth) {
popup('js_login_again', 'o');
jQuery('meta[name="csrf_token"]').attr('content', d.csrf);
} else {
$.ajax({
url: site_url + '?pop=loginagain',
type: 'post',
dataType: 'html',
success: function (data) {
var popup = $(data).filter('#js_login_again');
jQuery('body').append(popup);
popup('js_login_again', 'o');
loading('h');
}
});
}
}
}
});
}
i did check if the sent token is correct or not and it is a correct token but the ajax post request still results to an error The action you have requested is not allowed.
The thing is i'm already giving the csrf token to ajax request and the token is being also added to the parameters sent to the url, so it's not the case of token , i'm just lost about why it does so.
also did check the $this->input->post('csrf_'); it's empty.
I am working on login form in Angular Js.The HTML and validation part is working fine.
The problem is when i send data using HTTP POST method to my servicecall PHP page and want to save it to DB.
I have tried all the way by setting this in JS
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
I have tried by setting enctype of form to
enctype="application/x-www-form-urlencoded"
as well.But none of them is working i am not able to get data via $_REQUEST, $_POST, $_GET any of these method.
I have also tried using PHP library function.
$postdata = file_get_contents("php://input");
But it gives some weird string which i can't handle because number of POST data could be hundreds.
So this there any other way to solve the problem.
Code for http request is
var req = {
method: 'POST',
url: 'servicecall.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
username: $scope.loginData.username,
password: $scope.loginData.password,
action : 'checkLogin'
} //First way of sending data
//Second way of sending data which is also not working
//data: "{username:"+$scope.loginData.username+",password:"+$scope.loginData.password+",action:checkLogin}"
}
$http(req).then(function(response){
console.log(response);
}, function(response){
alert("Error "+response);
});
At PHP page i do
print_r($_REQUEST);
print_r($_POST);
But it prints just blank array like array{}
Following the code that I am using for same purpose. Hope that may help you.
var app = angular.module('angularApp', []);
app.controller('loginCtrl', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: "post",
url: "login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function (data) {
if(data == "1"){
$scope.responseMessage = "Successfully Logged In";
}
else {
$scope.responseMessage = "Username or Password is incorrect";
}
});
}
});
I am using the Human API found here: https://docs.humanapi.co/docs/connect-backend
At one point in connecting to the API, I need to send data back to them as JSON. I get a JSON object called sessionTokenObject which contains this:
{
humanId: "1234567890",
clientId: "abcdefg",
sessionToken: "9876zyx",
}
To which I'm supposed to add a clientSecret. Essentially, I'm taking what's in the JSON object, converting it individual variables, passing them through to another page via URL parameters and then reconstructing everything so that I can add the clientSecret like so:
$pop_clientid = $_GET['clientid'];
$pop_humanid = $_GET['humanid'];
$pop_userid = $_GET['userid'];
$pop_sessiontoken = $_GET['clientid'];
$my_sessiontokenobject = '{
humanId: "'.$pop_humanid.'",
clientId: "'.$pop_clientid.'",
sessionToken: "'.$pop_sessiontoken.'",
clientSecret: "thesecretgoeshere"
}'; ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.ajax({
type: "POST",
url: 'https://user.humanapi.co/v1/connect/tokens',
data: '<?php echo $my_sessiontokenobject; ?>',
success: null,
dataType: 'application/json'
});
});
</script>
If I don't wrap the data value in the .ajax() call in apostrophes, I get a 422 error back from https://user.humanapi.com/v1/connect/tokens
If I do, I get an "Uncaught SyntaxError: Unexpected token ILLEGAL" error.
Can anyone see what's wrong with my code, or perhaps even tell me if trying to recreate a JSON object and then pass it back via .ajax() in the manner I am is just completely incorrect?
Try with this: (Returns a 404 Not found error, but it seems that it is in their side)
connectBtn.addEventListener('click', function(e) {
var opts = {
// grab this from the app settings page
clientId: clientId,
// can be email or any other internal id of the user in your system
clientUserId: clientUserId,
clientSecret: clientSecret,
finish: function(err, sessionTokenObject) {
console.log(sessionTokenObject);
// When user finishes health data connection to your app
// `finish` function will be called.
// `sessionTokenObject` object will have several fields in it.
// You need to pass this `sessionTokenObject` object to your server
// add `CLIENT_SECRET` to it and send `POST` request to the `https://user.humanapi.co/v1/connect/tokens` endpoint.
// In return you will get `accessToken` for that user that can be used to query Human API.
sessionTokenObject.clientSecret = clientSecret;
jQuery(document).ready(function($) {
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
contentType: "application/json",
data: sessionTokenObject,
});
});
// clientId=ceb8b5d029de3977e85faf264156a4e1aacb5377&humanId=f54fa4c56ca2538b480f90ed7b2c6d22
// $.post(url, sessionTokenObject, function(res){
// console.log(res);
// });
},
close: function() {
// do something here when user just closed popup
// `close` callback function is optional
}
}
HumanConnect.open(opts);
});
Human API Code for Testing, this code generates accessToken from Human API Developer Side but its not coming as in response while i execute this code
<script src='https://connect.humanapi.co/connect.js'></script>
<script>
var options = {
clientUserId: encodeURIComponent('email'), //Unique ID of user on your system (we send this back at the end)
clientId: '',
publicToken: '',
finish: function (err, sessionTokenObject) {
/* Called after user finishes connecting their health data */
//POST sessionTokenObject as-is to your server for step 2.
console.log(sessionTokenObject);
sessionTokenObject.clientSecret = 'Client Secret Key';
$.ajax({
type: 'POST',
url: 'https://user.humanapi.co/v1/connect/tokens',
method: 'POST',
data: sessionTokenObject
})
.done(function (data) {
console.log(data);
// show the response
if (data.success) {
alert(data.success);
} else {
alert(data.error);
}
})
.fail(function (data) {
console.log(data);
// just in case posting your form failed
alert("Posting failed.");
});
// Include code here to refresh the page.
},
close: function () {
/* (optional) Called when a user closes the popup
without connecting any data sources */
alert('user clicked on close Button');
},
error: function (err) {
/* (optional) Called if an error occurs when loading
the popup. */
}
}
function openHumanApiModel() {
HumanConnect.open(options);
}
</script>
I've been task with building an app to check on the status of servers through a phonegap app. The trouble is the client is not giving me access to the existing API or the server. The only information he has given me is: "You can send a POST request to the xmlUserApi.php named "request" by jQuery for example."
As I understand it, we are sending some XML in the format
<xmlApi>
<action> getServerList </action>
<auth></auth>
</xmlApi>
For example, from which a an XML list of all the servers is returned.
Whenever I try to POST this data to the PHP (xmlUserApi.php), nothing is returned. I feel it would be helpful to look through the PHP, but, the client won't let me.
Any help/ideas would be really appreciated
EDIT
The response I'm getting in the inspector is :
<form action=xmlUserApi.php method=post>
<textarea name=request cols=120 rows=30></textarea>
<input type=submit value=Request></form><br><br>86.135.213.213
What your client is suggesting is programmatically replicating the action of a user filling out the form at the address they provided.
To do that, try this:
var xmlData = '<xmlApi><action> getServerList </action><auth>xxxxxx</auth></xmlApi>';
var serverPath = 'http://some.com/path/';
var requestPath = 'xmlUserApi.php';
var request = $.ajax({
url: requestPath,
type: 'POST',
dataType: 'jsonp',
data: { request: xmlData }
});
request.done(function(data) {
/process data
});
request.fail(function(jqXHR, textStatus) {
alert(textStatus);
});
//Leaving original answer down here
"You can send a POST request to the xmlUserApi.php named "request" by jQuery for example."
Not sure what they mean by 'named "request"', but with jQuery you would do this:
var serverPath: 'http://their.server.tld/path/';
var authToken: 'sometoken';
$.post(serverPath + 'xmlUserApi.php', { action: 'getServerList', auth: authToken },
function(data) {
//whatever you want to do with the return goes here
}
);
There may also be an issue with the connection to the API, sometimes passing additional parameters helps with this, you could try:
var serverPath = 'http://their.server.tld/path/';
var requestPath = serverPath + 'xmlUserApi.php';
var authToken = 'sometoken';
$.ajax({
url: requestPath,
type: 'POST',
dataType: 'jsonp',
data: { action: 'getServerList', auth: authToken }
}).done(function(data) {
//processing here
}).fail(function(jqXHR, textStatus) {
alert(textStatus);
});