Jquery too many ajax requests fired - javascript

Why does this code send exactly two requests for each slider change?
I have server application on flask python, and i am using ajax from JQuery to send request to my endpoint, which returns new html plot code. Flask server always getting two request per slider change. How i can to fix it, that it would send one request?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="../static/style.css" rel="stylesheet" type="text/css">
<title>plot</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type='text/javascript'>
$(function () {
var form = $('form');
$('#myRange').on('change mouseup', function () {
$.ajax({
type: "POST",
url: "/update_view",
data: form.serialize(),
}).done(function (res) {
$("#plot").html(res)
});
});
});
</script>
</head>
<body>
<div id="body_page">
<form>
<p>Default range slider:</p>
<input type="range" min="1" max="100" value="50" id="myRange" name="slider">
</form>
<div id="plot">
{{ html_plot|safe }}
</div>
</div>
</body>
</html>

because you are subscribed to two events change mouseup.
$(function () {
var form = $('form');
$('#myRange').on('change mouseup', function (e) {
console.log(e.type); // return TWO events
/* $.ajax({
type: "POST",
url: "/update_view",
data: form.serialize(),
}).done(function (res) {
$("#plot").html(res)
}); */
});
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<form>
<p>Default range slider:</p>
<input type="range" min="1" max="100" value="50" id="myRange" name="slider">
</form>
In this case, you can only leave change

Related

trying to use a script variable in html

I am trying to set the default value of an input in html with one that I get in the json from my ajax update function. The value is getting back from the ajax correctly, but I am having a devil of a time using it in the html.
I have created a "namespace" to contain my variables. How do I use the variables in my html? Note that ".innerHTML" and ".value" don't work because (I'm guessing) this is an input with min, max, step? If I replace {{ myNamespace.low_pump_speed_value }} with an acceptable number (between 800 and 1500), the code works as expected.
I am getting the following error:
jinja2.exceptions.UndefinedError: 'myNamespace' is undefined
Here is the html file:
<body>
<script>
myNamespace = { low_pump_speed_value: 850,
high_pump_speed_value: 950,
chlorine_percent_value: 1050};
document.write(myNamespace)
console.log("second", myNamespace)
</script>
<label for="low-pump-speed-id">Low Pump Speed:</label>
<input type="number" id="low-pump-speed-id" name="low-pump-speed-id" step="50" min="800" max="1500" required value="{{ myNamespace.low_pump_speed_value }}">
</body>
<script type="text/javascript">
setInterval(function(){$.ajax({
url: '/update',
type: 'POST',
success: function(response) {
myNamespace.low_pump_speed_value = response["pump"]['low-speed'];
},
error: function(error) {
console.log(error);
}
})}, 250);
</script>
You should use values within the max..min range, for example:
myNamespace = { low_pump_speed_value: 900,
Then, you can assign this value to the input field as follows:
var inputField = document.getElementById("low-pump-speed-id");
inputField.value = myNamespace.low_pump_speed_value;
Thanks (bedankt) to www.admiraalit.nl, this is now working:
I have to believe that it was something stoopid I was doing as I thought I started out this way and just wound up in the weeds.
<!DOCTYPE html>
<form class="form-inline" method="POST" action="{{ url_for('override_select') }}">
<link rel="shortcut icon" href={{ url_for('static',filename='favicon.png') }} />
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='css/root.css') }}">
</head>
<body>
<label for="low-pump-speed-id">Low Pump Speed:</label>
<input type="number" id="low-pump-speed-id" name="low-pump-speed-id" step="50" min="800" max="1500">
<label for="high-pump-speed-id">High Pump Speed:</label>
<input type="number" id="high-pump-speed-id" name="high-pump-speed-id" step="50" min="800" max="1500">
<label for="chlorine-percent-id">Chlorine Percent:</label>
<input type="number" id="chlorine-percent-id" name="chlorine-percent-id" step="50" min="800" max="1500">
</body>
<script type="text/javascript">
setInterval(function(){$.ajax({
url: '/update',
type: 'POST',
success: function(response) {
document.getElementById("low-pump-speed-id").value = response["pump"]['low-speed'];
document.getElementById("high-pump-speed-id").value =response["pump"]['high-speed'];
document.getElementById("chlorine-percent-id").value = response["chlorinator"]['chlorine-percent'];
},
error: function(error) {
console.log(error);
}
})}, 2000);
</script>
</form>

JavaScript Function to Post clicking checkbox keeps multiplying

This code its working okay but every time that I click on the checkbox it sends 1 post, then 2 posts, then 4 posts, then 8 posts etc.. to "insert.php". How can I prevent this error?
$(document).ready(function() {
$('#submiter').click(function() {
$("input:checkbox").change(function() {
if ($(this).is(":checked")) {
console.log('checked ' + $(this).val());
$.ajax({
url: "insert.php",
method: "POST",
data: {
test1: $(this).val()
},
success: function(data) {
$('#result').html(data);
}
});
}
});
});
});
<html>
<head>
<title>Ajax Jquery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<input type="checkbox" value="PHP" id="submiter" />PHP <br />
<div id="result"></div>
</body>
</html>
Initially you have 1 handler for your input, an onclick handler.
When clicked, it adds an onchange listener to same element, from now on, you have 2 listeners for your input.
The next click, it adds one more onchange listener, and so on...
Do you really need an onclick listener? Maybe just the onchange isn't sufficient? See below code (I removed ajax part to avoid requests in this example)
$(document).ready(function() {
$("#submiter").change(function() {
if ($(this).is(":checked")) {
console.log('checked ' + $(this).val());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<input type="checkbox" value="PHP" id="submiter" />PHP <br />
<div id="result"></div>

why when i reload a page using AJAX the data disappears

Basically i find code on the internet to test and use it.
the problem is that when i reload the page, the data disappears.
what i want to happen is for the data or the value to just stay.
Thanks guys
Here is the code in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" class="btn btn-success" onclick="passData();" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function passData() {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function(data) {
$("#message").html(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
</script>
</html>
and here is my php code
<?php
$pass=$_POST['pass'];
echo json_encode($pass);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" id="success" class="btn btn-success" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$("#success").click(function () {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function (data) {
$("#message").html(data);
localStorage.setItem("data",data);
},
error: function (err) {
alert(err);
}
});
}
return false;
})
$(document).ready(function () {
var someVarName = localStorage.getItem("data");
console.log(someVarName)
$("#message").html(someVarName);
});
</script>
</html>
First of all i changed your js code to use more jquery syntax, as you already have included it (i trigger the on click event on the script and i don't put it in in html). After that in order not to lose your variable after refresh on ajax success i pass the value of data to localstorage, and after refresh (on document ready) i retrieve it and display it in the label.
Of course every time you put a new value and display it, it over-writes the previous one, so after refresh you display the latest value put in your input field.
I am not sure I understand what you mean but...
Before this line:
<!DOCTYPE html>
enter
<?php session_start(); ?>
In this line add
<input type="text" id="pass_data" class=" form-control" value="<?php echo $_SESSION['VAL']; ?>">
and in your php file:
<?php session_start();
$pass=$_POST['pass'];
$_SESSION['VAL'] = $pass;
echo json_encode($pass);
?>

Chat not closing and not showing response

I made a qnamaker service and build a chat to show the response of the question.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Chat</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Droid+Sans:400,700">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="chat.js"></script>
<script src="rispostachat.js"></script>
<link rel="stylesheet" href="chat.css">
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<div id="live-chat">
<header class="clearfix">
x
<h4>Bot</h4>
</header>
<div class="chat">
<h3>Risposta:</h3>
<div id="answer"></div>
<input type="text" id="question" name="question">
<button type="button" class="button" id="post-btn"> Chiedi</button>
</br>
</body>
</html>
This is for close and show the chat box
(function() {
$('#live-chat header').on('click', function() {
$('.chat').slideToggle(300, 'swing');
});
$('.chat-close').on('click', function(e) {
e.preventDefault();
$('#live-chat').fadeOut(300);
});
}) ();
And this is for take the response inserted and show the response to the user
$("#post-btn").click(function(){
jQuery.ajax ({
url: "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/idknowledgebasetoinsert/generateAnswer",
type: "POST",
data: '{"question" : "'+$("#question").val()+'"}',
dataType: "json",
contentType : "application/json",
headers: {"Ocp-Apim-Subscription-Key": "subscriptionkeytoinsert"},
success: function(msg, status, jqXHR){
$('#answer').html(msg.answers[0].answer);
}
});
});
When i click on the header of the chat , the chat not close and the chat not disappear when i clcik on the close button x of the chat.
When i click on Chiedi to send the answer nothing happen. I don't see the response of the service in the chat.
it looks like you have included the jQuery twice (2 different versions) in your header
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="jquery-3.3.1.min.js"></script>

How to filter xml data according to the search?

<pages>
<link>
<title>HTML a tag</title>
<url>http://www.w3schools.com/tags/tag_a.asp</url>
</link>
<link>
<title>HTML br tag</title>
<url>http://www.w3schools.com/tags/tag_br.asp</url>
</link>
<link>
<title>CSS background Property</title>
<url>http://www.w3schools.com/cssref/css3_pr_background.asp</url>
</link>
<link>
<title>CSS border Property</title>
<url>http://www.w3schools.com/cssref/pr_border.asp</url>
</link>
<link>
<title>JavaScript Date Object</title>
<url>http://www.w3schools.com/jsref/jsref_obj_date.asp</url>
</link>
<link>
<title>JavaScript Array Object</title>
<url>http://www.w3schools.com/jsref/jsref_obj_array.asp</url>
</link>
</pages>
this is the sample xml data which i am parsing and getting the output from
SEARCH.HTML
<!DOCTYPE html>
<html>
<head>
<link
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.js"></script>
<script>
$(document).ready(function () {
var myArr = [];
$.ajax({
type: "GET",
url: "http://localhost/category/links.xml",
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function (data) {
alert("XML File could not be found");
}
});
function parseXml(xml) {
//find every query value
$(xml).find("link").each(function () {
myArr.push($(this).find('title').text());
});
}
function setupAC() {
$("input#searchBox").autocomplete({
source: myArr,
minLength: 3,
select: function (event, ui) {
$("input#searchBox").val(ui.item.value);
$("#searchForm").submit();
}
});
}
});
</script>
</head>
<body style="font-size: 62.5%;">
<form name="search_form" id="searchForm" method="GET" action="http://localhost/search_result1.html">
<label for="searchBox">Keyword Search</label>
<input type="text" id="searchBox" name="searchString" />
<button name="searchKeyword" id="searchKeyword">Sumbit</button>
</form>
</body>
</html>
and this my search bar with auto complete feature. In it i first parse the above xml and then store the title in an array which i can use it for auto completeion feature. and on clicking the submit i redirect the page to another html page where i show all the results.
the code for the second html page is as given below..
RESULT.HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="1.7.2.jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#dvContent").append("<div></div>");
$.ajax({
type: "GET",
url: "http://localhost/category/link.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('link').each(function () {
var stitle = $(this).find('title').text();
var surl = $(this).find('url').text();
$("<li></li>").html(stitle + ", " + surl).appendTo("#dvContent div");
});
},
error: function () {
alert("An error occurred while processing XML file.");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="dvContent">
</div>
</form>
</body>
</html>
but what i want is to show only the title and url of the searched term. In this i am getting the entire xml as output. So in there a way by which i can show only the title and url of the searched term.
that is i get the output in result.html as
. HTML a tag, http://www.w3schools.com/tags/tag_a.asp
. HTML br tag, http://www.w3schools.com/tags/tag_br.asp
on searching for the term HTML in the search in search.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="1.7.2.jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#dvContent").append("<div></div>");
var searchValue = $('#searchBox').val(); // Here you get the search text
$.ajax({
type: "GET",
url: "http://localhost/category/link.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('link').each(function () {
var stitle = $(this).find('title').text();
var surl = $(this).find('url').text();
if (searchValue === stitle) { // Only append those if search text matches with title
$("<li></li>").html(stitle + ", " + surl).appendTo("#dvContent div");
}
});
},
error: function () {
alert("An error occurred while processing XML file.");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="dvContent">
</div>
</form>
</body>
</html>

Categories

Resources