jQuery.getJSON() Not working - javascript

I'm trying to get JSON array from my php-script. Following is my Jquery code written in my jsp file-
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://example.com/root_dir/test_json.php', function(data)
{
alert(data);
});
});
but, above code showing only outer alert (i.e. alert("Inside Ready");) and not showing inner alert (i.e. alert(data); ). I'm getting expected json when I hit URL in browser. So definitly there is no problem in URL and php-script.
following is test_json.php
<?php
//Create an array
$json_response = array();
$row_array['label'] = 'A';
$row_array['value'] = $row['0 to 2'];
$row_array['color'] = '#FA2020';
array_push($json_response,$row_array);
$row_array['label'] = 'B';
$row_array['value'] = $row['2 to 3'];
$row_array['color'] = '#2BD95A';
array_push($json_response,$row_array);
$row_array['label'] = 'C';
$row_array['value'] = $row['above 3'];
$row_array['color'] = '#F7F739';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
Getting following json when I hit URL in browser-
[{"label":"A","value":"19","color":"#FA2020"},{"label":"B","value":"1","color":"#2BD95A"},{"label":"C","value":"2","color":"#F7F739"}]
I'm using jquery-1.10.2.js. Thank You..!

Try This one...Hope so it is useful to you
$(document).ready(function()
{
$.ajax({
type:'POST',
url:'http://example.com/root_dir/test_json.php',
dataType:'JSON',
data:{
},
success:function(data1){
alert(data)
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("error");
}
});
});

Your code seems to be working fine -
I just created a test page with your code and it works -
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://<<CHANGE SERVER NAME>>/zz-test/get_json.php', function(data)
{
alert(data);
});
});
</script>
</head>
<body>
</body>
</html>

Your jQuery and PHP code looks fine so, in my experience, it is usually an error caused by calling your PHP script from a different domain (i.e.: file:///). If you can access your browser's console, you should be able to see if this is in fact the error causing the data not to be displayed.
One solution for this is to add at the top of your PHP code:header('Access-Control-Allow-Origin: *');. There are however some security concerns with this, so it should not be used permanently.
Alternatively, you could upload all your HTML, CSS, JS, jQuery, etc. code to the web server hosting the PHP file, which is a far better option.
Finally, if the option above is not possible you could use JSON-P (although this does not work with POST requests), there is a question about this at Simple jQuery, PHP and JSONP example?

Related

How can I read file names from a folder and store them into a javascript array?

I'm trying to make a website and all I want is to have an array in my javascript file that has the names of every file in my "images/" folder.
I've tried everything. I've scoured stackoverflow over and over again and nothing has worked. I've tried ajax and php functions, and I've tried using MAMP and XAMPP as my local web server (I'm on mac, by the way, in case that's important). Whenever I try to load images and just log the file name to the console, nothing happens. I have no idea what to do.
I'm fairly certain the problem is that access to my directories is blocked, and it's the local web server that's not working, not the code (though I could be wrong).
Here are some more specific examples of solutions I've tried that haven't worked:
Attempt 1
index.php:
...
<?php
$images = array_values(array_diff(scandir($dir), array('..', '.')));
$imagesJS = json_encode($images);
?>
<script type="text/javascript">
var images = "<?= $imagesJS ?>";
</script>
</script src="js/bodyScript"></script>
...
bodyScript.js:
console.log(images); // returns null on attempt
Attempt 2
bodyScript.js:
var folder = "images/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
images.push(val); // add file name to array (doesn't work)
console.log(val); // log to console for debugging purposes (also doesn't work)
}
});
}
});
Attempt 3
bodyScript.js:
$.ajax({
url : "images/",
success: function(data){
$(data).find("td > a").each(function(){
console.log($(this).attr("href")); // nothing gets logged
});
}
});
Thank you
pseudo code
JavaScript:
$.ajax({
url : "http://mysite/getdirectories.php",
success: function(data){
console.log(data);
}
});
PHP (getdirectories.php)
$images = array_values(array_diff(scandir($dir), array('..', '.')));
exit(json_encode($images))

Get text from a txt file in the url

When I go to a url like this: http ://my.url.com/file.txt, the browser shows text.
I would like a simple javscript command that does the following:
1. go to the url
3. take the text that shows up on the screen
4. store it in a variable for further processing
so something like
var url = http: //my.url.com/file.txt;
//some code here that goes to the url
//some code that takes said info and does something like:
var fileInfo = ---content of file.txt---
Note that the info I seek from the txt file is in html tags
<p>Text I need in Variable</p>
Any assistance would be greatly appreciated!
Thank you!
Use the Fetch API.
Play with it at jsfiddle.net.
var url = 'https://fiddle.jshell.net/robots.txt';
var storedText;
fetch(url)
.then(function(response) {
response.text().then(function(text) {
storedText = text;
done();
});
});
function done() {
document.getElementById('log').textContent =
"Here's what I got! \n" + storedText;
}
Here's a smaller ES6 example that separates fetching from storing and showing off the result.
fetch('https://fiddle.jshell.net/robots.txt')
.then((response) => response.text().then(yourCallback));
function yourCallback( retrievedText ) { /* . . . */ }
Adoption is already across the board.
You don't have to wait. Most people don't. You shouldn't.
GitHub provides a polyfill of those who can't upgrade.
What's better about fetch than XHR? ... Lots.
Make an AJAX call to the url. Here is using the jQuery library:
$.get( "http: //my.url.com/file.txt", function( data ) {
var text = data;
});
To extract what you need from your text string in between the paragraph tags, try regex:
var pText = text.match(/<p>([^<]+)<\/p>/)[1];
Using vanilla JS :
From the MDN doc :
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Read the doc and ndcomix SO link to go further (error checking and such)
Just use jquery. It's easy fun and extensible. Don't try bizzare uses. Be sure all the time to be compatible through all the browser. If you copy this and run it under a local or remote webserver will work like a charm.
Cheers.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "test.txt", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>

AJAX Post HTML Code

I'm having an issue with sending some HTML code using AJAX please see my code below
<iframe src="http://www.w3schools.com" width="10" height="10" id="awc_frame"></iframe>
<script>var iframe = document.getElementById("awc_frame");</script>
Here is the AJAX code below
<script>
$.ajax({
type: "POST",
url: "mobileView.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
})
</script>
The code isn't sending the variable to the PHP file. Looking into the Network side of things it sends text ie if I put "" around iframe it sends this code
"val = iframe" but not the actual code within the iframe. The "var iframe"does work and pulls back the HTML code of the iframe
Please tell me what I'm doing wrongly.
Thanks in advance.
EDIT: I'm sorry. It's not the HTML code within the iFrame I need to send, It's the entire iFrame code I need to send.
Another Edit: What I'm trying to accomplish when a visitor from my company goes to my website I would like Javascript or Jquery to load an internal website from the visitors computer and then have all of the code from that website that's on the client's end to be sent to a Server which will store the entire iFrame code in a database.
This would send the entire html inside the iframe.
var iframe = $('#awc_frame').html();
First of all, var iframe does not contain HTML of the iframe element - it contains a DOM Node, which is kind of a wrapper around the iframe element (it contains various properties of that element, including the HTML).
Next thing, you probably want to wait for the iframe to completely load all the contents, so you'll have to bind to the load event of it.
Something like this should work:
var $iframe = $("#awc_frame");
$iframe.on("load", function () {
var iframeHTML = $iframe[0].contentWindow.document.body.innerHTML;
// jQuery alternative
var iframeHTML = $iframe.contents().find("body").html();
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: iframeHTML
},
success: function(data){
console.log(data);
}
});
});
Super important thing in this example
Just one more thing - please note that for websites outside of your own domain, this code won't work (due to Same Origin Policy). Any other code won't work too.
Since javascript has problems with getting the HTML from a cross-domain iframe, you can't do this across domains. However, why not just send the iframe's src attribute to the PHP page, and then just use file_get_contents to get the HTML, and then store that? Problem solved:
Javascript:
var iframe = $('#awc_frame').prop('src');
$.ajax({
type: "POST",
url: "posttest.php",
data: { val : iframe },
success: function(data){
console.log(data);
}
});
PHP:
$html = file_get_contents($_POST['val']);
what are you trying to do?
var iframe = document.getElementById("awc_frame");
above code is an javascript object of your iframe which contains a lot of properties.. since you are using jQuery, you could get that with:
var iframe = $('#awc_frame');
keep in mind that above code is the element it self in jquery object format you could get element object like this:
var iframe = $('#awc_frame')[0];
** you're doing something wrong.
if you're trying to get iframe HTML content:
var iframe_contents = $("#awc_frame").contents();
if you explain more about what you are trying to do, i can update my answer to suit you.
* UPDATE *
considering what you are trying to do..
Method #1: (Easy Way)
you could use php to fetch content of the website you need:
<?php
$contents = file_get_contents('http://www.w3schools.com');
// Saving $contents to database...
?>
Method #2: (Hard Way)
as #mdziekon said, you first should wait until your iframe gets loaded then:
var iframe = $("#awc_frame");
iframe.on("load", function () {
var contents = $(this)[0].innerHTML;
$.ajax({
type: "POST",
url: "mobileView.php",
data: {
val: contents
},
success: function(data){
console.log(data);
}
});
});
hope it solves your problem

javascript read file workaround (to view script but not load it)

EDIT My question was misleading in that it sounded like I wanted to read/write to the client machine when what I meant was that i want to read a script, not load it, from the source computer. I just assumed since you can summon (load) a script like so
<script LANGUAGE="javascript" SRC="source.js"></script>
Then there must be some way to read source.js before, during or after loading it. I ask because I am still trying to find an answer to my previous question here. I am trying to find some way to make an object/function/class aware of the code that gave rise to it, with comments and tabs and all.
you could load it via ajax and access it as a string
$.ajax({
type: "GET",
dataType: "text",
url: "jsLoader.php",
success: function(data){
alert("Length: " + data.length.toString());
eval(data);
}
});
Or:
$.ajax({
type: "GET",
dataType: "text",
url: "source.js",
success: function(data){
alert("Length: " + data.length.toString());
$("head").append('<script type="text/javascript">' + data + '</script>');
}
});
your question is kind of confusing, but it sounds like you want a way of accessing an object's code. To be honest I don't know how far you can get with this approach, and it won't include comments, but you can always just use toString().
e.g.
function myFunc() {
var somestuff = "my function's code";
};
function myClass() {
var that = this;
this.classFunc = function() {
var somethingelse = "my class function's code";
}
}
alert(myFunc.toString() + '\n\n' + myClass.toString());
Maybe I'm a little confused by your question, but first things first:
<script LANGUAGE="javascript" SRC="source.js"></script>
Does NOT read from client's machine, it reads from the web context that the page was loaded from. If the html page you're loading is www.google.com for example, then src="source.js" will load www.google.com/source.js
If I understand your question correctly though, I think the answer to your questions is that source.js does NOT get read asynchronously in the loading of the web page. Let's say source.js contains only this line.
var variable = {};
In index.html, you have this:
<script type="text/javascript">
alert(typeof(variable));
</script>
<script type="text/javascript" src="source.js"></script>
<script type="text/javascript">
alert(typeof(variable));
</script>
Then, the first alert is going to give you "undefined", and the second alert will give you "object". So, if you want to test if source.js is loaded or not, you can simply do a quick conditional:
if (typeof(variable) != "undefined") { doSomething(); }
One way to get around this would be to setup a php script which fetches the code serverside, wraps it in a function/object, and while doing so assigns the code as a string variable, somewhat like so
/*Get js script at $filename*/
$script = fread($handle, filesize($fileName));
/*Add the code as a string*/
$codeAsString = file_get_contents($fileName);
$script .= '_code=' . json_encode($codeAsString) . ';';
But this doesn't solve the bigger problem of not being able to debug the code. The reason for this is that I am using eval rather than including the scripts. The former executes the code, whereas the latter updates the DOM then executes the code. Only the latter will provide useful debugging info (see here).

How to include JSON data in javascript synchronously without parsing?

I want to load a JSON file from my own server containing an array into a javascript Object variable.
I would like to do it at the beginning of page load in a synchronous way because data is needed during page load.
I managed to use jQuery.getJSON but this is asynch ajax and it seems a little overkill.
Is there a way to load JSON in a synch way without doing your own parsing? (more or less like using a <script language="JavaScript" src="MyArray.json"></script>)
Thanks in advance for any help, hope it makes sense since I am a javascript newbie.
Paolo
getJSON() is simply shorthand for the ajax() function with the dataType:'json' set. The ajax() function will let you customize a lot about the request.
$.ajax({
url: 'MyArray.json',
async: false,
dataType: 'json',
success: function (response) {
// do stuff with response.
}
});
You still use a callback with async:false but it fires before it execution continues on from the ajax call.
Here you go:
// Load JSON text from server hosted file and return JSON parsed object
function loadJSON(filePath) {
// Load json file;
var json = loadTextFileAjaxSync(filePath, "application/json");
// Parse json
return JSON.parse(json);
}
// Load text with Ajax synchronously: takes path to file and optional MIME type
function loadTextFileAjaxSync(filePath, mimeType)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",filePath,false);
if (mimeType != null) {
if (xmlhttp.overrideMimeType) {
xmlhttp.overrideMimeType(mimeType);
}
}
xmlhttp.send();
if (xmlhttp.status==200 && xmlhttp.readyState == 4 )
{
return xmlhttp.responseText;
}
else {
// TODO Throw exception
return null;
}
}
NOTE: This code works in modern browsers only - IE8, FF, Chrome, Opera, Safari. For obosolete IE versions you must use ActiveX, let me know if you want that I will tell you how ;)
if you're using a server script of some sort, you could print the data to a script tag on the page:
<script type="text/javascript">
var settings = <?php echo $json; ?>;
</script>
This will allow you to use your data synchronously rather than trying to use AJAX asynchronously.
Otherwise you'll have to wait for the AJAX callback before continuing on with whatever it is you're doing.
I only needed to read a small input file provided in json format and extract a small amount of data. This worked just fine in the circumstances:
json file is in the same directory as the script and is called data.json, it looks something like this:
{"outlets":[
{
"name":"John Smith",
"address":"some street, some town",
"type":"restaurant"
},
..etc...
read the data into js like this:
var data = <?php echo require_once('data.json'); ?>;
Access the data items like this:
for (var i in data.outlets) {
var name = data.outlets[i].name;
... do some other stuff...
}
If RequireJS is an option, you can make it a dependency using requirejs. I use it to mock data in my Angular application. It's essential that some of the mocked data is there before the bootstrap of the app.
//Inside file my/shirt.js:
define({
color: "black",
size: "unisize"
});
Just wrap the json data in a define and declare it as a dependency. More info here: http://requirejs.org/docs/api.html#defsimple
AFAIK jQuery has deprecated synchronous XHR requests because of the potential for performance issues. You could try wrapping your app code up in the XHR response handler as in the following:
$(document).ready(function() {
$.get('/path/to/json/resource', function(response) {
//'response' now contains your data
//your app code goes here
//...
});
});
The modern HTML5 way without jQuery would be:
var url="https://api.myjson.com/bins/1hk8lu" || "my.json"
var ok=await fetch(url)
var json=await ok.json()
alert(a.test)

Categories