Is it possible to handle requests on XWiki other way than just with submitting HTML forms ? I need to use XMLHttpRequest, but $request
simply doesn 't react to the request.
JavaScript code
function requestHandle(msg, subj) {
var recipientName = recipientsArr.pop()[0];
req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
console.log('req ok');
var mailStatusTmp = "<div class=\"mailStatus\">" + recipientName + " <span class=\"glyphicon glyphicon-ok\"/></div>";
$('#mailStatusWrapper').append(mailStatusTmp);
if (recipientsArr.length > 0) {
requestHandle(msg, subj); // call requestHandle() for next recipient
} else {
return;
}
} else {
console.log('req err');
var mailStatusTmp = "<div class=\"mailStatus\">" + recipientName + " <span class=\"glyphicon glyphicon-remove\"/></div>";
$('#mailStatusWrapper').append(mailStatusTmp);
if (recipientsArr.length > 0) {
requestHandle(msg, subj); // call requestHandle() for next recipient
} else {
return;
}
}
}
};
req.open("POST", "https://wiki.intra.tieto.com/xwiki/bin/view/Sandbox/TestPage1", true);
req.send("msg=" + msg + "&subj=" + subj + "&recipientName=" + recipientName);
}
I want to use XMLHttpRequest, because the page will send data to multiple receivers and I need to check the status every request.
If the page making the request is not on the same domain as the XWiki instance, then you might have to configure the target domain to accept cross-origin requests. That's not easy to do on XWiki's side, since there's no mechanism for responding to OPTION requests, but it's easy to configure if you're using a frontend, such as Apache HTTPD or nginx, or in the servlet container's configuration, for example in Tomcat or Jetty.
Related
I have a browser action I've implemented it as an AddOn.
I'm testing my construction of the AddOn within my domain
between two machines as server and a client.
I'm stuck at AJAX failing with status code 0.
I set up Apache to enable CORS to make sure that the code is behaving as expected.
I added this line to the apache config and enabled headers:
Header set Access-Control-Allow-Origin "*"
The javascript code: UPDATED
function sendData(data){
var requestdata = 'data1=one&data2=two&data3=three';
var xhr = new XMLHttpRequest();
xhr.open("POST","http://server/test/test.php");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onloadstart = function(){
console.log("Onload status: " + xhr.status);
}
xhr.onerror = function(ev) {
console.log("OnError Status: " + xhr.status + ", Loaded: " + ev.loaded + ", Total: " + ev.total);
}
xhr.onreadystatechange = function() {
console.log(xhr.status);
if (xhr.status !== 200){
console.log("Failure :( + Status: " + xhr.status);
//console.log(requestdata);
console.log("Ready State: " + xhr.readyState + ", Status: " + xhr.status +", Response Text: " + xhr.responseText);
} else {
alert("Success!");
}
}
xhr.send(requestdata);
}
test.php
<?php
require '../lib/Database.php';
error_reporting(E_ALL);
$db = new Database('test');
var_dump($db);
json_encode($_POST);
?>
Have I done this AJAX implementation correctly?
If I have, and I have made adjustments for CORS, why is it failing with status code 0?
UPDATE
This is an AddOn I am testing in Firefox.
From the "matches" parameter in manifest.json, navigating to the page in question retrieves data from the page using Vanilla JS on the DOM.
The collected data is held in an object.
The data object is delivered
This is a picture of what's returned in the browser:
UPDATE2
I replaced the POST url with http://httpbin.org/post to see if the data is going anywhere. Nope.
I would like to read the substatus code of the exception like 500.1 on the client side. How to achieve this?
here is my code on the server side:
if(string.IsNullOrEmpty(userEmail)) {
Response.StatusCode = 500;
Response.SubStatusCode = 1;
Response.StatusDescription = "Email fehlt";
return;
}
Client side:
if (xhr.status == 500 && thrownError.indexOf("Email") > -1) {
alert('Email is missing...');
}
else {
alert('Error...');
}
On client side you can use the getAllResponseHeaders() method of XMLHttpRequest.
If a correct http header is really sent, it will read it.
Example:
var request = new XMLHttpRequest();
request.open("GET", "ajax.php", true);
request.send();
request.onreadystatechange = function() {
if(this.readyState == this.HEADERS_RECEIVED) {
console.log(this.getAllResponseHeaders());
}
}
Output is separated by "\r\n".
If somehow the substatus cannot go through, maybe you can use another http header field for your goal, even if it is not according to the standards...
I made a simple chat. It's working properly, but not behaving as expected. When a user submits a message, the user's name, time and message are supposed to display.
It so happens that the username and response appear first and the time seems to be inserting itself after a slight delay (that's the lag). I can't figure out why, especially since the response is (or at least seems to be) sent as a whole and nothing is being inserting once the response is sent from the server...
Here's the link to the chat. You can input dummy username and dummy messages.
And here are the important pieces of code:
PHP
while ($row = $result->fetch_assoc()) {
$time = date('g:ia', $row['time']);
echo "<p class=\"message\"><i>{$row['username']}</i> ($time): {$row['content']}</p>";
}
JavaScript
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
document.getElementById('messagesArea').innerHTML = ajax.responseText;
}
};
Your culprit is this section of the script:
var content = document.getElementById('messageBox').value;
if ( content === '') {
return;
} else {
var ajax = new XMLHttpRequest();
var username = document.getElementById('signedin').innerHTML;
document.getElementById('messageBox').value = '';
ajax.open('POST', 'postmessage.php', true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
// if there are errors echoed from the PHP file
if (ajax.responseText != "") {
document.getElementById('mysqliError').innerHTML = ajax.responseText;
return;
}
document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
}
};
ajax.send('username=' + username + '&content=' + content);
}
Notice this line: document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
You are inserting the message, without the time, into #messagesArea. Then, in getRecentMessages later, it is set to fetch the entire chat log from displaymessages.php and overwrite #messagesArea with the content of the output, which does have the time.
I'm using some JavaScript to send an Ajax request to an Arduino webserver and change the HTML on a webpage.
In Safari this has been working great, but when I try to load it in Firefox and Google Chrome the document elements never update. In the debugger consoles I can see the requests and responses coming back so I'm guessing that there is an issue with parsing the response to an array?
Here is the code:
function GetSwitchState()
{
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function()
{
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseText != null) {
var response = this.responseText;
var comma = ",";
var inputArray = response.split(comma);
var green = inputArray[0];
var red = inputArray[1];
var fault = inputArray[2];
var counter = inputArray[3];
document.getElementById('green').innerHTML = green;
document.getElementById("red").innerHTML = red;
document.getElementById("status").innerHTML = fault;
document.getElementById("cars").innerHTML = counter;
}
}
}
}
request.open("GET", "url" + nocache, true);
request.send(null);
setTimeout('GetSwitchState()', 1000);
}
The response from the Arduino webserver is four comma-separated values.
Okay it looks like the issue was actually getting past the
{
if (this.readyState == 4) {
if (this.status == 200) {
arguments. When I changed it to:
{
if(response.readState == 4) {
I was able to move past that statement in firefox. To get the status to 200 instead of 0 I needed to modify the response header on the arduino side to include:
Access-Control-Allow-Origin: *
To allow Cross Origin Domain Requests in FireFox. Once I made these changes the code works great, I guess I was barking up the wrong tree with my array assumption.
Thanks for the help!
What I did today was pretty much the same!
When I ran an Ajax request to a PHP file and wanted to return an array I needed to specify the return-datatype as "json". In my PHP file I then returned my values like this:
return json_encode(array(
'success' => false,
'error' => $_POST['password_hashed']
));
I was acctually using jQuery to run the request. That looks like this:
$.ajax({
type: 'POST',
url: 'script.php',
data: 'password_hashed=' + hex_sha512(str_password) + '&email=' + str_email, //Clientside password hashing
cache: false,
dataType: 'json',
success: function(value){
//Ajax successfully ran
alert(value.success + '_' + value.error); //=false_[hash]
},
error: function(){
//Ajax error occured -> Display error message in specified element
alert('error with request');
}
});
I just started with Ajax two days ago, and this may not help a lot, but it is worth trying.
I have to send a name and a link from client side to the server. I thought of using AJAX called by Javascript to do this.
This is what I mean. I wished to make an ajax request to a file called abc.php with parameters :-
1. http://thumbs2.ebaystatic.com/m/m7dFgOtLUUUSpktHRspjhXw/140.jpg
2. Apple iPod touch, 3rd generation, 32GB
To begin with, I encoded the URL and tried to send it. But the server says status Forbidden
Any solution to this ?
UPDATE ::
It end up calling to
http://abc.com/addToWishlist.php?rand=506075547542422&image=http://thumbs1.ebaystatic.com/m/mO64jQrMqam2jde9aKiXC9A/140.jpg&prod=Flat%20USB%20Data%20Sync%20Charging%20Charger%20Cable%20Apple%20iPhone%204G%204S%20iPod%20Touch%20Nano
Javascript Code ::
function addToWishlist(num) {
var myurl = "addToWishlist.php";
var myurl1 = myurl;
myRand = parseInt(Math.random()*999999999999999);
var rand = "?rand="+myRand ;
var modurl = myurl1+ rand + "&image=" + encodeURI(storeArray[num][1]) + "&prod=" + encodeURI(storeArray[num][0]);
httpq2.open("GET", modurl, true);
httpq2.onreadystatechange = useHttpResponseq2;
httpq2.send(null);
}
function useHttpResponseq2() {
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
}
Server Code
<?php
include('/home/ankit/public_html/connect_db.php');
$image = $_GET['image'];
$prod = $_GET['prod'];
$id = $_GET['id'];
echo $prod;
echo $image;
?>
As I mentioned, its pretty basics
More Updates :
On trying to send a POST request via AJAX to the server, it says :-
Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"
2 things.
Use encodeURIComponent() instead of encodeURI().
Here is a detailed discussion on this: When are you supposed to use escape instead of encodeURI / encodeURIComponent?
If you are new to JavaScript, use some lib to help you do the AJAX work. Like mootools, jQuery, etc.
Using a POST request solved my issue :)
function addToWishlist(num) {
var url = "trial.php";
var parameters = "prod=" + encodeURIComponent(storeArray[num][0]) + "&image=" + encodeURIComponent(storeArray[num][1]);
httpq2.open("POST", url, true);
httpq2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpq2.onreadystatechange = function(){
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
};
httpq2.send(parameters);
}