jQuery client for REST webservice with jersey - javascript

I am new in jQuery and I'm trying to develop a client for my web service. I've tried something simple, just for testing, but still it doesn't work, although it seems ok to me.
I have the jQuery library in my tomee/webapp folder, along with my html and javascript files. If I write some non-jQuery code in my javascript file, it works.
I have the following code:
index.html
<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="client.js"></script>
</head>
<body>
<input type="button" id="getAllButton" value="Get all books" onclick="return getAllBooks()"/>
<div id="messageBox"></div>
</body>
</html>
client.js
function getAllBooks() {
$.ajax({
dataType: 'application/xml',
type: 'GET',
url: rootURL + '/books',
success: function (data) {
alert(1);
},
error: function (data) {
alert(2);
}
});
}
The problem is that no alert will appear. If a write pure javascript (I mean without jQuery), alerts will do appear.
Why do alerts not appear? Any advice?
Thank you!
Sorin

Lets try to find out what works and what not; try changing your client.js to:
alert(1);
function getAllBooks() {
alert(2);
window.open(rootURL + '/books');
$.ajax({
dataType: 'application/xml',
type: 'GET',
url: rootURL + '/books',
success: function (data) {
alert(3);
},
error: function (data) {
alert(4);
}
});
}
If you see the alert #1 (when your html page loads) then your client.js path is OK. If you see alert #2 (when you click the button) then at least the function is being called.
Verify if window.open() shows what your web service is supposed to show you (even a error message will guide you throw the right path). And of course, if you see alert #3 or #4 then your problem was mysteriously solved by it self.... it sometimes happens :-)
NOTE: If you know how to use the javascript console of your browser use console.log() instead of alert() for debugging;

Thanks charlietfl for your tips! They helped me solve the problem.
The problem was that it didn't know who rootURL is. I found rootURL in an example and I thought that is something defined in jQuery. It seems it isn't.

Related

how to Invoke api using simple html code?

I have a small requirement that needs to make REST API POST call using HTML code. I have copied the sample code below and some reason this is not working. I am unable to see any call using the below code. Please let me know If there is any change required in the code.
<html>
<head>
<title>My first API script</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<H1>Testing the API call</h1>
<form>
<label for="msg">Message</label>
<button id='submitButton'>Submit</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var API_URL = 'https://example.com/'; // this will be my API like https://example.com
$('#submitButton').on('click', function(){
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringfly({"message": $('#msg'.val())}),
contentType: "application/json",
success: function(data){
location.reload();
}
})
})
</script>
</body>
</html>
Rewrite $('#msg'.val()) to $('#msg').val(), and implement an error(xhr, textStatus, errorThrown) function in .ajax too so you'd catch the error next time.
Several things need to be fixed in your code. Not sure if that's the one you're actually using but:
Change stringfly to stringify.
label doesn't have an id="msg" but you're trying to access it with #msg.
Add a e.preventDefault() on your click callback function. Make sure to receive e as parameter.
label-s don't have a val() function. If you're trying to get the "Message" inside the label, use $('msg').text().
Try using API placeholders like JSONPlaceholder instead of example.com so you don't get CORS errors.
Finally, add an error callback to your AJAX so you can catch and handle errors.

Sending form data to nodejs without reloading page using Ajax

This is my code for sending form data to nodejs using Ajax. I want to achieve this without reloading the page.
I have tried to run this in IE,Firefox and Chrome. There is no output seen, hence I want to know where am I going wrong. I am new to Ajax, please help me!
<html>
<meta charset="UTF-8">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$('#newform').on('submit', function (event) {
//alert('Hi');
event.preventDefault();
var data = {
username: $('#username').val(),
};
$.ajax({
url: 'http://127.0.0.1:8081/upload',
data: data,
method: 'POST'
}).then(function (response) {
$('body').append(response);
}).catch(function (err) {
console.error(err);
});
});
</script>
</head>
<body>
<form action="/upload" method="post" id="newform">
<input type="text" name="username" id="username"></input>
<input type="button" value="submit" id="s1"></input>
</form>
</body>
</html>
I see that you are including version 1.5 of jquery (now 1.11..). It is very old. but running your code i see the following error: TypeError: $(...).on is not a function.
If we go to the documentation of jQuery for the .on method ( http://api.jquery.com/on/ ) we can see that it was included in version 1.7, this means that is not present in the version you included.
My suggestion is to update the library to 1.11.3 (latest) http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js
The code looks ok to me. Ah and when you run the script you should check for the errors in the inspector console in chrome, so you can see what is wrong.

Load Javascript after AJAX-fetched HTML is fully loaded

I have a situation where the HTML part is loaded with AJAX into a DIV with ID="dynamic content" using main.js script. This script is situated inside the HEAD part of main.php and it goes like this:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
}
});
The Javascript file responsible for controlling that content is situated in another JS file named secondary.js. This file is placed just before the closing of BODY again inside main.php.
main.php Document Structure:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
....
<div id="dynamic-content"></div>
....
....
<script type="text/javascript" src="js/secondary.js"></script>
</body>
</html>
Sometimes the content of content.php is too large, and secondary.js file loads before the content is fully loaded. Hence some elements are not targeted and i have problems.
Is there a way for me to delay for 1-2 seconds the execution of secondary.js, just to make sure that the content is fully loaded?
ps: all above files are hosted on the same server
Thanks in advance.
What you're trying to achieve is async behaviour. Whatever secondary.js does, put it inside a function and call it inside the ajax callback. If you do so, you won't even need two JavaScript files.
Don't try to manage this by timeouts or loading order. This will not be failsafe. You cannot know the exact time the browser needs to load your content. For example, what if you are on very slow internet connection? Don't try to predict those things, that's what the callback is for :-)
Your code could look sth like this:
function doSthWithLoadedContent() {
// whatever secondary.js tries to do
}
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
doSthWithLoadedContent();
}
});
You could possibly load the script using $.getScript once the output has been applied to the html tag:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
$.getScript('js/secondary.js');
}
});
https://api.jquery.com/jquery.getscript/
The best way to do this would actually be to hand a callback to the function that does your ajax call. I probably wouldn't put this in html but it demonstrates the method:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
<script lang="javascript>
function doWhenLoaded(someCallback)
{
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
someCallback();
}
});
}
$(document).ready(function(){
doWhenLoaded(function(){
$.getScript('js/secondary.js');
});
})
</script>
</head>
...
</html>
Instead of using $.getScript you could also load in secondary.js with main.js and wrap it in a function call (i.e. doStuff = function() { /* your code here */ }). Then you could call doWhenLoaded(doStuff) in $(document).ready.
You have to add script after ajax call.
$.ajax({
url: 'url of ajax',
type: "POST",
data: data,
dataType: "html",
success: function (data) {
$('#instructions').html('<div>' + data + '</div>');
$.getScript("js/html5lightbox/html5lightbox.js", function() {
$('body').find('.html5lightbox').html5lightbox();
});
}
});

Call a php function in a javascript with params

I need to call a PHP function with params from JavaScript when I click on some text in a html file; yeah, I know, it sounds like $##!$##
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() { /// Wait till page is loaded
$('#detailed').click(function(){
$('#main').load('parse.php?file=gz.xml', function() {
/// can add another function here
});
});
}); //// End of Wait till page is loaded
</script>
<a><div id="detailed">Stuff1</div></a>
<a><div id="detailed">Stuff2</div></a>
<div id="main">Hello - This is my main Div that will be reloaded using jQuery.</div>
What I want to make, is when I click Stuff1 on page, to call function parseLog('Stuff1'), and when I click Stuff2, to call function parseLog('Stuff2').
function parseLog(), is a PHP function, in functions.php
Anybody know a solution?
Thanks!
Javascript is client side script and PHP is server side script. So if you think, you need a call to that function over the network and get the response over the network. you should try using a coding method called AJAX. To make life easier and cross browser compatible use jQuery library and its ajax functionality.
Look at this post for a quick intro to jQuery and AJAX.
It helped me , hope this helps you too.
You should try something like this :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function myFunc (myData) {
$.ajax( {
type: "POST",
url: "parse.php?file=gz.xml",
dataType: 'json',
data: { param: myData},
success: function( result ) {
$("#main").append(result);
}
}
}
Stuff1</div>
Stuff2</div>
<div id="main"></div>

Jquery $.get is unaccesible

I have this mark up and a json.txt file which lies on the same directory as this .im unable to fetch it contents..also im not getting any errors in my firebug
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$.get('/json.txt',
function(data) {
$('div.result').html(data);
});
});
</script>
</head>
<body>
<div class="result"></div>
</body>
</html>
"on the same page" ? Do you mean "in the same directory" ? If so use
$.get('json.txt'
If this doesn't work, I suggest using the long form to see what happens :
$.ajax({
url: 'json.txt',
success: function(data){console.log(data)},
error: function(jqXHR, textStatus, errorThrown) {console.log(jqXHR, textStatus, errorThrown)};
});
So you can see in your console (ctrl+maj+i) the error (or the data).
Another note : this can't work if you're opening the html file in file:// as the json would be considered coming from another domain. You must have an http server and open it in http://.
If you type full path, everything works?
$.get('http://localhost/json.txt', function(data) {
});
I am trying help to detect problem
If file is local (file:///), then look jQuery: read text file from file system

Categories

Resources