How to get HTTP reply in javascript? - javascript

Before I satart, allow me to explain a situation.
I have an html(say A.html) page where I get information from a form. I send the data to a php page (say B.php).
B.php processes the form and echo a string on screen.
A javascript page (Say C.js) needs to send an HTTP request to B.php and read what has been echoed.
Is such a thing even possible? I searched a lot and no explanation.

You should use AJAX.
It concludes 3 steps :
Create XMLHttpRequest Object
Set onreadystatechange function
Post data via JS
File A.html:
<html>
<input id="text" type="text" value="Hello"/>
<input type="button" value="getResponse" onclick="getResponse();"/>
<script>
var xmlhttp;
//Create XMLHttpRequest Object
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//this function will be triggered after "xmlhttp.send" finished
xmlhttp.onreadystatechange=function()
{
//readyState==4 means success, and status==200 means 'OK'
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
// send post data via your web element
function getResponse(){
var text = document.getElementById("text").value;
//send data and get response
xmlhttp.open("POST","b.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("text="+text);
}
</script>
</html>
And the file b.php:
<?php
$text = $_POST['text'];
echo "The length of your text $text is ".strlen($text);

Related

Php not receiving post from JavaScript

I have implemented the same setup elsewhere in my site and can't figure out why it's not working this time.
When a user clicks the accept button, it calls a JavaScript function acceptOrder(orderID) which passes the orderID onto a php page to update a record in the db.
orderID is assigned ok in the JavaScript but it doesn't reach the php. Var_dump on POST shows nothing, nor does $_POST('orderID'). I've even tried just sending an integer to the php in case there was a problem with the var but it made no difference.
Js
function acceptOrder(orderID) {
var orderID=orderID;
console.log("assigned: "+orderID);
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft. }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log (xmlhttp.responseText);
}
}
xmlhttp.open("POST","acceptorder.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-rule encoded");
xmlhttp.send(orderID);
console.log(orderID+" sent");
//location.reload();
//console.log("reload");
}
Php
<?php
require_once("config1412/class.shop.php");
session_start();
$shop = new SHOP();
echo var_dump($_POST);
//$orderID = $_POST['orderID'];
//echo "orderId var = ".$orderID."<br/>post ".$_POST['orderID'];
//$shop->acceptOrder($orderID);
?>
Needless to say I've searched about and don't see any solutions elsewhere.
Many thanks
As i can see, you didn't set variable name for orderID, change line of code:
xmlhttp.send(orderID);
to:
xmlhttp.send("orderID="+orderID);
If it's only SQL error of missing orderID, and all other passess okay, it's solution for you. As you said in comments "I just get a sql error because the variable orderID is empty".
You're missing only naming post send data, that's why it's empty.
Please replace this line
xmlhttp=new ActiveXObject("Microsoft. }
with following this line
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
You should write this in your js
function acceptOrder(orderID) {
var orderID=orderID;
console.log("assigned: "+orderID);
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log (xmlhttp.responseText);
}
}
xmlhttp.open("POST","acceptorder.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-rule encoded");
xmlhttp.send(orderID);
console.log(orderID+" sent");
//location.reload();
//console.log("reload");
}
I would recommend you to use jQuery for ajax calls. It's much easier to setup and straightforward. Especially, and specialy because it is very easy setup for a beginner. And for people who want to install ajax the easy way. I use it every single time I want to do ajax in my code. Here is a link:
http://api.jquery.com/jquery.ajax/
Just put the tag to include jQuery and then one javascript command to call the ajax.

Sending a javascript AJAX request triggers multiple page loads

I have searched but cannot find an answer to this issue. I am calling an asynchronous javascript file and the php page it calls makes a database entry twice.
window.onload = function(){
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
//document.write(xmlhttp.responseText);
return;
}
}
xmlhttp.open("POST","http://example.com/api/tracking/index.php?cid=" + get["clientId"] + "&refUrl=" + encodeURIComponent(siteURL) + "&auk=" + get["auth"],true);
xmlhttp.send();
}
The index php page does an insert and returns the new row id. The alert in the successful response corresponds to that id, but there is another entry made one millisecond before. I assume this is happening because the page is being accessed until it gets the ready state of 4. The question is how do I stop or bypass this?

Ajax code to access hidden or Non public html or php page

I am using following Ajax javascript code to get response from another php page.
I below code, main page is sending request to mypage.php which is located in same directory and getting response.
But mypage.php page is accessible separately through http:// ... /mypage.php
I want to send request the non public files and get response to prevent mypage.php access from http web access.
say i want to access it from /home/privatefolder/mypage.php from ajax
<script type="text/javascript">
function checkmypage(str)
{
//alert(str);
if (str=="")
{
document.getElementById("mypageResponse").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mypageResponse").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mypage.php?mypage="+str,true);
xmlhttp.send();
}
</script>
Note: I know javascript cannot access non http:// files. please provide alternate solution
Add request check at the top of your mypage.php and if true, include another php script from your privatefolder which does the jobs of mypage.php:
1- Check if request is an AJAX request or not in mypage.php :
if(empty($_SERVER['HTTP_X_REQUESTED_WITH'])
|| strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
// Not an AJAX request!
header('Locate to an error page or other page');
exit();
}
2- Include your script in else statement:
else {
// $_SERVER["DOCUMENT_ROOT"] is a good usage in here
include('Path to your script in privatefolder');
}

How to get the URL of a xmlhttp request (AJAX)

On w3schools.com(url) there is an example of how to do an AJAX call with plain Javascript. If you look at the example you will see the call is triggered by a button:
<button type="button" onclick="loadXMLDoc()">Change Content</button>
This is the function:
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
What I would like to do is get the URL of the outgoing AJAX call which is ajax_info.txt(url):
xmlhttp.open("GET","ajax_info.txt",true);
Im trying to put that URL in to an alert, so I tried calling the headers of the response using getAllResponseHeaders() hoping that it will give me the Host like so:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
alert(xmlhttp.getAllResponseHeaders());
It does give me all the headers but not the Host. So my next move was trying to set the Host myself using setRequestHeader() but then I realized the Header needs a Value which I had to send myself, so this will not work. What else can I try to get/fetch the outgoing AJAX URL in the alert?
Please note the code is just an example and I know that changing headers(in this case) is prohibited because of Access-Control-Allow-Origin.
I'm not sure how much access you have to the code but you can over-ride XMLHttpRequest.open and hook the url there.
XMLHttpRequest.prototype.open = (function(open) {
return function(method,url,async) {
console.log('the outgoing url is ',url);
open.apply(this,arguments);
};
})(XMLHttpRequest.prototype.open);
Here is a FIDDLE.

Show Save-As window from JSP

I need to write a String in a file on the client side, however as the Internet protocol does not allow that for Security concerns, this is the workaround I did: I have an AJAX request which invokes a JSP that queries a Database to get a String. I need to show the users a "Save-As" dialog and write this String to the local path they specify.
My JavaScript function:
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
alert("result obtained");
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
In the JSP, I have something like this:
response.setHeader("Content-Disposition", "attachment;filename=report.xml");
out.println(stringObtainedFromDatabase);
I do not see a Save As dialog while I get the alert saying result obtained. This is the first time I am doing this, could you please tell me if I am doing something wrong?
But, is there a way in JavaScript to show users a Save-As dialog and write the content of "div" tag in a file on the Client system?
Use a regular HTTP request, not an AJAX (XMLHttpRequest) one.
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
window.location = url;
}
This will send an HTTP GET, not a POST, though it looks like GET is the correct HTTP method to use here anyway, since you're retrieving data and not actually altering anything on the server.

Categories

Resources