Appending external PHP file in jQuery - javascript

I'm referring a question answered here.
Trying to append an external PHP file in to jQuery and tried load.
$(".chatbox").load("./one.php");
This gives me the output;
Your success message!
However the concern is this removes all HTML in the body and does not really 'append' the success message.
I tried the following instead.
$(".chatbox").append("./one.php");
which merely prints this!
./one.php
Am I missing something here?

The .load() load data from the server and place the returned HTML into the matched element. But you need to use $.ajax() or $.get() that get data and return it into callback function.
$.get("./one.php", function(data) {
$(".chatbox").append(data);
});

in case if the page you're trying to load is failing due to some reason, you also need to handle the error block to inform you about the issue. Here is a more comprehensive way to do it. Here I have called a wiki page but you will know, all the php pages are in fact interpreted as valid html by PHP engine :)
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
$.ajax({
type: "GET",
url: "https://en.wikipedia.org/wiki/PHP",
data: { },
success: function(data){
$('#demo').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#demo').html("Status: " + textStatus + "<br/>Error: " + errorThrown);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo"></div>

Related

getJSON in Javascript

I am new to html and javascript.As far as i know the following code should give an alert when i press "Get JSON Data" button.But the page is not giving me any response.Any help is greatly appreciated.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
I suspected that should be the Cross-domain issue. That is why I asked for the console log. you have couple of choices:
config the cross-domain headers from your servlet/backend response.
(ex: if you're using a Servlet:)
response.setHeader('Access-Control-Allow-Origin','*');
use jsonp call back
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
The "?" on the end of the URL tells jQuery that it is a JSONP
request instead of JSON. jQuery registers and calls the callback
function automatically.
use $.ajax with CORS enabled or with jsonp
ex:
$.ajax({
url: surl,
data: {
id: id // data to be sent to server
},
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback"
});
// Named callback function from the ajax call when event fired.
function jsonpcallback(rtndata) {
// Get the id from the returned JSON string and use it to reference the target jQuery object.
var myid = "#" + rtndata.id;
$(myid).feedback(rtndata.message, {
duration: 4000,
above: true
});
}
or else, download and configure "CORS.jar" in your server side which will allow the cross-domain requests.
HOW ?
Hope you can get some idea. follow which suits for you ..
Replace the JSON call with
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err )
});
That way you can see what goes wrong. The javascript looks OK, I suspect it's a server issue.
You could also try getting back JSON from some random source, like http://1882.no/API/business/get/results.php?q=skole&page=0

Ajax with javascript / Jquery

I have problem with get the returned data from a link . It is not working .
I have search more and try everything but it still not working . could anyone help me .
the link : https://www.routingnumbers.info/api/data.json?rn=13442323
my code is
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var request = $.ajax({
type: 'GET',
data: "rn=" + "54455445",
url: "https://www.routingnumbers.info/api/data.json",
success: function(data) {
alert("Data: " + data + "\nStatusA: " + status);
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Data: " + "Err" + "\nStatus: " + status);
console.log(jqXHR, textStatus, errorThrown);
request.abort();
}
});
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
Thank you
Well, first of all, I'd always advise using proper JSON formatting in ajax requests. The data attribute should be an object instead of a variable assignment. In the end, it doesn't actually matter; the request will complete with either format. It's always nice to look at consistently-formatted code, though. Regardless, the major problems that were causing the request to fail were the type of request you were making and its origin.
In the code you provided, you were making a request to an https address. The page you were requesting from, however, was not an https page, but an http page instead. This caused the request to return the error net::ERR_INSECURE_RESPONSE.
If you fix that, however, the request still won't complete successfully. This is because XMLHttpRequest doesn't allow requests to websites that aren't the same as the one that you are requesting from. For example, you could request content from routingnumbers.info if you're running the script from within routingnumbers.info itself, but not if you're running it from elsewhere. This can be fixed by specifying the request as a jsonp request instead of the default json request.
$("button").click(function(){
$.ajax({
type: "GET",
dataType: "jsonp",
async: true,
url: "http://www.routingnumbers.info/api/data.json",
data: {
rn: "54455445"
},
success: function(data) {
var array = [];
$.each(data, function(index, value){
array.push(index + ': ' + value);
});
alert(array.join("\n"));
},
error: function(data) {
alert(data.statusText);
}
});
});
JSFiddle
Hope this is helpful!

Loading JSON into JavaScript variable locally without server-side script?

I have 41 JSON objects, each with the same scheme.
These objects are fairly large, and so I would like to load the object conditionally into a JavaScript script, when selecting an <option> from a <select> menu with an id of myPicker.
So far, I have set up jQuery to handle changes on the <select>:
$('#myPicker').change(function() {
alert('Value change to ' + $(this).attr('value'));
$('#container').empty();
init();
});
The function init() draws stuff in div called container.
When I change myPicker, I want init() to behave like init(value), which in turn tells init to load one of 41 JSON objects from a file (based on value).
Is loading a chunk of JSON from a file (located on the server-side) doable in this case, or do I need to use a server-side script handling Ajax form submissions and responses, etc.?
EDIT
I wrote the following code:
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$('#cellTypePicker').change(function() {
alert('Value change to ' + $(this).attr('value'));
$('#container').empty();
initFromPicker($(this).attr('value'));
});
});
function initFromPicker(name) {
// pick default cell type from picker, if name is undefined
if (typeof name === "undefined")
name = 'AG10803-DS12374';
var jsonUrl = "file://foo/bar/results/json/" + name + ".json";
alert(jsonUrl);
$.ajax({
url: jsonUrl,
dataType: 'json',
success: function(response){
alert("Success!");
},
error: function(xhr, textStatus, errorThrown){
alert("Error: " + textStatus + " | " + errorThrown + " | " + xhr);
}
});
init(); // refills container...
}
</script>
<body onload="initFromPicker();">
...
The line alert("Success!"); never gets called.
Instead, I get the following error:
Error: error | Error: NETWORK_ERR: XMLHttpRequest Exception 101 | [object Object]
I am checking the value jsonUrl and it appears to be a proper URL. The file that it points to is present and I have permissions to access it (it is sitting in my home folder). Is there something I am still missing?
Let me make sure I understand your question. I think you want to:
have a handful of files out there that contain JSON objects
depending on which option is selected a particular file is loaded
the contents of the file is JSON and
you want to be able to use the JSON object later on in other javascript
If this is the case then you would just need to do something like:
$('#myPicker').change(function() {
$('#container').empty();
init($(this).val());
});
function init(jsonUrl){
$.ajax({
url: jsonUrl
dataType: 'json'
success: function(response){
// response should be automagically parsed into a JSON object
// now you can just access the properties using dot notation:
$('#container').html('<h1>' + response.property + '</h1>');
}
});
}
EDIT: Exception 101 means the requester has asked the server to switch protocols and the server is acknowledging that it will do so[1]. I think since you're using file://foo/bar/... you might need to toggle the isLocal flag for the $.ajax function [2], but honestly, I'm not sure.
[1] http://en.wikipedia.org/wiki/Http_status_codes#1xx_Informational
[2] http://api.jquery.com/jQuery.ajax/
Below is a complete working example that pulls a JSON object from Twitter, so you should be able to copy/paste the entire thing into a file and run it in a browser and have it work. If your server is configured correctly and your .json files are in the document_root and have the appropriate permissions, you should be able to swap them out for the Twitter URL and have it work the same way...
<!doctype html>
<html>
<head>
<title>My Super Rad Answer</title>
</head>
<body>
<form id="my-form">
<select id="cellTypePicker">
<option value=''>No Value</option>
<option value="AG10803-DS12374">AG10803-DS12374</option>
</select>
</form>
</body>
<!-- Grab the latest verson of jQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
// Wait until the page is fully loaded
$(document).ready(function(){
$('#cellTypePicker').change(function() {
// Grab the value of the select field
var name = $(this).val();
if (!name) {
// Make sure it's not null...
// This is preferred over using === because if name is
// anything but null, it will return fale
name = 'AG10803-DS12374';
}
// Right now I'm overwriting this to a resource that I KNOW
// will always work, unless Twitter is down.
//
// Make sure your files are in the right places with the
// right permissions...
var jsonUrl = "http://api.twitter.com/help/test";
$.ajax({
url: jsonUrl,
dataType: 'json',
success: function(response){
// JSON.stringify takes a JSON object and
// turns it into a string
//
// This is super helpful for debugging
alert(JSON.stringify( response ));
},
error: function(xhr, textStatus, errorThrown){
alert("Error: " + textStatus + " | " + errorThrown + " | " + xhr);
}
});
});
});
</script>
</html>
You can use $.ajax() for this - or one of the shortcuts, e.g. $.getJSON():
$.getJSON('somefile', function(data) {
// here, data is javascript object represented by the json in somefile
});

JQuery Ajax Request returns no data

I am trying out JQuery Ajax methods. I wrote a simple Ajax request to fetch certain 'tagged' photos from Flickr. Following is the snippet I am using:
function startSearch() {
$(function() {
var tagValue = $("#tagInput").attr("value");
alert(tagValue);
$.ajax({
url: "http://api.flickr.com/services/feeds/photos_public.gne?tags=" + tagValue + "&tagmode=any&format=json&jsoncallback",
dataType: 'json',
async: false,
success: function(data) {
alert("Success");
$.each(data.items, function(i, item) {
var pic = item.media.m;
$("<img/>").attr("src", pic).appendTo("#images");
});
},
error: function(data, error) {
alert("Error " + error);
}
}); });
'startSearch' is associated with a Search button. User is supposed to input a 'tag' to search and on click this function gets called.
Problem is that I am not receiving any 'data' in response. Hence no images gets displayed.
What am I doing wrong here?
Thanks & Regards,
Keya
I think the problem is that you're trying to make a cross-site request, which doesn't work because of security concern. You could use JSONP instead, e.g. as described in http://www.viget.com/inspire/pulling-your-flickr-feed-with-jquery/
You can also try searching for "cross site ajax" on this site, there's plenty of discussion about it.

How to get external pages into div?

i tried for including external page in div in my home page but the problem is that external page is developed in ajax means that if we click any link inside that external it doesn't change URL .
My problem is that when i included that page in my code using code on link.
http://www.javascriptkit.com/script/script2/ajaxpagefetcher.shtml
it doesn't show images and when i click any link it also doesn't work..
Please suggest some solution.
Thanks...
can use this JavaScript method to get content of any page and set it to div
function CallPageSync(url, data) {
var response;
$.ajax({
async: false,
url: url,
data: data, // parameters
timeout: 4000,
success: function(result) {
response = result;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
response = "err--" + XMLHttpRequest.status + " -- " + XMLHttpRequest.statusText;
}
});
return response;
}
$('contentDiv').html(CallPageSync(url, ''))
This sounds like what iframes are for.

Categories