Ajax data parameter to php file on external domain - javascript

In this file called like this :
/fichier_clients/fiche_client.html?id=4870
It used "id" value and make a request to external file (php).
Data doesn't pass to php file (external domain).
Distant php file execute fine with no error and resend extract.
Data from database with test id,
but not with value received via ajax -> params: {"term": id},
<link href="jquery-mobile/jquery.mobile.theme-1.0.min.css" rel="stylesheet" type="text/css"/>
<link href="jquery-mobile/jquery.mobile.structure-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="jquery-mobile/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.min.js" type="text/javascript"></script>
<script type='text/javascript' language='javascript'>
function fiche0()
{
var id = location.search;
var id = id.split('=');
var id = id[1];
alert (id);
var encoded = encodeURIComponent('http://www.mydomain.fr/connexion.php');
$.ajax({
url: 'http://whateverorigin.org/get?url='+encoded,
type:'POST',
contentType:"application/json",
dataType: 'jsonp',
crossDomain:true,
params: {"term": id},
timeout: 4000
}).done(function(reponse){
a=reponse.contents.split(';');
document.getElementById("client").innerHTML = a[0] ;
document.getElementById("adresse1").innerHTML = a[1] ;
})
}
window.onload = fiche;
</script>

You cannot POST to an external domain, only GET requests pass data to external.
I would suggest using $_REQUEST in your php script as opposed to $_POST, this way you can see all data coming in regardless of how it was sent.

in this case I can send data, but no return
<script type="text/javascript">
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
// sends data to a php file, via GET, and displays the received answer
function ajaxrequest(pid) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create the URL with data that will be sent to the server (a pair index=value)
var url = 'http://www.mydomain.fr/connexion.php?term=3334';
request.open("GET", url, true); // define the request
request.send(null); // sends data
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
alert ("toto");
document.getElementById("context").innerHTML = request.responseText;
}
}
}
window.onload = ajaxrequest;
</script>
<div id="context"></div>

Related

Cant retrieve an XML list from a web service

I have a server running OTRS 5 and I would like to retrieve a list in XML format. I'm running a JavaScript code that should display the list, but instead I get an error.
My local server is https://labcentos3/otrs/mds.pl?Action=ServiceList.
I think its a Perl script that runs on the server side and then displays a list in XML format.
This is what I get if I browse the local link: it gives me the list I want
I wrote HTML and JavaScript to try to do the same for working with the retrieved data later, but I can't get past an error.
HTML
<html>
<head>
<title>XML read</title>
<script src="reader.js" type="text/javascript"></script>
</head>
<body>
<h1>XML File</h1><br/>
</body>
</html>
reader.js
var user = "bla bla bla";
var pass = "bla bla bla"
var getXMLFile = function(path, callback) {
var request = new XMLHttpRequest();
request.open("POST", path);
request.setRequestHeader("Content-Type", "text/plain");
//request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader('Authorization', 'Basic ' + btoa(user + ":" + pass));
request.onreadystatechange = function() {
if(request.readyState === 4 && request.status === 200) {
callback(request.responseXML);
}
};
request.send();
};
getXMLFile("https://labcentos3/otrs/mds.pl?Action=ServiceList", function(xml) {
console.log(xml);
});
The error I get in the Chrome console is this:
XMLHttpRequest cannot load https://labcentos3/otrs/mds.pl?Action=ServiceList. The request was redirected to 'https://labcentos3/otrs/index.pl', which is disallowed for cross-origin requests that require preflight.

http request with cookie in javascript

I'm trying to make a request with javascript but the cookie part seem to be not working. Code I'm using is below.
<script type = "text/javascript">
<!--
function SendReq(){
var request = new XMLHttpRequest();
var path="http://192.168.186.131/hello.html";
request.onreadystatechange=state_change;
request.open("GET", path, true);
request.withCredentials = true;
document.cookie="sessionid=d8e8fca2dc0f896fd7cb4cb0031ba249";
request.setRequestHeader("User-Agent", "Mozilla/5.0");
request.setRequestHeader("Cookie",document.cookie);
request.setRequestHeader("Accept-encoding",'deflate');
request.send(null);
function state_change(){
if (request.readyState==4){
alert('ready');
if (request.status==200){
alert('ok');
}
else{
alert("Problem retrieving XML data");
}
}
}
}
</script>
What could be the issue here? Are there better ways to get this done?

How to call a REST web service API from JavaScript?

I have an HTML page with a button on it. When I click on that button, I need to call a REST Web Service API. I tried searching online everywhere. No clue whatsoever. Can someone give me a lead/Headstart on this? Very much appreciated.
I'm surprised nobody has mentioned the new Fetch API, supported by all browsers except IE11 at the time of writing. It simplifies the XMLHttpRequest syntax you see in many of the other examples.
The API includes a lot more, but start with the fetch() method. It takes two arguments:
A URL or an object representing the request.
Optional init object containing the method, headers, body etc.
Simple GET:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json');
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Recreating the previous top answer, a POST:
const userAction = async () => {
const response = await fetch('http://example.com/movies.json', {
method: 'POST',
body: myBody, // string or object
headers: {
'Content-Type': 'application/json'
}
});
const myJson = await response.json(); //extract JSON from the http response
// do something with myJson
}
Your Javascript:
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "Your Rest URL Here", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
}
Your Button action::
<button type="submit" onclick="UserAction()">Search</button>
For more info go through the following link (Updated 2017/01/11)
Here is another Javascript REST API Call with authentication using json:
<script type="text/javascript" language="javascript">
function send()
{
var urlvariable;
urlvariable = "text";
var ItemJSON;
ItemJSON = '[ { "Id": 1, "ProductID": "1", "Quantity": 1, }, { "Id": 1, "ProductID": "2", "Quantity": 2, }]';
URL = "https://testrestapi.com/additems?var=" + urlvariable; //Your URL
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.setRequestHeader('Authorization', 'Basic ' + window.btoa('apiusername:apiuserpassword')); //in prod, you should encrypt user name and password and provide encrypted keys here instead
xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.send(ItemJSON);
alert(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
}
function callbackFunction(xmlhttp)
{
//alert(xmlhttp.responseXML);
}
</script>
<html>
<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>
</div></body>
</html>
$("button").on("click",function(){
//console.log("hii");
$.ajax({
headers:{
"key":"your key",
"Accept":"application/json",//depends on your api
"Content-type":"application/x-www-form-urlencoded"//depends on your api
}, url:"url you need",
success:function(response){
var r=JSON.parse(response);
$("#main").html(r.base);
}
});
});
I think add if (this.readyState == 4 && this.status == 200) to wait is better:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
var response = xhttp.responseText;
console.log("ok"+response);
}
};
xhttp.open("GET", "your url", true);
xhttp.send();
If that helps anyone, if you are ok with an external library then I can vouch for Axios, which has a pretty clean API and rich documentation to deal with REST calls, here's an example below:-
const axios = require('axios');
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
});
Before we try to put anything on the front end of the website, let's open a connection the API. We'll do so using XMLHttpRequest objects, which is a way to open files and make an HTTP request.
We'll create a request variable and assign a new XMLHttpRequest object to it. Then we'll open a new connection with the open() method - in the arguments we'll specify the type of request as GET as well as the URL of the API endpoint. The request completes and we can access the data inside the onload function. When we're done, we'll send the request.
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function () {
// Begin accessing JSON data here
}
}
// Send request
request.send()
By far, the easiest for me is Axios. You can download the node module or use the CDN for your simpler projects.
CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Code example for GET/POST:
let postData ={key: "some value"}
axios.get(url).then(response =>{
//Do stuff with the response.
})
axios.post(url, postData).then(response=>{
//Do stuff with the response.
});
Without a doubt, the simplest method uses an invisible FORM element in HTML specifying the desired REST method. Then the arguments can be inserted into input type=hidden value fields using JavaScript and the form can be submitted from the button click event listener or onclick event using one line of JavaScript. Here is an example that assumes the REST API is in file REST.php:
<body>
<h2>REST-test</h2>
<input type=button onclick="document.getElementById('a').submit();"
value="Do It">
<form id=a action="REST.php" method=post>
<input type=hidden name="arg" value="val">
</form>
</body>
Note that this example will replace the page with the output from page REST.php.
I'm not sure how to modify this if you wish the API to be called with no visible effect on the current page. But it's certainly simple.
Usual way is to go with PHP and ajax. But for your requirement, below will work fine.
<body>
https://www.google.com/controller/Add/2/2<br>
https://www.google.com/controller/Sub/5/2<br>
https://www.google.com/controller/Multi/3/2<br><br>
<input type="text" id="url" placeholder="RESTful URL" />
<input type="button" id="sub" value="Answer" />
<p>
<div id="display"></div>
</body>
<script type="text/javascript">
document.getElementById('sub').onclick = function(){
var url = document.getElementById('url').value;
var controller = null;
var method = null;
var parm = [];
//validating URLs
function URLValidation(url){
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var x = url.split('/');
controller = x[3];
method = x[4];
parm[0] = x[5];
parm[1] = x[6];
}
}
//Calculations
function Add(a,b){
return Number(a)+ Number(b);
}
function Sub(a,b){
return Number(a)/Number(b);
}
function Multi(a,b){
return Number(a)*Number(b);
}
//JSON Response
function ResponseRequest(status,res){
var res = {status: status, response: res};
document.getElementById('display').innerHTML = JSON.stringify(res);
}
//Process
function ProcessRequest(){
if(method=="Add"){
ResponseRequest("200",Add(parm[0],parm[1]));
}else if(method=="Sub"){
ResponseRequest("200",Sub(parm[0],parm[1]));
}else if(method=="Multi"){
ResponseRequest("200",Multi(parm[0],parm[1]));
}else {
ResponseRequest("404","Not Found");
}
}
URLValidation(url);
ProcessRequest();
};
</script>

my php can't receive the 'post' variabe I am sending via ajax

Here is my javascript:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
hanapin.send(reqdata);
hanapin.onreadystatechange = function() {
if (hanapin.readyState == 4 && hanapin.Status == 200) {
document.getElementById('province').innerHTML=hanapin.ResponseText
}
}
window.alert(targeturl);
window.alert(reqdata);
}
I know the function is receiving the data because I used the alert.
but on php:
<?php
$findwat = $_POST['condo'];
echo $findwat;
?>
even when I open the php file using a separate link it won't echo the variable
An example using jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
function fetchprov(proptype) {
$.post("testajax.php", {condo:proptype}, function(data){
// data is the result received from php
alert(data);
});
}
A mandatory header field for http post request is Content-length. change your code to:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hanapin.setRequestHeader("Content-length", reqdata.length);
hanapin.setRequestHeader("Connection", "close");
hanapin.send(reqdata);
hanapin.onreadystatechange=function() {if (hanapin.readyState == 4 && hanapin.Status == 200) {document.getElementById('province').innerHTML=hanapin.ResponseText} }
window.alert(targeturl);
window.alert(reqdata);
}
also a better solution is to use jquery to handle ajax

Request to external domain

I want to make a request to external domain,
parameter is sent correctely to php file (on external server)
but "request.responseText" allways empty,
thanks in advance (an example will be very apreciate)
<script type="text/javascript">
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest() {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
var url = 'http://www.mydomain.fr/connexion.php?term=3334';
request.open("GET", url, true); // define the request
request.send(null); // sends data
request.onreadystatechange = function() {
if (request.readyState == 4) {
//response allways empty
document.getElementById("context").innerHTML = request.responseText;
}
}
}
window.onload = ajaxrequest();
</script>
<div id="context"></div>
by default you cannot just load data from another server, however if the server is configured to allow cross origin requests then you'll be good to go.
Take a read through the info here
http://www.html5rocks.com/en/tutorials/cors/

Categories