I'm trying to fetch a JS array created by a PHP file and re-use the JS array in a JS script in the page. I have tried many different solutions found on this site but none seems to work but I don't know what the issue is with my script.
I have a PHP file that echoes the following:
[["content11", "content12", "content13", "content14","content15"],
["content21", "content22", "content23", "content24","content25"]]
I'm using a simple Ajax get to retrieve the data:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html",
success : function(data)
{
result = data;
alert (result);
}
});
The alert displays the expected output from the PHP file but if I now try to access the array like result[0], it outputs "[" which is the first character. It looks like JS sees the output as a string rather than an array.
Is there something I should do to make JS understand it's a JS array?
I have seen many solution with JSON arrays but before going into this direction, I'd like to check if there are simple solutions with JS arrays (this would prevent me from rewriting too much code)
Thanks
Laurent
In you php file you need check that your arrays echos with json_encode.
echo json_encode($arr);
And in your javascript file:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html", // json
success : function(data)
{
var res = JSON.parse(html);
alert(html); // show raw data
alert(res); // show parsed JSON
}
});
You can use JSON.parse to format the string back into an array.
JSON.parse(result)[0]
or
var result = JSON.parse(result);
result[0];
#Rho's answer should work fine, but it appears that you're using jQuery for your AJAX call, which gives you a shortcut; you can use $.getJSON instead of $.ajax, and it will read the data as JSON and provide you with the array immediately.
$.getJSON(myUrlToPhpFile, function(result) { ... });
This is really just a short way of writing what you already have, but with a dataType of json instead of html, so you could even do it that way if you prefer. This is all assuming that you're using jQuery of course, but your code was following their API so it seems a good bet that you're either using jQuery or something compatible.
Related
Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.
I Am new in working with json and jquery. I am trying to study the basics of json and jquery by working on some example. So I use existing json data in http://api.androidhive.info/contacts for my example. I want to display this data in my HTML page. My code is:
<html>
<head>
<title>jQuery Ajax Example with JSON Response</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked.");
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php
type: "GET",
dataType: 'json', // Choosing a JSON datatype
success: function (msg) {
alert("ajax worked.");
JsonpCallback(msg);
},
})
function JsonpCallback(json)
{
for (var i in json.contacts) {
$('#wines').append('contacts: ' + json.contacts[i] + '<br/>');
}
}
return false; // keeps the page from not refreshing
});
});
</script>
</head>
<body>
<form method="post" action="">
<button value="all" type="submit">Get!</button>
</form>
<div id="wines">
<!-- Javascript will print data in here when we have finished the page -->
</div>
</body>
</html>
can any one please give me some brief introduction to JSON and how it's working ?
Thanks in advance.
You are iterating the JSON wrong, in your case since you are using jQuery (as mentioned) you can use the $.each(json, callback); helper fron jQuery, you can see the documentation here Jquery $.each documentation
For an example implementation I've created this JSFIDDLE LINK
for you. Have a great day ahead. Don't forget that JSON means
Javascript Object Notation
It's an object.
$.each(jsonData.contacts, function(k, v)
{
console.log(v.name);
$('#name').append('<li>'+v.name+'</li>');
});
jQuery
Am try to study the basics of json and jquery
Is a Javascript library with lots of very usefull methods. If you want to create a dynamic website it is very recommended to look into jQuery. There are many site with great explanation on what jQuery can do. As far as your example is concerned: There is an issue when passing variables/data from one framework to another or even when simply storing data. Here comes JSON.
JSON
Or JavaScript Object Notation (JSON) is used to solve exactly that problem. What is basically does is take all the desired data (array, variable, object, string etc.) and writes it in a human readable and for other frameworks readable fashion. I use JSON to store data in files when no database is available or when passing data from one framework to another (like JS <-> PHP).
Your example code
What happens here:
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked."); // not yet
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php --> this I don't know
type: "GET", // communication type
dataType: 'json', // Choosing a JSON datatype
success: function (msg) { // here, the whole content of the url is read, idealy it is in JSON format ofc
alert("ajax worked."); // hoorray
JsonpCallback(msg);
},
})
There is the serverside.php file that receives a GET command and returns HTML. All the HTML content is in JSON type (so no <stuff>, i.e. no actual HTML) and your success function returns that content in the msg variable. Typically you use something like
var obj = JSON.parse(text);
to convert the JSON data to Javascript variables. Read this here JSON in Javascript
JSONP
Now what if you want to do some domain crossing (as you suggested), then I strongly recommend to read this here What is JSONP all about? . It explains what JSONP is all about
I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.
Hey guys I would like to know how can I get json data with ajax call.
I tried this but seems won't work :P
First I created a JavaScript file to put inside my json data elements :
var food = [
{'name':'bread', 'price':'7,25'},
{'name':'fish', 'price':'9,00'}
];
I saved it as food.js.
Then I tried to make an ajax call from an another file, this is my code :
$(document).ready(function(){
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food.name;
alert(result);
});
}});
});
Any ideas?
Thanks in advance ;)
Firstly, you have a syntax error in your example - there's too many closing braces on the $.ajax call, although I guess that's just a typo.
In your JSON, food is an array, so you need to use an indexer to get the properties of the objects within it:
success: function(data) {
var result = data.food[0].name; // = "bread"
alert(result);
});
try this
$(document).ready(function() {
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food[0].name;
alert(result);
}
});
});
You need to loop through the returned data since it's an array:
$.each(data,function(i,val) {
alert(data[i].name);
});
I love how people are completely ignoring the fact that your "food.js" is not a JSON string, it's JavaScript code. This might work on old-school eval-based "JSON", but with jQuery AJAX your target file should be plain JSON. Remove the var food = from the start, and the ; from the end.
Then you can access data.food[0].name;
In this case, you are trying to get an another javascript file via ajax. For do this, you can "include" your script ( of food.js ) in your page, using Ajax GetScript ( see here ).
Your code is mucth better when you request directly json files.
You probably want to use the getJSON function in jquery : http://api.jquery.com/jquery.getjson/
$.getJSON( "food.json", function( data ) {
//here your callback
}
It will set the datatype to json and the method to GET by default.
You should also use the .json extension and not the js extension for you jsons. And format it like a proper json :
{
"food": [
{
"name": "bread",
"price": 7.25
},
{
"name": "fish",
"price": 9.00
}
],
}
You can use this website to help you format jsons : http://www.jsoneditoronline.org/
The way you are trying to call your element won't work. The data you obtain is an array. In the callback, you can try this :
console.log(data)
console.log(data.food)
console.log(data.food[0])
console.log(data.food[0].name)
console.log(data.food[0].price)
Finally, note that you formatted your numbers with a coma, this is not the way you format numbers in javascript. Use a dot, that way you'll be able to manipulate it as a number.
I have a php returning some json in response to a POST request made via an ajax function.
In my php function I format the data like this:
//json return
$return["answers"] = json_encode($result);
echo json_encode($return);
This returns the following string:
answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"
And this is where I am trying to catch it to use the data:
$.ajax({
type: "POST",
url: "http://ldsmatch.com/pieces/functions/question.functions.php",
dataType : 'JSON',
data: dataString,
success: function(data) {
alert(data.answers[0]["aa"]);
}
});
I've been trying to just alert the data so I can visualize it before setting up the vars I need, but am having some trouble formatting it correctly so it is usable.
If I alert data.answers[0] then it just shows me the first character in the string, which is a bracket [ and if i subsequently change the number it will go through each character in the returned string.
I have tried other variations, such as:
data.answers[0]["aa"] (this returns 'undefined' in the alert)
data.answers["aa"] (this returns 'undefined' in the alert)
data.answers[0] (this returns the first character of the string)
I feel like I'm close, but missing something. Any guidance appreciated.
edit:
thanks for all the suggestions. I removed the second json_encode and was able to parse with data.answers[0].aa
success: function(data) {
var json = $.parseJSON(data);
alert(json.answers[0]["aa"]);
}
Use parseJson like this
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
What if you remove double-encoding on PHP side? You've got an object with JSON string instead of object with first property being object itself, or you may explicitly decode "answers" property on client side as it was suggested above.