Issue with displaying the Jquery Ajax response in HTML - javascript

I need to load a page where that page needs to display some values with a dynamic pagination. So to load the values I have a rest call, In that rest call I am returning a json object. In the browser console I am able to see the json output. Now My issue is I am getting the response on $document.ready() function. Now I am trying to display the json object values in the HTML which is not happening.
JavaScript:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url : "http://localhost:8080/school-service/school/list/students/1/1",
type: "GET",
dataType: "json",
}).done( function(studentList) {
console.log("AJAX request success:" +studentList.pageNumber);
}).fail( function(jqXHR, textStatus) {
console.log("AJAX request failed with status:" + textStatus);
});
});
</script>
HTML:
<img onclick='previousPage("${studentList.pageNumber}", "${studentList.pageCount}")' src="${context}/images/previous.png">
<c:forEach var="i" begin="1" end="${studentList.pageCount}">
${i}
</c:forEach>
<img onclick='nextPage("${studentList.pageNumber}", "${studentList.pageCount}")' src="${context}/images/next.png"/>
Can anyone please help me that how can I display the json response object value in HTML.

I think you can't because the code you want to replace in your page is belong to a server-side language (i guess asp) and server-side code will be compiled before javascript execution so you'll not found the tags those tags.

So, if I understand what you are trying to do, you are trying to get the value from your AJAX request and include the returned value from .done in the html?
If that is the case, check this link out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you are returning a JSON object from .done, you will need to parse the JSON object into a string in order to place it in the DOM. From that point, you will need to decide where it should be placed. For example, you can create a div and say $('that-div').append(returned value).
Another approach could be having a default value in the html, and on .done, replace the html by calling .html on your response. But to do that you will need to grab a reference of $(this).
I hope this helps, if not let me know where my gaps are and we can go over this in a different way.

The code which you write is a server side code with JSTL, and it is not available when the AJAX response is returned.
JSP page will be converted to HTML.
The HTML page will call the server by using AJAX.
The returned response is a JSON which is received in a Javascrip Object.
You need to do some javascrip work to make your a tags
You need to write some Javascript code to render the returned response.

Try this instead
int pageCount = studentList.pageNumber;
Then in your html simply do this
<c:forEach var="i" begin="1" end=studentList.pageNumber>
i
</c:forEach>

Related

How to Set JavaScript variable inside Jsp Code

I would like to know that how can i set javascript variable in side Jsp code.
<script type='text/javascript' >
var result;
$.ajax({
type: 'GET',
url: '/api/report/test',
dataType: 'text',
success: function(data) {
result= data;
}
});
var dataTable = <%
out.print(result);
%>
</script>
Above is my Jsp code.In there i call my REST service to fetch data and print on the page.But when i try to set result variable its gave me error.I would like to know that is there any ways to call ajax method inside JSP code or how can i set java script variable inside JSP code.
No, you cannot. The JSP part is serverside, the javascript is client side.
You can only set values serverside if you push them via ajax, but then you will have four steps:
Render page with javascript(JSP)
Ajax call to JSP page(Javascript)
Process values serverside(JSP) and return output
Process returned output from JSP to user(JavaScript)
The javascript parts are purely clientside and will be executed by browser. Your server cant do anything with it. as far as your server is concerned its just text.
The JSP parts are server side and run by the server. Whatever the output it compiles is sent to the user.
You cannot "cross" over.

JS/jQuery passing array/variable/data to PHP in same page?

Im hoping you can point me in the right direction.
I have a php page, that includes some HTML markup and some JS/jQuery routines to build an array of 'user choices' based on the 'user input' (checkboxes..etc).
my question is, how can I pass off this (multidimensional) array to PHP, that is in the same page? (ultimately I want to save this data/array to my PHP session)
While looking around, I read about using another (external) .php script to do,, which is NOT what Im after, I'm hoping to do this to the SAME PAGE I'm in... WITHOUT A REFRESH.
will $.post() do this for me? without a page refresh (if we suppress the event or whatever)...
and -not- using an external .php script?
I understand PHP runs/executes FIRST... then everything else..
I'm not really trying to get PHP to do anything with the data being sent from JS/AJAX.. outside of save it to the SESSION array..
Ajax seems like it will be needed?
To summarize:
1.) PHP and JS are in/on same page (file)
2.) No page refresh
3.) No external PHP script to do 'anything'.
4.) Trying to get (multidimensional) array to PHP session in same page.
5.) I am trying to 'update' the PHP SESSION array each time a user 'clicks' on a checkbox.
I have read a little on using AJAX to post to the same page with the URL var left empty/blank?
edit:
to show the data, I want to pass...heres a snippet of the code.
its an array of objects.. where 1 of the poperties of each object is another array
example:
var somePicks = [];
somePicks.push({casename:caseName, fullname:fullName, trialdate:trialDate, citystate:cityState, plaintiff:plaintiff, itemsordered:itemsOrdered=[{name:itemOrdered, price:itemPrice}]});
when from all the checkboxes.. I update the 'sub-array' (push or splice..etc)
somePicks[i].itemsordered.push({name:itemOrdered, price:itemPrice});
'this' is the array/data I want to get into my PHP session from JS using whatever I can AJAX most likely.
You can sort of do that, but in essence it won't be any different than using an external PHP file. The PHP code gets executed on the server before ever being sent to the browser. You won't be able to update the PHP SESSION array without reconnecting with the server.
If you really want to use post to call the current page (I don't think you can just leave the url blank, but you can provide the current file name), you can just have the PHP handler code at the top of the page. However, this would be the exact same as just putting that handler code in an external file and calling it.
Either way, the page will not refresh and will look exactly the same to the user.
You can use $.ajax function with $(#formid).serializearray (). And use url as ur form action in $.ajax function.
I hope it will work for you
<form id="formId" action="post.php" methor="post">
<input type="checkbox" name="test1" value="testvalue1">TestValue1
<input type="checkbox" name="test2" value="testvalue2">TestValue2
<input type="button" id="buttonSubmit" value="click here" />
</form>
<script>
$("document").ready(function ()
{
$("#buttonSubmit").click(function () }
{
var serializedata=$("#formId").serializeArray();
$.ajax(
{
type:"post",
url:$("#formId").attr("action"),
data:{"data":serializedata},
success:function()
{
alert("yes");
}
});
});
});
</script>
<?php
if(isset($_POST))
{
session_start();
$_SESSION["data"]=$_POST["data"];
}
?>
I suggest to use the .post method of Jquery, to call a PHP file, sending the array and processing in the PHP called.
Can find the jquery documentation about .post() here: http://api.jquery.com/jquery.post/
Edited:
I used this case some time ago:
document.getElementById("promotion_heart_big").onclick = function(e){
$.post("' . URL_SITE . 'admin/querys/front.make_love.php",
{
id_element: ' . $business["promotion"]["id"] . ',
type: \'promotion\',
value: $("#field_heart").val()
},
function(data) {
if (data.result) {
//some long code....
}
}
},
"json"
);
from some preliminary testing..
this does NOT seem to be working, (will do more test tomorrow)
$.ajax({
type : 'POST',
//url : 'sessionSetter.php',
data: {
userPicks : userPicks,
},
success : function(data){
//console.log(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
});
It was mentioned that posting to external .php script -or- posting the same page would produce the same results..
no page refresh
$_SESSION would update for future pages
Does anyone have an y example for that?

Refresh Part of Page (div)

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>

Reading contents from a JSON url and writing out those contents

I have a url [https://www.inquicker.com/facility/americas-family-doctors.json] that is a JSON data url. How can I access the contents of this url, and write out the values.
The format contains schedules as an array that inside it contains schedule_id, name, and available_times. I have tried various ways of getting the JSON file, but none have worked.
UPDATE:
Well I have got it this far with this code, and it's laying out what looks like objects from the array. So I believe I got the cross site issue under control. I just need to figure out how to access the data now.
<!DOCTYPE html>
<html>
<head>
<title>JQuery (cross-domain) JSONP</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.getJSON('https://www.inquicker.com/facility/americas-family-doctors.json',
function(data){
alert(data.facility);
$.each(data.schedules, function(i, name){
$('#names').append('<li>' + name.available_times[0] + '</li>');
});
});
});
</script>
</head>
<body>
<ul id="names"></ul>
</body>
</html>
Any help, or suggestions will be greatly appreciated, Thanks.
You cannot generally pass an Ajax request across domains. Normally a server will refuse any Ajax calls that don't come from the same source unless it is explicitly configured otherwise. I am guessing that you aren't calling from the same domain, given that you are using a fully-qualified URL. If you own the server, you will have to configure it to accept such calls from your other domain.
If this is not the case, launch the script in Firefox with Firebug running and look at the console output and tell me what error you get if any.
Once you manage to pass the JSON from your server back to the page, you will retrieve it in your JavaScript as a string. You then need to execute this function:
var jsonObject = JSON.parse(jsonString);
where jsonString is the string that you received from your server. jsonObject becomes an object representation of the JSON passed back to the answer that you can access using dot notation.
Try something like :
alert(json.facility);
There is no title json object in the url you have mentioned.
The JSON is already parsed when it comes to your function.
$.get('https://www.inquicker.com/facility/americas-family-doctors.json', function(result){
alert(result.facility); //Do whatever you want here
// result.schedules array is also ready
});

how to send a single element from browser to server without reload

How can I send just one element from browser to server fast and without reloading browser page?
Is there an AJAX way to do this, that is a NON-FILE method? The opposite of ".load"?
.load works great sending a single element from server to browser without page reload.
How to do the opposite direction?
Browser is JavaScript.
Server is vxworks with windmarks.
PRESENT METHOD THAT WORKS BUT RELOADS PAGE:
Presently, the browser element is and I use submit to send it to the server, but this takes too long and reloads the browser page.
The element's innerHTML contains data formatted as a vxworks WINDMARK.
(When the vxworks server receives this submission, it reads the windmark and copies it to a 'C' string for backend software to process.)
If you're using jQuery and PHP then something like this should work:
JS:
$.ajax('doServerSuff.php?action1=saveLog', function() {
// do stuff after server received the data
});
PHP (doServerStuff.php):
<?php
if ($_GET['action1'] == 'saveLog') {
//do stuff
}
?>
You can get and send data using jQuery. using something like this:
$.post('urlfromserver',browserdata,function(datafromserver){
//do stuff
})
if you let me put a little bit more, it's a good idea to use JSON to send/receive data to/from server. Having that in mind, you can do something like:
$.post('urlfromserver',{browserdata: JSON.stringify(browserdata)},function(datafromserver){
javascriptObject = jQuery.parseJSON(datafromserver)
//do stuff
})
And in your PHP code, it would be as simple as using json_encode to send data to javascript and json_decode to receive data from javascript
UPDATE
Obtaining the data in the server should be as simple as requesting the object via post or get depending on your send method, and parsing the JSON.
In PHP, this is an example of obtaining data using the above code:
$dataFromBrowser = json_decode($_POST['browserdata'])
Use $.post in jQuery to send the data.
The load intruction can also be used to transmit data to the server:
$().load("url", {limit: 25}, function(){
//transmission finished
});
In this example the parameter limit with the value 25 wil be transmitted to the server.
Taken from:http://api.jquery.com/load/
You can simply do with the ajax call like this
$.ajax({
type: "POST",
url: "yourpage.php?id=someValue",
success:function(data){
//do some stuff here
});
I got it working. Here is the corrected JavaScript, from the above answer.
Here is how to change a single element at the server.
This is also an example of how to write to a vxworks windmark string at a vxworks web server, without reloading the page.
NOTE: no URL is specified, so that the same page is used.
$.ajax({
type: "POST",
url: "?general_page_to_MM_data_1_windmark=CCCCCCCCCCCCCC",
success:function(data_from_server){
}});

Categories

Resources