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);
});
Related
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.
I have an Ajax request that will pass some data to an action of a controller of cakephp 3, but the controller does not receive the data, $ _POST equal to empty.
var url = "http://localhost/update/"+ id;
var telefone = 9999999;
var cpf = 999999999;
$.ajax({
url: url,
type: "post",
data: {cpf: cpf, celular: telefone}
}).done(function( response ) {
}).fail(function( jqXHR, textStatus ) {
});
method receive data:
public function update($id = null) {
var_dump($_POST);die();
}
my var_dump show empty, but i send data in Ajax.
allow access in method! someone have this problem?
don't you need to specify the port in the url? for example http://localhost:8080/update/
type should be POST like this
$.ajax({
url: url,
type: "POST",
// blah blah
Use fireBug to see if the request is sending anything.With this tool you can track your request. The most likely you're not sending the data correctly.
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 am extremely bad at AJAX (actually, I just started to learn it).
So, I write whois service on PHP and I want to make it to output the result via AJAX-request.
All I have at the moment is:
my PHP code:
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:application/json");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo json_encode($res);
my JS code:
$('#submit').on('click', function() {
e.preventDefault();
var domain = $('#value').val();
});
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
dataType: "json",
success: function(json) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(json.html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
As HTML I have an input: <input type="text" id="value"> and the submit button.
I searched for the script examples and tried to make something similar, but it does not work at all...
P.S. Guess you won't hit this question a negative rating :)
P.P.S: As requested, this is my response from PHP:
{"domain":"exp.cm","whois":"[Domain]\nDomain: exp.cm\nStatus: active\nChanged: 2014-02-25T12:22:00.957819+02:00\n\n[Holder]\nType: Legal person\nName: Name, Surname\nEmail: email#example.com\nPhone: Phone here\nAddress: Address goes here\nSome other info\n\nUpdated: 2014-03-18T18:12:35.717462+00:00\n"}
In this case you don't need the JSON datatype, just return html.
Additionally, you'll want the ajax request to be inside the click event. In your click event, you also forgot to pass the e parameter.
$domain = $_POST['domain'];
$whois = new Whois();
header("content-type:text/html");
$res = $whois->getWhois($domain); // Calls the Whois-query function;
echo $res;
js:
$('#submit').on('click', function(e) {
e.preventDefault();
var domain = $('#value').val();
$.ajax({
url: 'ajax/whois.php',
type: "post",
data: {'domain': domain, 'action': 'whois'},
//dataType: "json",
success: function(html) {
$('#whoisResult').html('<h2>Whois Query result for ' + domain + '</h2>');
$('#whoisContent').html(html);
},
error: function(xhr, status) {
$('#whoisResult').html('<h2>Sorry, an error occured. Try again later, please!</h2>')
}
});
});
Everything was going great in my previous help request thread. I was on the correct track to get around a CSRF, but needed to be pointed in the right direction. I received great help and even an alternate script used to log into Google's Android Market. Both my script and the one I altered to match my form is get hung up at the same point. Apparently cURL cannot process JS, is there any way to work around the form being submitted with submitForm() without changing the form?
Here is the code for the SubmitForm function
function submitForm(formObj, formMode) {
if (!formObj)
return false;
if (formObj.tagName != "FORM") {
if (!formObj.form)
return false;
formObj = formObj.form;
}
if (formObj.mode)
formObj.mode.value = formMode;
formObj.submit();
}
Here is the code for the submit button -
<a class="VertMenuItems" href="javascript: document.authform.submit();">Submit</a>
Here is a link to my last question in case more background information is needed.
PHP service...
<?php
// PHP service file
// Get all data coming in via GET or POST
$vars = $_GET + $_POST;
// Do something with the data coming in
?>
Javascript elsewhere...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function sendData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'POST',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
function getData(data)
{
var response;
$.ajax({
url: 'phpservice.php',
data: data,
type: 'GET',
dataType: 'json',
async: false,
success: function(response_from_service)
{
response = response_from_service;
},
error: function()
{
}
});
return response;
};
});
</script>