How to HTTP Request a URL in JavaScript? [duplicate] - javascript

This question already has answers here:
HTTP GET request in JavaScript?
(31 answers)
Closed 7 years ago.
In the below code I need to execute the newUrl:
<SCRIPT type="text/javascript">
function callMyAction(){
var newUrl = '/makeObtained.action';
//here I need to execute the newUrl i.e. call it remote
//it will return nothing. it just starts server process
}
</SCRIPT>
<a onclick="callMyAction()" href='...'> ...</a>
How to make it?

With JQuery, you can do this:
$.get('http://someurl.com',function(data,status) {
...parse the data...
},'html');
For more info, check this question: Call a url from javascript please.
Without Jquery, you can do this:
var xhr = new XMLHttpRequest();
xhr.open('GET', encodeURI('myservice/username?id=some-unique-id'));
xhr.onload = function() {
if (xhr.status === 200) {
alert('User\'s name is ' + xhr.responseText);
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
as described in this blog, kindly suggested by Yuriy Tumakha.

As previous answer suggest JQuery code. Here is the code with pure JavaScript if you are not familiar with JQuery. But it is recommended to use some framework like JQuery for easy and better code management.
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");
}
//Replace ajax_info.txt with your URL.
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

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.

How to hit url in javascript

I want to just hit the url in javascript which will run in background not on frontend.
I had tried this code
var url = "http://yourpage.com";
req = new ActiveXObject("Microsoft.XMLHTTP");
req.open("GET", true);
req.onreadystatechange = callback;
req.send(null);
but it not work for me.
could any one please suggest me how to hit url in javascript.
you should use cross browser JavaScript AJAX code, or better to use jQuery ajax see below sample code
var url = "http://yourpage.com";
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 = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
I suggest you use either jQuery or AngularJs for sending AJAX requests rather than creating new ActiveXObject objects.
Girish gave you answer using pure javascript. I will give you an example of jQuery usage. Please see code below:
$.get('http://yourpage.com', function(){ /*callback*/ })

Javascript - Reading a text file line by line. Does it matter what browser is being used?

I have just started getting into Javascript and mobile web programming. One thing that I am uncertain of is how I can write proper code that runs on any browser without having the end user have any extra requirements on their end (what browser to use).
I am coding this in google chrome and more recently in c9.io.
I thought this would work:
function readTextFile(file)
{
var client = new XMLHttpRequest();
client.open('GET', file);
client.send();
client.onreadystatechange = function() {
alert(client.responseText);
}
}
But i get the error that XMLHTTpRequest is not defined. I have been trying to figure out why this is and I keep coming to different browsers not supporting this. I had figured simple file io would not be that difficult but its causing me more trouble than I had hoped.
What is the best way to input a text file? It is 1 text file that is not having anything being written to it. Just read only. The end user isn't choosing this text file it should be the only option.
The order in your code is wrong, send method should be the last one; otherwise, your code is fine and it should work fine in all modern browsers. The mentioned order issue, or maybe was something else (before) causing that error. The snippet below will also split received text in an array of text lines
var xhr, i, text, lines;
if(window.XMLHttpRequest){
// IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
}else{
// IE5, IE6 - next line supports these dinosaurs
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
text = xhr.responseText;
lines = text.split("\n");
for(i = 0; i < lines.length; i++){
console.log(lines[i]);
}
}
}
xhr.open('GET', 'http://domain/file.txt', true);
xhr.send();
XMLHTTpRequest is not supported by the older browsers. Try doing this to support the older browsers as well:
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");
}

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.

Ajax and VbScript: fetching Post variable in test.asp

current i am trying to use ajax for my site ....... because of size of data is not limited i need to use post method for send data to database but the problem is i am unable to fetch the Post variables in the test.asp
here is the script i am using
function SaveData(content )
{
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)
{
msg=xmlhttp.responseText;
alert(msg);
}
}
var para = encodeURIComponent("content="+content)
xmlhttp.open("POST","test.asp",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(para)
}
and here is test.asp code
t = Request.form("content")
Response.write(t)
please help me solving this problem of fetching the Post method variable in test.asp
if possible any one can share code of jquery ajax with post method in asp classic too that would also be helpful
You need to change this:
var para = encodeURIComponent("content="+content)
into this:
var para = "content=" + encodeURIComponent(content);
The way that it was, you were submitting something like this to the server:
content%3Dtest%20data%20123
With the adjusted line of code, you're submitting something like this, which is as it should be:
content=test%20data%20123
Have you considered using a JavaScript library such as jQuery? A library will abstract away all this unpleasantness:
$.post("test.asp", { 'content': content }, function(data) {
alert("Returned data: " + data);
});

Categories

Resources