I am trying to pull json down from my server and parse it into a Javascript object. here is what my json looks like:
{
"tour1": [
{
"title": "building1",
"description": "Tour of building1",
"image": "Icon.png",
"video": "tour.mp4",
"length": "0.00",
"version": "1.0",
"timestamp": "1111111111"
}
]
}
Here is the requst to the server:
<!DOCTYPE html>
<html>
<body>
<h2>Parse JSON from Server</h2>
<p id="demo"></p>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
$.ajax({
url: "mysite.com/videos/tour.json";
var j = [];
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
});
window.alert(j.tour1[0].title);
</script>
</body>
</html>
I cant understand why its not working. I am new to javascript. I appreciate any help with this issue.
I think better if you use getJson when you want to load JSON-encoded data from the server using a GET HTTP request, check example bellow :
$.getJSON( "mysite.com/videos/tour.json", function( j ) {
alert( j.tour1[0].title );
});
Hope this helps.
Ajax call is an asynchronous call, j is not populated as soon as your ajax statement ends.
Use success handler of Ajax to alert the j (didn't tested the code)
$.ajax({
url: "mysite.com/videos/tour.json",
method: "GET",
dataType: "JSON",
success: function( data ){
window.alert(data.tour1[0].title);
}
});
gurvinder give the best solution, because if you are firing the ajax-request then you must catch the response, but if you make the alert in your code your request is still working and j must be undefined because it is not a global variable.
there a lot of mistakes:
check your ajax-synthax , because the declaration of "var j.." is wrong,
never use ";" in a object declaration, always use ","
in your alert you try to find a variable "j", but j don't exist, it is undefined.
Related
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 am learning how to load json data into .js file. I have created a employee.json file. I saved my js and json file and on the desktop. What I trying to do is to put all the id in json files into an array in the js. I do not know what could be wrong. Hope someone could help me out. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON with jQuery</title>
</head>
<body>
<p id="demo"></p>
<h1><h2>
<script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
}
});
document.getElementById("demo").innerHTML = res.toString();
</script>
</body>
</html>
{
"person": [
{
"id" : 1,
"firstName" : "Lokesh"
},
{
"id" : 2,
"firstName" : "bryant"
}
{
"id" : 3,
"firstName" : "kobe"
}
]
}
Error 1: Typing error. <script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>. You mistyped the src of the script, accidentally adding another another <script> start tag.
Error 2: Misplaced statement. document.getElementById("demo").innerHTML = res.toString(); should be placed in the success callback function, so it will be executed only after the server responds. If it executes prematurely, res will still be [].
Error 3: type: 'GET' should be method: 'GET', according to the docs (though 'GET' is default so you don't need to explicitly write this).
Use this:
<p id="demo"></p>
<h1><h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
method: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>
You can't use the local json to read. it gives cross origin request failure. so deploy both the files (html and json) into a we server and execute. or place the json data onto some web url(http://somesite/myjson) and then request that url and see.
First of all, the JSON shouldn't be existed as in physical "file". It has to be generated by a backend language / web service etc. The JSON tags inside a manually created "file" have high chance of data invalidity upon parsing.
Solution
Use a Web Service to generate valid JSON output. And from Javascript end, use:
JSON.stringify( data );
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
The thing is that i have an embedded python interpreter and after a user presses "Run", the output from interpreter gets transferred to a pre element. I want to take that data from pre element and send it to django server through AJAX. The problem is that even after assigning of that data to a variable, django gets nothing. Also i can start interpreter and AJAX script only after pressing "Run", both work work with onclick. I am using POST request.
`$(document).ready(function(){
$('#run').click(function(){
var input_string = String(document.getElementById("output").innerHTML);
alert(input_string);
$.ajax({
url: '/courses/python3/lesson_validate/{{ lesson_number }}/',
data: {"text": input_string, csrfmiddlewaretoken: '{{ csrf_token }}'},
dataType: "json",
type:"POST",
success: function(data, textStatus){
alert('get_response');
alert(data);
},
error : function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
});
});
`
So that code works perfectly
var input_string = String(document.getElementById("output").innerHTML);
alert(input_string);
but when i try to use that variable in ajax, server fails to get it.
I tried using async: false, it doesn't change anything.
This is view code:
`def lesson_validate(request,lesson_number):
args = {}
args.update(csrf(request))
out_compare = Lessons.objects.get(id=lesson_number).lesson_output
if request.method == "POST" and request.POST.get('text') == out_compare:
text = "they are equal"
return HttpResponse(json.dumps(text), content_type='application/javascript')
else:
args['testtest']=request.POST.get('text')
return render_to_response('course_lesson.html', args, context_instance=RequestContext(request))`
After i check request.POST.get('text') it is empty
The question is how can i get data from ajax, from a variable assigned before, not just from a sting?
It looks like you're sending JSON to the server in that request, so to get the variables in Django you'd need to do:
def lesson_validate(request,lesson_number):
import json
data = json.loads(request.body)
text = data.get('text')
# Do stuff.
I've been trying some code from here to achieve my goal but I haven't found the solution yet.
Goal: I have to get a JSON objects array from a web (through the URL) using GET method. I have to do that in Javascript or HTML. I have been trying in javascript with jquery and with ajax. The idea is when the webpage I'm making loads I have to get the JSON objects array. I would want to save the JSON objets array fetched in a string to manipulate it.
Example of JSON array that I have to get from http://www.example.com/example
[
{
"type": "1",
"id": "50a92047a88d8",
"title": "Real Madrid"
},
{
"type": "1",
"id": "500cbb1a5ef23",
"title": "Fernando Alonso"
}
]
When I run my code in the browser I always get no response.
These are some pieces of code I've tried:
HTML Code
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<link type = "text/css" rel = "stylesheet" href = "stylesheet.css"/>
</head>
<body onload = "httpGet('http://www.example.com/example')">
</body>
</html>
Javascript code
function httpGet(theUrl)
{
$.getJSON(theUrl, function(data)
{
$.each(data, function()
{
console.log(this['title']);
})
});
}
Other Javascript code
$.ajax(
{
url: theUrl,
type: 'GET',
dataType: 'json',
accept: 'application/json',
success: function(data)
{
console.log(data);
var objets= $.parseJSON(data);
$.each(objets, function(i, obj)
{
console.log(obj.title);
});
}
});
And I have prove a lot of code from here (stak overflow)...
Thank you very much and excuse me for my English.
Edit:
Some time ago I tried with stringify, but I don't really known how can it works.
I proved the following:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl, true ); // I tried with true and with false
xmlHttp.send();
var answer= xmlHttp.responseText;
var str = JSON.stringify(answer);
console.log(str);
var jsonResponse = JSON.parse(str);
console.log(jsonResponse);
}
You can't fetch data cross domain with javascript, you have to put the data under your domain or using jsonp to get it, or just print it on the page.
I have found the solution to my problem with one line php code
<?php
echo file_get_contents("http://www.example.com/example");
?>
After that, I needed to reference the php file in the javascript file.
Finally I could access to the key-value pairs of the JSON objects array.
function httpGet()
{
$.getJSON('phpfile.php', function(data)
{
$.each(data, function(i, obj)
{
console.log("object: " + i + ", title: " + obj.title);
});
});
}
In the HTML file I modified the next line:
<body onload = "httpGet()">