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
Related
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>
I have this JavaScript code:
<script type="text/javascript">
$(document).ready(function() {
$(".deleteImage").on('click', function() {
var idmess = $(this).data("id");
var token = $(this).data("token");
$.ajax({
url: '{{ url('admin/deletemulti') }}/'+encodeURI(idmess),
type: 'DELETE',
dataType: "JSON",
data: {
"id": idmess,
"_method": 'DELETE',
"_token": token,
},
success:function() {
alert("it Work");
}
});
});
});
</script>
is working just fine (data is removing from my DB and I get 200 in network), except I cannot get my alert any idea why is that?
UPDATE
my network
my network response
Delete Function
function destroy(Request $request) {
$image = Image::find($request->id);
Storage::delete($image->name);
$image->delete();
}
try passing an argument in your success function.
success:function(data) {
alert("it Work");
}
You have used ajax with dataType : json
So you need to respond with a valid JSON as HttpResponse else it gets into a error event.
The response of your api call:
{{ url('admin/deletemulti') }}/'+encodeURI(idmess)
should be a valid JSON. Please check api response value and fix it, or share it so that we can help you update that.
In case the response is not a valid JSON, success function will never get triggered and hence alert is not getting executed.
More info :
Ajax request returns 200 OK, but an error event is fired instead of success
When I'm making backend for myown use, and when I'm writing json, I usually put my json on success like session = true, or something like that, so later you can check like :
success: function(json) {
if(json.session == true) {
alert('something')
}
}
Maybe it's not the best solution, but it's working perfectly for me.
I'm trying to make a JavaScript that is fetching a JSON (IP DATA) and retrieves data from it (GEO IP) with AJAX and this is what I have so far:
$(document).ready(function(){
var path_to_the_webservice = "http://www.pathtothescript.com/check.php";
$.ajax({
url: path_to_the_webservice,
success: function(html)
{
if(html)
{
alert('3');
$('#content').append(html);
}
else
{
alert('4');
}
}
});
});
and I get alert(4), WHY?
Basically when you access http://www.pathtothescript.com/check.php from browser, retrieves a JSON that I have to parse with:
$.getJSON(path_to_the_json,
function(data)
{
$.each(data, function(i,item)
{
});
}
but I'm not sure how to make it.
The JSON looks like this http://j.maxmind.com/app/geoip.js
Any help?
It can be caused by Same origin policy.
Try to use JSONP request:
$.getJSON('http://example.com?callback=?', function(data) {
console.log(data);
});
Handling the response from http://j.maxmind.com/app/geoip.js
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.get('http://j.maxmind.com/app/geoip.js', function(data) {
console.log('Retrieved data:',
data,
'is type of', typeof data);
// Now we have some functions to use:
console.info('Some info:', geoip_country_name(),
geoip_latitude(),
geoip_longitude());
});
Fiddle
UPDATE:
In chat we found that my previous example works good in Google Chrome but doesn't work in Mozilla Firefox.
Though I played a little bit with it and found the solution:
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.ajax({
url: 'http://j.maxmind.com/app/geoip.js',
type: 'GET',
success: function(data) {
// Now we have some functions to use:
alert(geoip_country_name() + ': ('
+ geoip_latitude() + '; '
+ geoip_longitude() + ')');
},
error: function(e) {
console.log('Error:', e);
},
contentType: 'application/javascript; charset=ISO-8859-1',
dataType: 'script'
});
Fiddle
Also I've set a charset accordingly to service documentation.
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
});
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.