Load data from local JSON file into javascript - javascript

[added:] Thank you guys for the reply. I understand that ajax has to used on a server. I wonder if there is a way to load the data from local json file into js in this example?
I have a file named employee.json. I tried load this JSON data into JavaScript. I saved both the .json and .html files on my desktop but when I click in the HTML, there is nothing shown. I tried to use alert() in the .ajax() method but it does not work. I am not sure what is wrong with my AJAX method. What do I need to do to take the id from the JSON and put it into an array in javaScript? Thank you in advance.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<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.employee).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>
</body>
</html>
{
"employee": [{
"id" : 1,
"firstName" : "Lokesh"
},{
"id" : 2,
"firstName" : "bryant"
},{
"id" : 3,
"firstName" : "kobe"
}]
}

As an alternative you can load your JSON as a javascript, just wrap all your JSON data into
var employees = { /*all your json data here*/ }
and save this as employees.js
Then you can just use a regular script tag in the html:
<script src="/yourpath/employees.js"/>
And then inside your javascript "employees" will be a global object.
so you will have:
employess.employee[1].FirstName
result in "bryant" in your case;

Related

Replace data into json file using PHP and javascript

I have a json file (file1.json) which contain json data.
I would like to replace these data by new datas (newDataToStore).
I don't know how to do it using a php file (save.php file below) ?
Content of file1.json :
[
{
"key" : "test1",
"desc": "desc1"
},
{
"key" : "test2",
"desc": "desc2"
},
]
New json to write into json1.json file :
var newDataToStore =
[
{
"key" : "test2",
"desc": "desc2"
},
{
"key" : "test3",
"desc": "desc3"
},
];
JS
this.save = function (newDataToStore) {
jQuery.ajax({
type : "POST",
dataType : "json",
url : 'save.php',
data : newDataToStore,
success : function() {
console.log("SUCCESS");
},
error : function() {
console.log("ERROR");
}
});
}
Another approach:
You'll need to stringify the JS-Object before sending it to the server:
this.save = function (newDataToStore) {
jQuery.ajax({
type : "POST",
dataType : "json",
url : 'save.php',
data : {'json': JSON.stringify(newDataToStore)},
success : function() {
console.log("SUCCESS");
},
error : function() {
console.log("ERROR");
}
});
}
On the serverside your script should do something like (as Mohammad Alabed pointed out):
file_put_contents('/path/to/file1.json', $_POST['json']);
BUT, beware! Users could write arbitrary data to the file. You should always validate user input on the server side. (Maybe using a json schema)
in php file the json data will be in the post global variable because you use post in your ajax
so all what you need is file_put_contents()
save.php
file_put_contents('file1.json', json_encode($_POST));
by using this function you will write a new json string to your json file (old content will be deleted)
in your save.php file
use json_decode()
it will decode your json datas passed from your ajax file

Send datas to JSON with jquery

i'm coding a script that send datas (nickname & score) to a JSON file in Jquery but i'm having trouble to make it work.
Here is my Jquery :
function addInfos() {
var nicknameSubmit = $(".nickname").val();
var scoreSubmit = $(".score").val();
var newScore = {
Nickname : nicknameSubmit,
Score : scoreSubmit
};
$.ajax({
url: './js/scores.json',
type: "POST",
data: JSON.stringify(newScore),
contentType: "application/json",
complete: console.log(nicknameSubmit + " " + scoreSubmit )
});
};
$(".submit").click(function(){
addInfos();
});
I used Jquery.post for this ( http://api.jquery.com/jquery.post/ )
And here is my JSON file :
[{
"Nickname" : "Alex",
"Score" : "1000"
},
{
"Nickname" : "Tom",
"Score" : "0"
}]
The script find the JSON file, it show me the correct values in the console but it doesn't add the values to the JSON file...
Can anyone know where i'm wrong ? Do i do the request properly ?
Thanks in advance,
remid
Unless your server is webdav compatible, you can't save a file on it via HTTP.
You need to create a server side script (perhaps PHP) that reads "POSTed"values and add them in your JSON file.

Pass parameter to an ajax call to read only specific field of a json file

I have a example.json file like this:
{
"User1": [{
"Age":21,
"Dogs":5,
"Cats":0
}],
"User2": [{
"Age":19,
"Dogs":2,
"Cats":1
}]
"User3": [ ...and so on...]
}
and a function LoadData(UserName); like this:
LoadData(UserName) {
$.ajax({
url: "/users/example.json",
dataType: "json",
data: // How can i say to AJAX to parse only the UserName array?
success: function(response) {
var data = $.parseJSON(response);
$.("#ageID").text(response.Age);
$.("#dogsID").text(response.Dogs);
// And so on with the others fields
}
});
}
Also.. the function LoadData(UserName); is called by the main html file (actually a .php script) with something like this:
<head>
<script type="text/javascript">
$(document).ready(function() {
LoadData("<?php echo $_SESSION['user_name']; ?>");
});
</script>
</head>
Thanks!
NOTE: i perfectly know that all data i parse/use in this way will be perfectly visible to anyone. The example above is just, indeed, an example. The data i am dealing with is not private, rather is actually public.
Try This
index.html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<p id="ageID"></p>
<p id="dogsID"></p>
<script type="text/javascript">
function LoadData(UserName) {
$.ajax({
url: "ajax.php",
dataType: "json",
data: {UserName:UserName},
success: function(response) {
$("#ageID").text(response[0].Age);
$("#dogsID").text(response[0].Dogs);
}
});
}
LoadData('User2');
</script>
</body>
</html>
ajax.php page
<?php
$jsonfile = file_get_contents("example.json");
$obj = json_decode($jsonfile);
echo json_encode($obj->$_REQUEST['UserName']);
?>
example.json
{
"User1": [{
"Age":21,
"Dogs":5,
"Cats":0
}],
"User2": [{
"Age":19,
"Dogs":2,
"Cats":1
}]
}
You can't. The server decides how it responds. You'll just have to deal with the returned data and ignore anything you don't need.
If you are also developing the server side application, then you can modify it to detect for example query parameters and react to those. Or use a different URL for getting only the UserName array.
I'm quessing here, but let's say you want to load all the user data only once but want to have a function that only deals with a single user at a time, try something like this:
function loadUsers() {
return $.ajax({
url: "/users/example.json",
dataType: "json"
});
}
function renderUser(user) {
$("#ageID").text(user.Age);
$("#dogsID").text(user.Dogs);
// And so on with the others fields
}
function loadAndRender() {
loadUsers().done(function(users) {
renderUser(users.User1);
renderUser(users.User2);
// or loop over all of them, or have the required names as arguments in loadAndRender, etc
});
}
Some additional notes and unsolicited advice:
no need to call parseJSON in the success function (or the done callback in my example)
in JS, only capitalize functions that are to be used as constructors. Don't capitalize anything else.
$.("#ageID") should be $("#ageID") (or in my personal preference $('#age'))

get content from external url using javascript

I am using freetexthost.com to store my json code..
and now i ve to get those content from url using javascript,jquery,ajax...
bt am being unable to get it..
am trying following code
<!DOCTYPE html>
<html>
<head>
<title>Useless</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.11.0.min.js'></script>
<script type="text/javascript">
$.ajax({
type: "GET",
url: "http://freetexthost.com/r56ct5aw03",
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
</script>
</head>
<body>
<div class="content" >Hello</div>
</body>
</html>
getting an error as `Uncaught SyntaxError: Unexpected token <
is there any chances we can manipulate content of other page(url) using js...
in your json file create function:
//----for example
parseResponse({"Name": "Foo", "Id": 1234, "Rank": 7});
then call this function by JSONP
var result = $.getScript("http://freetexthost.com/r56ct5aw03?callback=parseResponse");
I hope to help you.
reference : JSONP
You need to close your url using ":
$.ajax({
type: "GET",
url: "https://http://freetexthost.com/r56ct5aw03", // <-- Here
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
The content of the page http://freetexthost.com/r56ct5aw03 is html, it should be jsonp to parse properly
The only difference between json and jsonp is that when calling jsonp you will also pass a callback parameter
e.g. url:"http://freetexthost.com/r56ct5aw03?callback=myFunction",
Now the server side should print the json enclosed in this function name like below.
myFunction(
{
"sites":
[
{
"siteName": "123",
"domainName": "http://www.123.com",
"description": "123"
},
{
"siteName": "asd",
"domainName": "http://www.asd.com",
"description": "asd"
},
{
"siteName": "zxc",
"domainName": "http://www.zxc.com",
"description": "zxc"
}
]
}
);

How to post this array and print in php?

How can I send this array back to the server so I can handle it in PHP?
<script>
var myJSONObject = {
"onw": [
{"name": "nilesh", "age": "31", "sal": "4000"},
{"name1": "nitin", "age": "11", "sal": "14000"}]
};
document.write(myJSONObject.join());
</script>
You can use serialization method. i.e serialize the javascript variable and pass it to php, in php file you can deserialize the same.
serializing : Serializing to JSON in jQuery
Ref: http://api.jquery.com/serializeArray/
Never use document.write as its outdated, the preferred way to add elements to DOM is using appendChild
Example Code for appending:
var textNode = document.createTextNode("some text"); // creates new text node
textNode.appendChild(document.body); // adds to the end of the body
For posting data to php by using jquery:
Before sending it to server, you need to format it as String using JSON.stringify
var formattedData = JSON.stringify(myJSONObject )
$.ajax({
type: "POST",
url: "server.php",
data: formattedData ,
dataType: 'json',
success: function () {
alert("Data posted to php and processed succesfully");
}
});
var json_text = JSON.stringify(myJSONObject, null, 2);
alert(json_text);

Categories