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>
Related
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
I'm working on a standalone application and I'm trying to pass a string which is an output of change event, to the spring controller using the code below
HTML CODE
<!DOCTYPE HTML>
<html xmnls:th="http://www.thymeleaf.org">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<title>ADD NEW BILL</title>
<!-- jquery -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
$("#Mandy_Name").autocomplete({
source: "autocomplete",
minLength: 3
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#Mandy_Name").change(function(){
var changed = $(this).val();
console.log(changed);
$.ajax({
type : "POST",
dataType : 'json',
url : "mandyname",
data: {name:changed},
success: function(data) {
console.log(data);
return false;
}
});
});
});
</script>
</head>
<body>
<div class="container">
<hr>
<p class="h4 mb-4">SAVE NEW PURCHASE BILL</p>
<form action="#" th:action="#{/savePurchase}"
th:object="${purchase}" method="post">
<!-- add a hidden field to handle update -->
<!-- <input type="hidden" th:field="*{idPurchaseDetails}"> -->
<input type="hidden" th:field="*{ID}">
MANDY NAME : <input id="Mandy_Name" type="text" th:field="*{mandyName}"
class="form-control mb-4 col-4" placeholder="Mandy Name">
GSTIN : <input type="text" th:field="*{gstin}"
class="form-control mb-4 col-4" value = gst() placeholder="GSTIN">
<button type="submit" class="btn btn-info col-2">SAVE</button>
</form>
<br><br>
<a th:href="#{/purchaselist}">BACK TO PURCHASE LIST</a>
</div>
</body>
</html>
controller code
#RequestMapping(value = "mandyName", method = RequestMethod.POST)
public ModelAndView getSearchResultViaAjax(#RequestBody Purchase purchase, HttpServletRequest request,
HttpServletResponse response)
{
ModelAndView mv = new ModelAndView();
String name = purchase.getMandyName();
System.out.println(name);
return mv;
}
I'm getting an error "Failed to load resource: the server responded with a status of 404 ()" in the browser console.
Help me to pass the string "changed" to the controller.
I'm using these dependencies
jquery from "org.webjars" ,
spring-boot-starter-actuator ,
spring-boot-starter-data-jpa ,
spring-boot-starter-web ,
spring-boot-starter-data-rest ,
spring-boot-starter-thymeleaf ,
spring-boot-devtools ,
spring-boot-starter-json ,
mysql-connector-java ,
spring-boot-starter-test ,
junit-vintage-engine ,
spring-boot-maven-plugin
Should I be using any other dependencies ??
The HTTP Status 404 means that the URL provided, cannot be found on the server.
I see that you make the Ajax call with an incorrect URL. Change it to the correct one depending on your Spring App and port.
Normally it should be under: http://localhost:8080/mandyName. But this you have to check and examine.
Sample JS code:
$(document).ready(function(){
$("#Mandy_Name").change(function(){
var changed = $(this).val();
console.log(changed);
$.ajax({
type : "POST",
dataType : 'json',
url : "http://localhost:8080/mandyName", // ~~ HERE ~~
data: {name:changed},
success: function(data) {
console.log(data);
return false;
}
});
});
});
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);
?>
I am trying to send this array from javascript to PHP, but I keep getting Undefined index: list in on line 3. This error is coming from in the php file.
I am going to provide to whole code including the html, javascript, and php.
Here is the HTML code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type= "text/javascript" src = "js.js"></script>
</head>
<body>
<form class = "wall" action="phpf.php" method="post">
<label>What is your name</label>
<input type="text" name ="name" />
<input type = "submit" value = "Submit Order" />
</form>
</body>
Here is the Javascript code
$(document).ready(function () {
var list = [34, 56, 23, 90, 43, 58];
$.ajax({
type: "POST",
url: "phpf.php",
data: {'list': JSON.stringify(list)},
cache: false,
success: function (response) {
console.log("This is the list", list);
}
});
})
Here is where I am receiving it in PHP
<?php
$list = json_decode($_POST['list']);
echo "This is the new list".$list;
?>
I was hooping that someone could me please.
You can't print an array using echo, you should use print or var_dump in your php file:
<?php
$list = json_decode($_POST['list']);
echo "This is the new list";
print_r($list);
i've verified and it's working, i just add jquery, i suppose you are loading the file in js.js. But i put my code right here:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type= "text/javascript" src = "https://code.jquery.com/jquery-2.2.4.js"></script>
</head>
<body>
<form class = "wall" action="phpf.php" method="post">
<label>What is your name</label>
<input type="text" name ="name" />
<input type = "submit" value = "Submit Order" />
</form>
</body>
<script>
$(document).ready(function() {
var list = [34, 56, 23, 90, 43, 58];
$.ajax({
type: "POST",
url: "phpf.php",
data: {'list': JSON.stringify(list)},
cache: false,
success: function (response) {
console.log("This is the list", list);
}
});
});
</script>
</html>
Let's say I submit a form with anything in the value of user_input like "I am free." I submit it through AJAX and it gets returned to me as a string. Ok now it's an Object... how would I turn that into a string?
Thank you,
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<title>Sin tÃtulo 3</title>
</head>
<body>
<div id="result_target" style="display:none;"></div>
<form id="form_to_post" action="#" method="post">
<input type="hidden" name="url" value="example.php" />
<input type="text" name="user_input" />
<input type="submit" value="Submit" />
</form>
<script>
$(document).ready(function() {
$("#form_to_post").submit(function() {
var hiddenURL = $("input[name=url]");
var userInputForm = $("input[name=user_input]");
//var dataString = "userInput="+inputForm;
$.ajax({
type: "POST",
url: hiddenURL;
data: {userInput: userInputForm},
success: function(return_contents) {
//returns jquery object...
var output =//
$("#result_target").html(output);
}
});
});
});
</script>
</body>
</html>
use val() to get values from inputs
data: {userInput: userInputForm.val()},