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();
});
}
});
Related
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
});
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 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'
I have looked at a number of answers and other websites, but none answer my specific question. I have a webpage with "+" and "-" buttons, which should increment a variable called "pieFact". This variable must be updated dynamically without having to refresh the page. It should then be passed to my Django view each time the value is changed. This will be used to update the size of pie charts in a web map. I have the following:
<button type="button" id=bttnMinus onclick="pieFact=pieFact*0.9">-</button>
<button type="button" id=bttnPlus onclick="pieFact=pieFact*1.1">+</button></td>
<script type="text.javascript">
var pieFact=0;
</script>
How can I pass the value of "pieFact" to Django? Based on my limited knowledge, I think I may have to use AJAX post/get.
In order to keep from refreshing the page, yes, you will need AJAX. I usually don't like to suggest libraries too much in answers, however, in the interest of being easily cross-browser compatible, I would suggest the use of jQuery.
With jQuery it would be as simple as
Inside of your django template
<html>
...
<head>
<script>
var URL = "{% url 'my_view_that_updates_pieFact' %}";
</script>
</head>
...
Later on...
You'll need to either POST or GET the data to the server via AJAX. To be more RESTful, whenever I need to send data to the server I use POST. jQuery provides the $.post() convenience function to AJAX data to a url via POST. The three parameters are the URL, the data to send (as a JavaScript object; think python dictionaries if you're not too familiar with JavaScript), and a callback function once the server sends back a response.
<script>
function updatePieFact(){
var data = {'pieFact': pieFact};
$.post(URL, data, function(response){
if(response === 'success'){ alert('Yay!'); }
else{ alert('Error! :('); }
});
}
The .click() functions are basically the same thing as specifying onlick in the html attribute. Both click events update pieFact as you would expect and then call updatePieFact() to send the value of pieFact to the server.
$(document).ready(function(){
$('#bttnMinus').click(function(){
pieFact *= 0.9;
updatePieFact();
});
$('#bttnPlus').click(function(){
pieFact *= 1.1;
updatePieFact();
});
});
</script>
In views.py
Since I've used the $.post() function in the JavaScript, the request that Django is going to receive is going to have a method of "POST", so I check to make sure that the method is indeed POST (this means that if someone visits the URL for this view with something like a GET request, they won't update anything). Once I see that the request is, in fact, a POST, I check to see if the key 'pieFact' is in the dict request.POST.
Remember when I set the variable data in the javascript to {'pieFact': pieFact}? That javascript just becomes the request.POST python dictionary. So, if in the javascript I had instead used var data = {'hello': pieFact};, then I would be checking if 'hello' in request.POST instead. Once I see that pieFact is in the request.POST dictionary, I can get its value and then do something with it. If everything is successful, I return an HttpResponse with the string 'success'. This correlates with the check in javascript: if(response === 'success').
def my_view_that_updates_pieFact(request):
if request.method == 'POST':
if 'pieFact' in request.POST:
pieFact = request.POST['pieFact']
# doSomething with pieFact here...
return HttpResponse('success') # if everything is OK
# nothing went well
return HttpRepsonse('FAIL!!!!!')
Hopefully that will get you pointed in the right direction.
I have a link that when clicked needs to call a controller action with certain data which must be retrieved via JavaScript. The action will be returning a FileStreamResult.
I looked at #Url.Action but I couldn't figure out how (or even if) I could pass value dictionary stuff which had to be retrieved via JS.
So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.
So any help on how you would do something like this would be great..
So then I went with a $.post from a click handler. The problem I'm having is that I'm not sure what to do in my success: function() to return the file stream result to the user. Or even if I can.
Exactly. You can't do much with a received byte in javascritpt: obviously you cannot save it on the client computer nor pass it to some external program on the client. So don't call actions that are supposed to return files using AJAX. For those actions you should use normal links:
#Html.ActionLink("download file", "download", new { id = 123 })
and let the user decide what to do with the file. You could play with the Content-Disposition header and set it to either inline or attachment depending on whether you want the file to be opened with the default associated program inside the browser or prompt the user with a Save File dialog.
UPDATE:
It seems that I have misunderstood the question. If you want to append parameters to an existing link you could subscribe for the click event in javascript and modify the href by appending the necessary parameters to the query string:
$(function() {
$('#mylink').click(function() {
var someValue = 'value of parameter';
$(this).attr('href', this.href + '?paramName=' + encodeURIComponent(someValue));
return true;
});
});
Instead of going with a post, I'd go with associate a JQuery on click handler of the link which would call the controller action. This is assuming that the action method returns a FileStreamResult and sets the correct content type so that the browser interprets the result and renders it accordingly.
With your approach you'd have to interpret in the onSuccessHandler of the post on how to render the generated stream.