I'm building a dashboard with multiple eventlisteners and AJAX, which transfers data back and forth to a Python backend. It works fine the first time. The 2nd time I click the eventlistener function, I get two responses... the third time 3... I can reset it by reloading the page. So I assume that somehow each time the AJAX comes back the eventlistener registers again. I've done a bunch of searching and can't find a similar problem. Here's the javascript code (including the google map api that I'm passing back to the server).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link href="../static/css/bootstrap.css" rel="stylesheet">
<link href="../static/css/drunken-parrot.css" rel="stylesheet" type="text/css">
<link href="../static/css/jquery.ui.core.min.css" rel="stylesheet" type="text/css">
</head>
<div id="leftCol" class="bodyx">
<form role="form">
<placebutton class="btn btn-lg btn-primary btn-block" type="button" id="placebutton">Save</placebutton>
</form>
</div>
<script type="text/javascript">
function sendplace() {
$('placebutton').click(function() {
pete = ({"firstName":"John"});
console.log("Test");
$.ajax({
url: '/new_place2',
data: (pete),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function(response) {
console.log(response);
},
});
});
};
var placebutton = document.querySelector("placebutton");
placebutton.addEventListener("click", sendplace, false);
console.log("addEvent");
</script>
</body>
</html>
I've whittled the file down thinking there might be some interference - I can't find anything - the entire file is here. It still has the two problems - 1 - first click doesn't do anything, and 2 - it sends one more loop every time. Hopefully this is easier to see... Thanks again.
I can't really see the context, but clearly, you're attaching the listener each time ajax is done. Try replacing this:
placebutton.addEventListener("click", sendplace, false);
with this
placebutton.removeEventListener("click",sendplace);
placebutton.addEventListener("click", sendplace, false);
Mind you that this is not a very clean way to fix it. You should really figure out why placebutton.addEventListener is executed many times (or maybe it's added somewhere else in the code?).
Thanks to #MikeMcCaughan for making it clear - I had a jQuery function wrapped inside of an addEventListener function.
Here's how this looks (working):
function sendplace() {
var add1 = place;
console.log(place);
$.ajax({
url: '/new_place2',
data: JSON.stringify(place),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function(response) {
window.alert("Saved!");
console.log(response);
},
error: function(error) {
console.log(error);
}
});
};
And the code that calls the function:
var placebutton = document.querySelector("placebutton");
placebutton.addEventListener("click", sendplace, false);
Related
I have a web page that's showing a "ressource" (aka just one entry from a mongodb collection), and on that web page I want to have a button "delete" that will send a "delete" request to the server to the correct route.
The router works (so when I use an external program to send a delete request, the entry is deleted), but I want to the same with a link.
Apparently, after doing some research, I would need to use an ajax function to do that, as in this post. The problem is that I can't make it work (probably because I just started using jquery), it seems nothing happens when I click on the button. But if I try a simple alert(), it works ('#delete').on('click',function(){ alert('clicked')}); .
So
Here's the basic html :
$('#delete').on('click', function() {
alert('click');
//here would be the code to send the DELETE request ?
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Storystrap Template</title>
<meta name="generator" content="Bootply" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- bower:css -->
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css" />
<!--endbower-->
<!-- bower:js -->
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/printplugin.min.js"></script>
<!--inject:js-->
<script src="/js/app.js"></script>
<script src="/js/modernizr-custom-touch.js"></script>
</head>
<body>
<button class="delete" data-target="/" data-method="DELETE" data-disabled="true">Delete Ressource</button>
</body>
</html>
And here is the route code in node.js (this code works if I manually send a DELETE request), the id is supposed to be in the link of the page
ressourcesRouter.route('/ressources/t/:ressourcesId')
// permet d'afficher UNE ressource spécifique
.get(function(req,res){
var returnRessource = req.ressource.toJSON();
res.render('ressourceView', {
title: 'Ressources',
ressource: returnRessource
});
})
.delete(function(req,res){
req.ressource.remove(function(err){
if(err)
res.status(500).send(err);
else{
res.status(204).send('Removed');
console.log('ressource supprimée');
}
});
});
Could you help me out to figure the ajax code needed ? or is there another way ?
Don't hesitate to ask for more code if needed, I'll be as reactive as possible to answer you quickly.
Best regards.
Take a look at the jQuery ajax docs: http://api.jquery.com/jquery.ajax/
$.ajax({
url: '/ressources/t/123',
method: 'DELETE',
data: yourdata
})
.done(function( data ) {
console.log(data);
});
<script type="text/javascript">
$(document).ready(function(){
$('table#delTable td a.delete_link').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: '../scripts/delete_link.php',
data: 'link=' + $(this).attr('data_link') + '&topic_pk=' + $(this).attr('data_topic') + '&topic_introduction=' + $(this).attr('data_introduction'),
cache: false,
success: function()
{
parent.fadeOut('fast', function() {$(this).remove();});
}
});
}
});
});
</script> just look at this. it can solution your problem. Dont Forget your datatable's name
I am trying to retrieve data from an api and use it to populate the div with the ID "output". I get an error that the $ is undefined. Can anyone help determine what I am missing?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<meta name="Content-Style-Type" content="text/css">
</head>
<body style="margin: 0px; padding: 0px;">
<div id="fullscreen">
<div id="output">
</div>
</div>
</body>
<script>
$.ajax({
type: 'GET',
url: "https://apiurl.com",
dataType: "json",
crossDomain: true,
success: function( response ) {
console.log( response ); // server response
var id = response[0];
var vname = response[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
</script>
</html>
As Sirko already explained in the comments, you are trying to use the javascript library JQuery, but the library is not available because you didn't include it.
You can include it by either downloading JQuery here and including it via
<script src="src_to_local_jquery.js"/>
or by including it externally (described in CDN section of above link)
Also note, that script tags should be put either in the head or the body section. To make sure your custom script is executed after the page is ready, you can use JQuery's document ready method.
The $ sign is not part of the JavaScript language, it is a short hand for a third party library jQuery ($ === jQuery).
You need to add it as a dependency in your html file with a script tag with a src attribute containing the URI for the source file before you can use it.
<html>
<head></head>
<body>
...
...
<script src="//code.jquery.com/jquery-3.1.1.js"></script>
<script>
$(function () {
// Your code here
});
</script>
</body>
</html>
Include jQuery either as a CDN or download add reference locally. Then make sure the DOM is ready before you make the call. You can read more about that here
<script src="local_jquery.js"/>
// OR
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
$(function() {
$.ajax({
type: 'GET',
url: "https://apiurl.com",
dataType: "json",
crossDomain: true,
success: function( response ) {
console.log( response ); // server response
var id = response[0];
var vname = response[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});
I have a problem with jQuery ajax function:
var arrayIdEq = JSON.stringify(iditem);
$.ajax({
type: "POST",
url: "index.php",
dataType : 'text',
contentType: 'application/json; charset=utf-8',
data: {
arrayIdEq : arrayIdEq
},
success: function(answer) {
alert(answer);
},
complete: function() {
},
error: function(jqXHR, errorText, errorThrown) {
alert(jqXHR+" - "+errorText+" - "+errorThrown);
}
});
"arrayIdEq" contains number from 0 to 7, or string "EMPTY".
PHP code:
elseif(isset($_POST['arrayIdEq'])){
$answer = "my_answer";
return $answer;
After request, when success response come, alert show up... but here's the problem. Instead of "$answer" value, alert contains... HTML code from my main page!
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> Medivia</title>
</head>
<body>
<h1>Medivia</h1>
<form action="index.php" method="POST">
<label>E-mail:<br><input type="text" name="mail" required></label>
<br>
<label>Hasło:<br><input type="password" name="pass" required></label>
<br>
<button name="login">Zaloguj się</button>
</form>
</body>
</html>
I have no idea what happend here. Could anybody explain to me what happend there? What did i do wrong?
Your answer variable in the success function will contain the complete output of your php script.
So when you call index.php and you do:
elseif(isset($_POST['arrayIdEq'])){
$answer = "my_answer";
return $answer;
}
The script will only exit if the return statement is called from the main script (not from within a function) but the output will be the output generated by the script until that point.
Your script should output - and not return - only what you want returned to the javascript.
Probably a separate script for ajax requests will be a more convenient solution than using the index.php file you use to build the complete page.
Today I have a question that may seem kinda simple the the rest of you. I'm just now learning how to use APIs/JSONs and I'm a little confused. I'm trying to simply grab the temperature from this openweathermap.org API response and displaying it in an html tag.
The javascript from what I know is grabbing the temperature and setting it as a var. I'm confused why I cannot use id="" to set text inside a tag. The code below is what I have so far. I thank you for your time.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
var weather;
var temp;
$(document).ready(function() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
dataType: 'jsonp',
success: function(weather){
var temp = weather.main.temp;
}
});
</script>
</head>
<body>
<p id="temp"></p>
</body>
</html>
#ArunPJohny have already identified the errors: 1) missing }) and 2) use $('#temp') to get the HTML element. Also you don't need to declare weather because it is declared as an argument.
$(document).ready(function() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44db6a862fba0b067b1930da0d769e98&units=metric",
dataType: 'jsonp',
success: function(weather) {
$('#temp').text(weather.main.temp);
}
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<p id="temp"></p>
I want to create a code that reloads a part of the page every 10 seconds and if it fails to reload (because of connection issue), then it plays a sound.
Is such thing possible using ajax and how? I have seen this type of feature in web chats before but never came across a code for it.
Try using setInterval function:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<title>Test</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" type="text/css">
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript" language="JavaScript"></script>
<style type="text/css">
<!--
.square {
background-color: #AAAAAA;
width: 250px;
height: 100px;
}
//-->
</style>
<script type="text/javascript" language="JavaScript">
$(document).on('ready',function(){
setInterval(updateDiv,10000);
});
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
//Code to play a sound
$('.square').html('<span style="color:red">Connection problems</span>');
}
});
}
</script>
</head>
<body>
<h1>The next div will be updated every 10 seconds</h1>
<div class="square">
Hello
</div>
</body>
</html>
And the php script:
<?php
echo "Updated value --> " . rand();
?>
To test, try renaming the php script (simulating connection problems) and rename to original name (getContent.php) to test correct situation again. Hope this helps.
Using JQuery, you can add handlers to run on fail...
$.ajax({
dataType: "json",
url: "myurl.com"
}).done(function( data ) {
//do what you want when it's all good
}).fail(function() {
//do what you want when the call fails
});
Or you can do it this way...
$.ajax({
type: "post",
url: "/SomeController/SomeAction",
success: function (data, text) {
//do what you want when it's all good
},
error: function (request, status, error) {
//do what you want when the call fails
}
});
And per request, here is a jsfiddle, it calls a service every 2 seconds, either with a URL that will return the date, or with a bad URL that will fail, mimicking a failed server.
UPDATE: I modified the jsfiddle to play a sound, as long as that sound remains on the server it's on :)