I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'
Related
I am new to AJAX here. How can i replace the initial php function after the action of ajax is execute? I have found that the page will not refresh after the action is execute.
Here is the code:
javascript
function set_ddm(another_data) {
var result = $.ajax({
url: '../display/ea_form_header.php',
type: 'POST',
data: {
action: 'set_ddm',
Data_store: another_data,
},
success: function(data) {
console.log(data);
}
}).responseText;
}
php code
<td>
<?php
//initial function (customized drop down)
print ddm_jsfunc_employee("employee_list",$employee_list)
set_ddm(data);
if($_POST['action'] =='set_ddm') {
$employee_list=$_POST['Data_store'];
$employee_list_decoded = json_decode($employee_list,true);
//expected this function to replace the initial function after ajax was called
print ddm_jsfunc_employee("employee_list",$employee_list_decoded);
} ?>
</td>
I expect the function will replace the initial function and show in the main page but it only show in console after ajax(page aren't refresh to show it). Is there any wrong with the code or any solution for this? (the ddm_jsfunc_employee must be there to print the drop down)
thanks in advance
From ajax success callback you have to set that response in the html to view on web page.
like this:
$('.elementClass').html(response);
i hope this will works for you.
I think you have a slight misunderstanding about what AJAX is, it is not something to replace your PHP code with, but to asynchronously get data and update your webpage without reloading.
Let's first take a look at the .ajax function specifically interesting for us now is the .done() callback method, because JavaScript does the request realtime (async) JavaScript does not know when the request is done. But it allows us to specify a function inside the .done for it to call when it is done.
A really simple example would be:
$.ajax('https://stackoverflow.com')
.done(function(data) {
// We can do what we want with the data here.
console.log(data);
});
Now when the request is done the function we defined in .done will be called, in this case a simple log. But you would want to change this to a function that updates your HTML.
I also see you are calling JavaScript functions in your PHP, this will not work as PHP runs on your server but JavaScript runs in your browser. (Unless you use node or the likes)
Just a tip; it is advised to place JavaScript at the bottom of your HTML page as JavaScript is blocking content. (proper link explaining needed here)
Meaning your browser will stop parsing the HTML and run the JavaScript as it finds it.
Long story short, if you want to replace the PHP code, you would have to remove it. Make a PHP script which gives you your data. AJAX call it and then use .done or success and update your webpage from there.
I have simplified my Code to breakdown the Problem and to have a simple Example with a Timestamp for whats actually going wrong.
So please not be suprised why i do a AJAX call, this is for the real functionality of the Servlet.
Its a Servlet and the follwing code is part of a JSP page, im Working on JAVA 1.7 and a Tomcat 7. I run it in Firefox and Chrome.
My goal is to retrieve a value from a Java method and write it on the servlet page into the DIV "ContentCharts".
The Problem is that Javascript does not update the vaule of "zeit" and always writes the same Timestamp into the DIV-Container and on the Console
$(document).ready(function()
{
function ausgabe()
{
<%
GregorianCalendar now = new GregorianCalendar();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
String JZeit = df.format(now.getTime());
System.out.println("FKT ausgabe zeit:"+ JZeit);
%>
var zeit='<%=JZeit %>';
console.info('Zeit:', zeit);
document.getElementById('ContentCharts').innerHTML = zeit;
}
$("#subtab2").click(function()
{
$.ajax
(
{
url:'overview',
data:{dbname:this.className},
type:'get',
cache:false,
success:function(){ausgabe();},
error:function(){alert('error');}
}
);
}
}
To test this I write the value of the JAVA varible "Jzeit" into the Serverlogs and get this (Click to see the Picture) results when I click the buttons three times. As you can see in the Picture here I get the right Timestamps.
Now I have also post the Value of the JS varialbe "zeit" into the Firebug Console. And now i get the Wrong time Stamps (Click to see the Picture)
The Content in the DIV is refreshing but here is the same Problem like in the Console, its always the same Timestamp.
These are my thoughts and Questions:
Why has the JS variable the wrong value when its right in JAVA?
Is there any option to say JS that it has to update the variable?
Could it be that JS saves the answers of the JAVA code and does not run it anymore, but runs the upper JAVA Code Snippet because there is no direct connection betwen JS and JAVA, like a value allocation?
How can i fix my Problem?
If you need more Informations to help me please ask for it.
You're a bit confused about the ajax pattern.
Note that anything you write in <%= jsp tags %> will be rendered on the server, then sent to the client where it will never change. Therefore your ausgabe function will always return the same result when it is called. Subsequent calls to the function will not make repeated server requests, which is the behavior you're observing.
To fix this, the success function in your ajax call should take an argument which will be instantiated with the response from the server. The java code you've written in the jsp tags in the ausgabe function should be moved to the server and any variables you need should be returned from the overview endpoint. Then, the ausgabe function should be refactored to take an argument containing the server-calculated values, and update your page as desired.
Here is some reading on ajax requests:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
http://api.jquery.com/jquery.ajax/
I am on Linux -both browser side & server side- with a recent Firefox 38 or 42 if that matters; this question gives more context, and the github GPLv3 project containing my code. It is not a usual Web application (it would have usually one, and perhaps a dozen, of simultaneous Web users). I am writing or generating both server & browser side code
Let's suppose I have some HTML5 code like
<div id="mydyndiv_id"></div>
I am making an AJAX request with JQuery. On success it should insert some (AJAX generated) HTML element, e.g. <b>bold</b> (in reality it is a much bigger HTML fragment with nested <span>-s whose content is dynamically generated from the POST argument of the AJAX request), into that div and call some other Javascript function doit, e.g. doit(42) only once just after the AJAX request (e.g. that function would clear some other <textarea> in my page, and the 42 argument is provided by the AJAX response). I can change code both on server side (e.g. alter the AJAX processing) and on browser side.
What is the most idiomatic way to achieve that?
making a JSON AJAX which contains both the inserted HTML & the function argument, so the AJAX response could be {"text":"<b>bold</b>", "data": 42}" of Content-type: "application/json" and the Javascript code would be
$.ajax
({url: "/someajax",
method: "POST",
data: {"somearg": "foo"},
datatype: "json",
success: function(jsa) {
$("#mydyndiv_id").html(jsa.text);
doit(jsa.data);
}});
this is rather heavy, the server should double-encode HTML&JSON the HTML fragment: it needs first to construct the <b>bold</b> fragment -with HTML encoding, and then to construct the JSON object and send it.
making an HTML AJAX which has some <script> element. The AJAX response would be of Content-type: text/html and would contain <b>bold</b><script>doit(42)</script>, and the Javascript code would be
$.ajax
({url: "/someajax",
method: "POST",
data: {"somearg": "foo"},
datatype: "html",
success: function(ht) {
$("#mydyndiv_id").html(ht);
}});
this might be wrong, since the doit(42) function could be perhaps called more than once and is kept in the DOM and I don't want that
making a Javascript AJAX; the AJAX response would be of Content-type: application-javascript and would contain:
$("#mydyndiv_id").html("<b>bold</b>");
doit(42);
with the AJAX invocation in Javascript being
$.ajax
({url: "/someajax",
method: "POST",
data: {"somearg": "foo"},
datatype: "script",
success: function(jscode) { /* empty body */ }
})
This is brittle w.r.t. errors in doit(42) (see this question; the only debugging technique I found is lots of console.log and that is painful) and also requires double encoding on server side.
Of course, any other technique is welcome!
PS. If you are curious, the code is commit a6f1dd7514e5 of the MELT monitor (alpha stage) and you would try the http://localhost.localdomain:8086/nanoedit.html URL in your browser; this software (which is also a specialized HTTP server!) would have only very few simultaneous Web users (usually one, perhaps a dozen); in that sense it is not a usual web application. In my dreams it could become a workbench for a small team of (C & C++) software developers, and the GUI of that workbench would be their browser.
These different approaches have pros and cons, but generally the first two options are more advisable, let's see:
JSON AJAX
First of all, working with templating on your server is the right approach. If you use this method you will be able to pass more flexible data from your server to your client as you can e.g. use {"text":"<b>bold</b>", "data": 42, "more_data": 43}".
You are not bound to use just the data at the moment you initially create the service but expand passed data easily.
HTML AJAX
This method is simple and if you would like to have a service for every single piece of data you need to pass, rather than a service for multiple pieces, this is the preferable choice. In difference to the JSON AJAX method, you will not be able to expand here and if needed, you'll naturally have to create a new service for passing new data.
Javascript AJAX
Altough it is possible, tis method is rather unadivsable, as you can not maintain your application in a reasonable way, as your templating is client-side. See what Peter-Paul Koch says here:
Although templating is the correct solution, doing it in the browser is fundamentally wrong. The cost of application maintenance should not be offloaded onto all their users’s browsers (we’re talking millions of hits per month here) — especially not the mobile ones. This job belongs on the server.
Further reading : Why client-side templating is wrong.
First approach looks good for me, but generally it's a little bit ugly to transfer raw HTML via AJAX, if you have to transfer raw HTML it's better to use techniques called PJAX, see jquery-pjax plugin for more information of how to use and customize it.
From my point of view best approach would start using jquery-template to avoid transferring HTML over AJAX and start transfer only object witch would be rendered to template on frontend.Call doit method within handling success is ok until it use data provided in response.
I would rather go with a variation of first approach. But, it depends on the kind of generated HTML that you are currently returning from the server-side.
If it is a simple element, then you could just return a JSON object from server with one of the properties identifying the element.
For example, the response from the web-service would be like:
{'elem': 'b', 'text': 'bold', 'value': '42'}
And you consume that in the AJAX call like this:
$.ajax({
datatype: "json",
...
success: function(response) {
// create the required element client-side
var elem = document.createElement(response.elem);
// use other properties of the response object
elem.textContent = response.text + doit(response.value);
// add the element to your div
$('#mydiv-1')[0].appendChild(elem);
}
});
Where doit is the Javascript function that is already part of your client-side code-base and you just use the arguments returned by the web-service.
Alternatively, if your generated HTML is a complex fragment, then you need to identify common patterns and use client-side templates to transform the returned data into presentation.
For example, your client-side template may look like this:
<script type='text/template' id='tmpl'>
<div><h3></h3><p></p><h5></h5></div>
</script>
Your web-service returns something like this:
{'title': 'title', 'text': 'paragraph', 'value': '42'}
And you consume that in the AJAX call like this:
$.ajax({
datatype: "json",
...
success: function(response) {
// clone the client-side template
var template = $('#tmpl').html(), $elem = $(template);
// append to your div
$('#mydiv-2').append($elem);
// populate the cloned template with returned object properties
$elem.find('h3').text(response.title);
$elem.find('p').text(response.text);
$elem.find('h5').text(doit(response.value));
}
});
This way you avoid returning generated HTML from your server and manage the presentation details at the client-side only. Your web-service needs not to know the presentational aspects and deals only with raw data (consuming or spewing). The client-side code gets data from the web-service and deals with using and/or presenting that data as part of the client-side app.
Demo for both the variations: https://jsfiddle.net/abhitalks/wuhnuv99/
Bottom-line: Don't transfer code. Transfer data. Code should then use that data.
I would like to get the contents of a file on the server into a string. What is the easiest way to do this? Right now I am trying:
<script type="text/template" src="partials/someTemplate.html"
id="someTemplate"></script>
<script>
console.log($('#someTemplate').html()); //nothing comes up
</script>
A hacky way to do this is:
$('<div>').appendTo(document.body)
.load('partials/someTemplate.html', function () {console.log(this.innerHTML);} );
and then get the innerHTML of that, but that's a waste of an HTML element. Any thoughts? I feel like this should be silly easy.
Just use $.get():
var html;
$.get('partials/someTemplate.html', function(res)
{
html = res;
});
You basically need to use an asynchronous server request (ajax) to get the content of a file and process it later.
This can be done in pure JavaScript using XMLHttpRequest but the most popular and easiest way to do this is using jQuery's $.ajax function.
$.ajax({
url: "partials/someTemplate.html"
}).done(function( content ) {
console.log( "Your returned content is " + content );
});
You can configure this ajax call in many ways as described in documentation, you can pass parameters to the file, cache the request or demand a specific content type to be returned if that is necessary, but given example would do just fine for what you are trying to accomplish.
Please note that there are many ways to do an ajax request in jQuery, like .load(), $.post(), $.get(), $.getScript() and $.getJSON() but those are all just shorthand methods for an Ajax request so if you use those you are basically using an $.ajax with some predefined parameters.
Also, make sure that you need to use JavaScript and an async request at all. Getting content of a file inside some other file is mostly often done using some server side processing language like PHP (require() and include()),.NET, Java etc., and while that seems obvious for some people I felt obligated to say that since you didn't provide enaugh information about why you need that content and what you want to do with it.
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();
});
}
});