Sending form data to nodejs without reloading page using Ajax - javascript

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.

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.

Sample AJAX call not working

Trying to do a simple AJAX call (teaching myself). I have a .txt file in same folder as html. What am I doing wrong here? Thanks.
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#poo").submit(function(e){
e.preventDefault(); //stop submit
$.ajax({
type: "GET",
url: "data.txt",
data: "",
success: function(data){
$("#foo").html(data);
document.getElementById("foo").style.display = 'block';
alert('hey');
}
});
});
});
</script>
</head>
<body>
<form id="poo">
<input type="text"> </input>
<input type="submit"> </input>
</form>
<br>
<br>
<div style='display: none;'>
<p id="foo">this shows</p>
</div>
Start Over
</body>
</head>
</html>
This is a convenience function that loads remote files via AJAX and uses .innerHTML() to load it into any elements in your jQuery selector.
// Does the exact same thing as the entire block of code you wrote..
// These jQuery methods are chainable so you can do this in 1 statement.
$("#foo") // Contains the DOM reference,
// so no need to use getElementById().
.load("data.txt") // Loads "data.txt" into "#foo".
.show(); // Makes "#foo" visible.
Relevant:
jQuery selectors and method chaining
jQuery load() method
jQuery show() method.
Per your comments, you had some other issues.
You said you weren't sure if jQuery was loaded. jQuery is just javascript, so you include it in <script></script> tags. The easiest way is to use jQuery's CDN. Click on the link, then choose the version and format you want. There will be a pop-up containing the script tag, just copy it into the page, preferably before any other Javascript you have on the page. If you're not sure which version/format to use, v1.x, minified is the way to go.
You mentioned that you were running it locally. The problem is, Javascript isn't supposed to have direct access to your filesystem. It will attempt to request the file over the http protocol, without having server software you can only request files over the file:// protocol.
There are zillions of topics on this all over the internet, but to solve it you should install a server. XAMPP is a good one and it's cross platform. Download that and your application will work in all your browsers. It will work in your browsers when you upload it to a server as well
try to add the dataType: "text"
$.ajax({
type: "GET",
url: "data.txt",
dataType: "text",
success: function(data){
$("#foo").html(data);
document.getElementById("foo").style.display = 'block';
alert('hey');
})

Bing Image Archive Ajax Error

I have made an Ajax call to Bing to get its daily image, however i get an error in the console:
this is the full code its on a localhost using wamp
index.php
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
$.ajax({
url : "http://bing.com/HPImageArchive.aspx?format=js&idx=0&n=1",
dataType:"jsonp",
});
function mycallback(data)
{
$('#output').html(data.images[0].url);
}
</script>
I think you should study the documention for jquery ajax call.
<head>
<script src="jquery.min.js"></script>
</head>
<body>
<div id="output"></div>
</body>
<script type="text/javascript">
(function() {
var bingImagesUrl = "http://bing.com/HPImageArchive.aspx";
$.getJSON( bingImagesUrl, {
idx:0,
n:1,
format: "js"
}).done(function( data ) {
$('#output').html(data.images[0].url);
});
})();
</script>
#Below_the_Radar: your answer does not really help as OP is likely getting the same error even if he makes the Ajax call correctly.
According to Is there a way to get Bing's photo of the day?, it seems that Bing.com only supports XML, JSON, and RSS. I guess OP want to make the call with dataType: "jsonp" probably because he would like to bypass the browsers same-origin policy.
This can be solved client-side in browser by using a Chrome extension, but I guess that is not OP's use case. I bet OP is trying to get a picture from Bing's archive and thus use it in his own website. If that is the case, it has no solution as we need to have "Access-Control-Allow-Origin": "*" in the response's headers returned by Bing, which we do not have control.
I suggest considering an alternative. Try this: https://source.unsplash.com/

Very simple ajax request not working

I'm making a web app. I run this function with jquery 1.11.2 in index.html:
$.ajax("http://localhost/index.html")
.done(function () {
console.log("success");
})
.fail(function () {
console.log("fail");
});
It works fine. I try it with another file:
$.ajax("http://localhost/online.html")
.done(function () {
console.log("success");
})
.fail(function () {
console.log("fail");
});
I have this error message:
GET http://localhost/online.html net::ERR_FAILED
online.html is in the same folder, it contains:
<!DOCTYPE html>
<html>
<head lang="en">
<title>Picture Viewer</title>
</head>
<body>
</body>
</html>
Why it doesn't work ?
Thanks.
I'm using a manifest.mf to build a web app which work even if device hasn't access to internet.
If I add online.html in manifest.mf it works, I don't understand why. Now idk how to check if the browser is online or offline, the request will always success with this method.
So I found answer to my original question, thanks for help.
Edit: Still work if I put online.html in NETWORK list in manifest.mf, but it looks like the browser still store it in cache.
Edit 2: Finally working fine if I request a .php page instead of requesting .html contents.

jQuery client for REST webservice with jersey

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.

Categories

Resources