I have a 3rd party that returns a string of html. Lets call it 'b.com'.
I want to manipulate this string client side with java-script/jquery.
I want to do this on 'A.com'.
I am familiar with JSON being returned and being used server side, but never client side and never with html.
Could someone please assist?
I've tried this with jquery:
<body>
<div id="temp"></div>
<script type="text/javascript">
$('#temp').load("http://www.b.com/datapage");
</script>`enter code here`
</body>
And this with pure JS:
<script type="text/javascript">
function httpGet(theUrl)
{
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
return xmlhttp.responseText;
}
}
xmlhttp.open("GET", theUrl, false );
xmlhttp.send();
}
document.write(httpGet("http://stackoverflow.com/"));
</script>
Yes b.com does allow cross-origin requests
Use $.ajax() , perform processing of responseText at .then()
$.ajax({url:"b.com", type:"GET", dataType:"html", crossDomain:true})
.then(function(data, textStatus, jqxhr) {
// do stuff with data here
}, function err(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
})
Related
I'm using jQuery to read an XML file. Sometimes the XML is empty, and I expect the error function (no_info) is executed because the file is not formatted according to the dataType.
In IE 10 the Error function is executed. But in Firefox (40.0.2) the success function (parse) is executed. Why both browsers behave differently and which one is correct?
$.ajax({
url: '/~play/shout.xml',
dataType: "xml",
success: parse,
error: no_info
});
Looks like there's a bug in IE
how about you handle it yourself?
function parseXml(xml) {
if ($.browser.msie) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "XML_file.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
xml = xmlDoc;
}
return xml;
}
previous answer
which JQuery version do you use? I use the most actual and with my ajax function I couldn't encounter any issues. That's my code
function sync(arg, callback){ //ajax result
$('.loader').show();
$.ajax({
method: 'GET',
url: 'liveSearch.php',
data: arg, // send argument and update
success: function(data, status, xhr){
$('.loader').hide();
callback(data);
},
error: function(xhr, ajaxOptions, thrownError){
console.log(thrownError);
}
});
}
function onCallback(data) {
result = data;
}
dataType parameter merely indicates what "Content-Type" header you are expecting.
As long as the file exists and served with a valid Content-Type Success function should be triggered.
instead of just /~ try passing the whole URL from which you want to retrieve the XML file.
I understand I can't pass AJAX Vars directly to PHP, being a client versus server side script. But that being said, here's my code:
setInterval(function()
{
//do something after you receive the result
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("message_area").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","messages.txt",true);
xmlhttp.send();
}
I know I can indirectly process AJAX variables by POSTing them to a PHP page using AJAX, like so:
$.ajax (
{
type: "POST",
url: "decode.php",
});
I just need to know how to pass the contents of the "messages.txt" file used in the xmthttp.open call to a PHP file for further processing.
How can I do this?
If you are using pure javascript:
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
or if you're using jquery, simply:
$.ajax (
{
type: "POST",
url: "decode.php",
params: {param1: "val1", param2: "val2"}
});
Hope this helps :
$.get( "messages.txt", function( data ) { //Fetching contents of messages.txt file.
$.ajax ({
type: "POST",
url: "decode.php",
data: data, //passing contents of messages.txt file to decode.php
success: function(result){
alert(result);//Getting result from decode.php
}
});
});
cheers
Are you using jquery? You first code block is regular js, the second is jQuery's ajax short hand.
That said, if you want to POST data with ajax using jQuery, you would do something like the following.
var PostData = "something";
$.ajax({
type: "POST",
url: "someurl",
data: PostData
}).done(function(returnData) {
//process data returned from server, if there is any
});
I am using Ajax async to pull one report from db.. I am able to do when i used this code
function showCustomer(str)
{
alert("Report is loading..!Please wait");
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Pull.action?rel="+str,true);
xmlhttp.send();
}
But when i try to use jquery ajax, i am not able to get the output,
$(document).ready(function() {
$("#submit").click(function(event){
$("#submit").hide();
$('#txtHint').text("Loading..! Please Wait. !!");
var name = $("#first").name();
alert(name);
$.ajax({
type: "GET",
url:"Pull.action?rel="+name,
context: document.body,
success: function(data){
alert(name);
$('#txtHint').html(data);
//$('#txtHint').load("Pull.action?rel="+name);
$("#submit").show();
}
});
});
});
Am i doing any mistake here, it is not calling that "pull.action" Struts2 action also.
JSP which is using is
<form action="">
<table><tr><td>
<s:select id="first" label="Please select the Go Live Date : " name="applicationPhases" value="%{applicationPhases}" headerValue="--Select--"
list="{'--Select--','Q1','Q2','Q3','Q4','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'}" />
</td><td>
<s:submit id="submit" name="submit" value="Submit" />
</td></tr> </table>
</form>
<br /><br />
<br />
<div id="txtHint" />
Please help me out to make ajax request using jquery to call one action class from a jsp and display the output in same jsp.. (output will be display-tag table and variable has to be passed through url to action class)
This Jquery ajax helped me to attain my requirement,
$(document).ready(function() {
$("#report").click(function(event){
$("#report").hide();
$('#txtHint').text("Loading..! Please Wait. !!");
var name = $("#first").val();
alert(name);
$.ajax({
type: "GET",
url:"Pull.action",
data:{"name":name},
context: document.body,
success: function(data){
$('#txtHint').html(data);
$("#report").show();
}
error:function(){
$('#txtHint').html(data);
alert("Error in pulling details");
}
});
});
});
This probably has some really obvious answer that I'm missing, but I just can't seem to figure it out. All the search functions from PHP and queries work. The only thing that doesn't work is that the data isn't being displayed properly in the text area translated. Below is the code.
document.getElementById("translated").innerHTML = xmlhttp.open("GET","ajax-result.php?result="+num,true);
After the innerHTML portion, whatever I add (from text to html) goes into the right place but right now the above code says it is undefined.
xmlhttp.open does not return anything - that's why you get "undefined". Read http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp , paying particular attention to
xmlhttp.onreadystatechange part.
Far more convenient way to do this is to use jquery ajax method: http://api.jquery.com/jQuery.ajax/
That's not how ajax works. You should have a callback function to be called when server responses
Something like
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
// setup callback function
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
if(xmlhttp.responseText == 1){
document.getElementById("translated").innerHTML = xmlhttp.responseText;
}
}
}
xmlhttp.open("GET",'your request to sever',true);
If you really want to save yourself some head ache, I'd familiarize yourself with jQuery.
Here is a full working example of what it appears it is you are attempting to accomplish.
The implementation of the input and button was simply to simulate the method in which a value is being specified and the function is being called.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
function runAjax(num) {
$.ajax({
'url': 'ajax-result.php',
'type': 'GET', // Can also be 'POST'
'data': {
'result': num
},
'success': function(result) {
$('#translated').html(result);
alert('success!');
},
'error': function(xhr, status, exception) {
alert('failed with status code: ' + status);
}
});
}
$(document).ready(function() {
$('button').click(function() {
var $input = $('input');
var num = $input.val();
runAjax(num);
});
});
</script>
<input type="text" name="num" value="123" />
<button type="button">Click Me!</button>
</body>
</html>
How to know when all ajax calls are complete?,now I just use a delay timeout to wait the request complete,these is a better way?i want make sure ajax requests are completed...
The XMLHttpRequest object has readyState property and onreadystatechange that you can manipulate like that:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) { // xmlhttp.status==200 == successful request
// What you want here
}
}
xmlhttp.open("GET", "foo_url.php", true);
xmlhttp.send();
}
You can do it simpler with jQuery, if you're using that library:
$.ajax({
url: 'foo_url.php',
complete: function() {
// What you want here
}
});
If you're using jQuery's AJAX, it has a complete option, see docs
$.ajax({
url: 'foo.php',
complete: function(jqXHR, textStatus) {
alert('AJAX call complete');
}
});
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// This is when your Ajax request is complete
}
}
that is depend on your library; ex, if you are using jquery then you can use success: parameter and if javascript then you can use if (xmlhttp.readyState==4 && xmlhttp.status==200) statement.
If you are using xmlhttp object for ajax call then when xmlhttp.readyState==4 then it is consider as ajax request is completed.
$.ajax({
url: 'abc.php',
data: "&id=" + id ;
complete: function(data) {
alert(data.responseText);
}
});