What do I do after I json_encode() my php array? - javascript

I am new to both php and javascript and having trouble understanding how to communicate between the two. I have a php array and I used json_encode() to turn it into json and now I just don't know what to do from there. I have just been looking around and haven't been able to find an answer of what to do from there. Do I print it? If I do print it... how do I used javascript to grab it. I can't use the php variable name since javascript doesn't understand it. I am just not grasping this concept.

The most popular way to make a Javascript script communicate with a PHP script is via Asynchronous Javascript And XML (AJAX) requests.
In AJAX requests, your javascript code calls the PHP script needed, sending to it any required parameters. Then, your PHP script should print (echo) the result (the JSON encoded array in your case), and when it does, an event gets fired in your javascript code, which you can handle accordingly.
In Javascript, there are two main ways of performing AJAX requests:
1- Using the XMLHTTPRequest object:
In this method, we are using a Javascript XMLHTTPRequest object to send the request to our PHP script, and we handle its onload event to get the response and do something with it :
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "some_url.php?param1=123");
xmlhttp.send();
xmlhttp.onload = function() {
//here the response from the PHP script is saved in the this.responseText variable
//parsing the JSON string we got into an actual array
var myArray = JSON.parse(this.responseText);
//do something with the array
}
(note that we can also handle the object's onreadystatechange, but onload is a bit simpler to handle)
2- Using a promise (fetch):
fetch("some_url.php?param1=123")
.then(function(response) {
return response.text();
})
.then(function(data)) {
var myArray = JSON.parse(data);
//do something with the array
});

Related

Making a local file hold a value to use by any user

I am trying to make a webpage that will be able to store a variable, using JavaScript, called heart-count (I was trying it with jQuery and JSON, but didn’t have any luck, I could access the number easily, but I couldn’t change it).
This variable should be easily accessed by the JavaScript and be able to be changed (or in my case incremented).
The way that I have it right now is in a local file called heart.json inside this file is the following code:
{
"hearts": 0,
"heartLog": []
}
I am accessing that file in my JavaScript like this:
$.getJSON("../js/heart.json", function(data) {
$("#num-hearts").text(data.hearts)
})
I was trying to use XMLHttpRequest (a way that was suggested to me):
var myJSON
$.getJSON("../js/heart.json", function(data) {
myJSON = data
setTimeout(() => {
myJSON.hearts++
console.log(myJSON)
console.log(data)
}, 2000);
})
var xhr = new XMLHttpRequest()
xhr.open("PUT","../js/heart.json",true)
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
xhr.send(JSON.stringify(myJSON))
I can’t confirm that this doesn’t work, since the way that the webpage is set up I test it using some interesting methods (interesting, but required…), and those use localhost. The reason I say that I can’t confirm that it doesn’t work, is because when I test the previous code, it says that “PUT” isn’t a valid protocol.
If there are any suggestions or validations of my code, that would help a lot.
How ya doin? I'm sorry to say but you can not write to a file in server directly with jQuery or Javascript because Javascript is frontend language. It doesn't have the capability to do so.
However you can send or receive data with XMLHttpRequest, but you need a server side language/program to process your XMLHttpRequest.

How can I make HTML fill itself with the content from the JSON file using handlebars?

I need to make HTML fill itself with content from JSON file using Mustache or Handlebars.
I created two simple HTML templates for testing (using Handlebars) and filled them with content from an external JavaScript file. http://codepen.io/MaxVelichkin/pen/qNgxpB
Now I need content to lay initially in a JSON file.
I ran into two problems, but they both lie at the heart of solutions of the same main problem - creating a link between the content in the JSON file and HTML, so I decided to ask them in the same question.
How can I connect JSON and HTML? As far as I know there is a way, using AJAX, and there's a way that uses a server. AJAX is a new language for me, so I would be grateful for an explanation of how can I do it, using local HTTP server, that I created using Node.JS.
What should be the syntax in a JSON file? The script in the JSON file must be the same, as a script in JavaScript file, but then it should be processed with the help of JSON.parse function, is that correct? Or syntax in JSON file should be different?
For example, if we consider my example (link above), the code for the first template in the JSON file must be the same as in the JavaScript file, but before the last line document.getElementById('quoteData').innerHTML += quoteData;, I have to write the following line var contentJS = JSON.parse(quoteData);, and then change the name of the variable in the last line, so it will be: document.getElementById('quoteData').innerHTML += contentJS;, Is it right?
Try this:
HTML:
<!-- template-1 -->
<div id="testData"></div>
<script id="date-template" type="text/x-handlebars-template">
Date:<span> <b>{{date}}</b> </span> <br/> Time: <span><b>{{time}}</b></span>
</script>
JS:
function sendGet(callback) {
/* create an AJAX request using XMLHttpRequest*/
var xhr = new XMLHttpRequest();
/*reference json url taken from: http://www.jsontest.com/*/
/* Specify the type of request by using XMLHttpRequest "open",
here 'GET'(argument one) refers to request type
"http://date.jsontest.com/" (argument two) refers to JSON file location*/
xhr.open('GET', "http://date.jsontest.com/");
/*Using onload event handler you can check status of your request*/
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};
/*Using onerror event handler you can check error state, if your request failed to get the data*/
xhr.onerror = function () {
alert("Network Error");
};
/*send the request to server*/
xhr.send();
}
//For template-1
var dateTemplate = document.getElementById("date-template").innerHTML;
var template = Handlebars.compile(dateTemplate);
sendGet(function (response) {
document.getElementById('testData').innerHTML += template(response);
})
JSON:
JSON data format derives from JavaScript, so its more look like JavaScript objects, Douglas Crockford originally specified the JSON format, check here.
JavaScript Object Notation has set of rules.
Starts with open curly braces ( { ) and ends with enclosing curly braces ( } )
ex: {}
Inside baces you can add 'key' and its 'value' like { "title" : "hello json"}
here "title" is key and "hello json" is value of that key.
"key" should be string
"value" can be:
number
string
Boolean
array
object
Can not add JavaScript comments inside JSON (like // or /**/)
there are many online JSON validators, you can check whether your JSON is valid or not, check here.
When comes to linking JSON to js file, its more like provide an interface to get JSON data and use it in your JavaScript.
here XMLHttpRequest our interface. we usually call XMLHttpRequest API.
In the given js code, to get JSON from the server using an REST API (http://date.jsontest.com/)
for more information on REST API you can check here
from the url: http://date.jsontest.com/ you can get JSON object like below.
{
"time": "03:47:36 PM",
"milliseconds_since_epoch": 1471794456318,
"date": "08-21-2016"
}
Note: data is dynamic; values change on each request.
So by using external API you can get JSON, to use it in your JavaScript file/ code base you need to convert JSON to JavaScript object, JSON.parse( /* your JSON object is here */ ) converts JSON to js Object
`var responseObject = JSON.parse(xhr.responseText)`
by using dot(.) or bracket ([]) notation you can access JavaScript Object properties or keys; like below.
console.log(responseObject.time) //"03:47:36 PM"
console.log(responseObject["time"]) //"03:47:36 PM"
console.log(responseObject.milliseconds_since_epoch) //1471794456318
console.log(responseObject["milliseconds_since_epoch"])//1471794456318
console.log(responseObject.date) //"08-21-2016"
console.log(responseObject["date"]) //"08-21-2016"
So to link local JSON file (from your local directory) or an external API in your JavaScript file you can use "XMLHttpRequest".
'sendGet' function updatedin the above js block with comments please check.
In simple way:
create XMLHttpRequest instance
ex: var xhr = new XMLHttpRequest();
open request type
ex: xhr.open('GET', "http://date.jsontest.com/");
send "GET" request to server
ex: xhr.send();
register load event handler to hold JSON object if response has status code 200.
ex: xhr.onload = function () {
for more info check here
Know about these:
Object literal notation
difference between primitive and non-primitive data types
Existing references:
What is JSON and why would I use it?
What are the differences between JSON and JavaScript object?
Basically, JSON is a structured format recently uses which would be preferred due to some advantages via developers, Like simpler and easier structure and etc. Ajax is not a language, It's a technique that you can simply send a request to an API service and update your view partially without reloading the entire page.
So you need to make a server-client architecture. In this case all your server-side responses would be sent in JSON format as RESTful API. Also you can simply use the JSON response without any conversion or something else like an array object in JavaScript.
You can see some examples here to figure out better: JSON example

Execute a Javascript using AJAX call

Is it Possible to execute a Javascript using AJAX call or calling a specific function in the Javascript.
I am able to display the contents of the Javascript file like "http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first " but not able to execute the javascript.
Is there any way. Actually I am a newbie AJAX
Ajax lets you do two things:
Make a request to the server
Read the response you get back
Anything else happens around that.
If you are, for instance, running NodeJS on the server, then the HTTP request will trigger some server side JavaScript.
If you get JavaScript back from the server, then you'll have that available in a string and you can do whatever you like to it (including passing it through eval()).
Generally speaking, fetching new JS from the server like that is a bad idea. Better to have your JavaScript loaded into your webpage up front and then just trigger it based on data you get back from the server.
If I am understanding correctly the case here is that the
server is returning some javascript code and you like to evaluate it.
You can use the eval() function as described here.
In the example you provided it would be something like:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
eval(xhttp.responseText);
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
But you should be careful, because using eval is not always a good idea.
See this SO question: Why is eval a bad idea?

How to pass variables from an HTTPObject

I'm very, very new to Javascript, and to web programming in general. I think that I'm misunderstanding something fundamental, but I've been unable to figure out what.
I have the following code:
function checkUserAuth(){
var userAuthHttpObject = new XMLHttpRequest();
var url = baseURL + "/userAuth";
userAuthHttpObject.open("POST",url,true);
userAuthHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
userAuthHttpObject.onload=function(){
if (userAuthHttpObject.readyState == 4) {
var response = json.loads(userAuthHttpObject.responseText);
return response; //This is the part that doesn't work!
}
};
userAuthHttpObject.send(params);
}
I would love to call it from my page with something like:
var authResponse = checkUserAuth();
And then just do what I want with that data.
Returning a variable, however, just returns it to the userAuthObject, and not all the way back to the function that was originally called.
Is there a way to get the data out of the HttpObject, and into the page that called the function?
Working with AJAX requires wrapping your head around asynchronous behavior, which is different than other types of programming. Rather than returning values directly, you want to set up a callback function.
Create another JavaScript function which accepts the AJAX response as a parameter. This function, let's call it "takeAction(response)", should do whatever it needs to, perhaps print a failure message or set a value in a hidden field and submit a form, whatever.
then where you have "return response" put "takeAction(response)".
So now, takeAction will do whatever it was you would have done after you called "var authResponse = checkUserAuth();"
There are a couple of best practices you should start with before you continue to write the script you asked about
XMLHTTTPRequest() is not browser consistent. I would recommend you use a library such as mootools or the excellent jquery.ajax as a starting point. it easier to implement and works more consistently. http://api.jquery.com/jQuery.ajax/
content type is important. You will have have problems trying to parse json data if you used a form content type. use "application/json" if you want to use json.
true user authorization should be done on the server, never in the browser. I'm not sure how you are using this script, but I suggest you may want to reconsider.
Preliminaries out of the way, Here is one way I would get information from an ajax call into the page with jquery:
$.ajax({
//get an html chunk
url: 'ajax/test.html',
// do something with the html chunk
success: function(htmlData) {
//replace the content of <div id="auth">
$('#auth').html(htmlData);
//replace content of #auth with only the data in #message from
//the data we recieved in our ajax call
$('#auth').html( function() {
return $(htmlData).find('#message').text();
});
}
});

Using JSON data in a javascript function

I am returing JSON data as a response in a web service I am writing.
I am wondering what is the best way to consume the data, returned to a Javascript function (passed as an argument).
Do I:
use eval()
use Doug Crawfords jSon parser to parse the JSON data into a Javascript object
simply use the returned data as an object literal
BTW, I am still learning Javascript, (just started reading the Definitive Guide 2 days ago) so if my question seems a bit naive or asinine - bear with me.
I would suggest a few things, first, on the web service side:
If a callback=functionName parameter is passed in the query string, then return the properly serialized JSON as the only parameter to the callback function (In this case functionName
If no callback was requested, then simply return the properly serialized JSON string. (This is helpful for when other languages consume the JSON. PHP or Ruby for instance)
Then, as far as consuming it, if you are on the same domain as the web service, you can retrieve the code and use the json2.js parser to parse it. If you are on a separate domain, use the callback parameter when requesting the data, and make sure you set up a function to handle the callback.
Simple example (Using PHP):
<?php
$callback = null;
if( isset($_REQUEST['callback']) ){
$callback = $_REQUEST['callback'];
}
$fakeData = array( 'key' => 'value');
$json = json_encode( $fakeData );
echo $callback ? "$callback($json)" : $json;
?>
JS (On different domain than the web service):
function handleCallback( data ){
alert( data.key );
}
function get_json(){
// Dynamically create the script element
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://yourwebservice.com/service/?callback=handleCallback";
document.getElementsByTagName('head')[0].appendChild( script );
}
Calling get_json would dynamically create the request (as a script element due to cross domain restrictions. You can't use XMLHttpRequest to make cross domain requests in most browsers), and the PHP returned script would correctly call the handleCallback function when the script returns.
If you are using jQuery you can set it up so it returns as a JSON object.
http://api.jquery.com/jQuery.getJSON/
Assuming that your webservice is decorated with ScriptService attribute:
I would suggest using json2.js to handle the json clientside. It defers to native implementations when they are available.
(1). use eval()
Only if you're certain the data is clean. I'd never trust anything from an outside source.
(2). use Doug Crawfords jSon parser to parse the JSON data into a Javascript object
Best idea overall. Even jQuery uses plain old eval() to parse JSON.
(3). simply use the returned data as an object literal
When it's returned, it's just a string, not an object unless passed through one of the two aforementioned functions, or wrapped in a function ala JSONP.

Categories