I've checked dozens of similar topics already answered and I simply can't get around the issue I have.
I am using a bootstrap date time picker (https://eonasdan.github.io/bootstrap-datetimepicker) and my goal is to pass the displayed value from a page that holds the calendar (calendar.php) to a PHP file (data.php) whenever the date is changed.
Below I added the code. Since I have some files locally stored, I added some info from Chrome's dev tools.
The date picker is working fine and I can get the value with Javascript.
The issue is that nothing is passed to PHP.
Checked the syntax..everything seems fine for me at this point.
I don't know what I'm doing wrong. Any advice would be more than welcomed !
calendar.php :
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript" src="moment.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="bootstrap-datetimepicker.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1' >
<input type='text' id='date' name='date' class="form-control" >
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(function () {
// Formatting how date is displayed
$('#datetimepicker1').datetimepicker({
calendarWeeks: true,
format: "YYYY MM DD"
});
//Displaying the current date in the text box when the page is accessed
$('#datetimepicker1').data("DateTimePicker").date(new Date());
// Sending the date to PHP when the user is changing it
//dp.change is an event fired when date is changed
$('#datetimepicker1').on("dp.change",function(){
var day = $('#date').val();
$.ajax({
type: "POST",
url: "data.php",
data: { day : day } })
.done(function() { alert(day); })
.fail(function() { alert("error"); })
});
})
})
</script>
</div>
</div>
</body>
</html>
When I execute the code, it alerts me with the day ( it goes to .done(function() { alert(day); }) ) and in my current understanding, the post was a success or at least that's how I interpret it.
This is from Chrome's dev tool.
I am trying to show that the value is retrieved. No other errors appear.
// Sending the date to PHP when the user is changing it
$('#datetimepicker1').on("dp.change",function(){
var day = $('#date').val(); // Date gets retrieved : day = "2016 08 03"
$.ajax({
type: "POST",
url: "data.php",
data: { day : day } }) // Date gets retrived: day = "2016 08 03"
.done(function() { alert(day); }) // I get a pop-up with the date
.fail(function() { alert("error"); })
});
})
})
The file with Javascript code and the file with PHP code are in the same folder.
PHP (data.php) code is below :
<?php
if(isset($_POST['day']))
{
$day = $_POST['day'];
echo $day;
}
?>
I simply can't figure what am I doing wrong or missing in the code above.
Edit :
I think I didn't focused well on the issue I am having and I am sorry for that. All your suggestions ( thanks a lot for them) are about the .done(function).
My issue is that my php file (data.php) is empty. The date isn't passed by the Ajax and I don't know why. The post doesn't happen.
I tried all the suggestions u guys mentioned, thinking that they may be the answer but no luck.
The PHP is outputting the value. The web server is sending the value to the browser. The browser is giving that value to JavaScript. jQuery is processes that value. Then you ignore it.
It is passed as the first argument to the function you pass to done, use it.
.done(function(data_in_response) { alert(data_in_response); })
You should put the same variable inside the ajax response function to print on response, i.e.,
.done(function(data){
alert(data);
})
Related
I have an HTMLForm which on click forward me to new HTML page i have Two JS files for each HTML
What i am doing and trying to achieve is :-
On 1st HTML when i click search button i am storing the values of input field and select field in different variables
What I am trying to achieve is when on search new page loaded I want to use that new variable into my new JavaScript
I have Two HTML files also
here is the code of my file1.html
<form id="formId" action="file2.html">
<div class="container">
<h4>Date:</h4>
<input type="text" id="startdate" name="fromdate" width="276"
placeholder="dd/mm/yyyy" required />
<h4>Outlets:</h4>
<select name="outlet" id="myselect">
<option>ALL</option>
</select>
<div>
<br>
<button id="btn-search" class="btn btn-default" type="submit">
<i class="fa fa-search"></i> Search
</button>
</div>
</div>
</form>
<script type="text/javascript" src="JS/JavaScript1.js"></script>
In This HTML i have a form having one date field and one select field
On clicking submit Button I am Storing the values of date and Outlet into a variable in my JavaScript file which is JavaScript1
**Here is my JavaScript1 file **
$(document).ready(function() {
$("#btn-search").click(function(){
var currentlyClickedOutletform = $("#myselect").find(":selected")[0].textContent;
var currentlyClickedStartdateform= $("#startdate").val();
$.ajax({
url : "LinkReportMain",
method : "POST",
data : {
Outletlink : currentlyClickedOutletform,
Fromdatelink : currentlyClickedStartdateform,
},
});
});
});
var currentlyClickedOutletform and var currentlyClickedStartdateform are the two values i want to use in my new JavaScript file which is JavaScript2
my file2.html is
in this file i am just populating an HTML table so i only have an div tag inside
<div id="tbl"></div>
<script type="text/javascript" src="JS/JavaScript1.js"></script>
<script type="text/javascript" src="JS/JavaScript2.js"></script>
And finally my JavaScript2 is
in this file I want to use the values of first Javascript file
$(document).ready(function() {
alert(currentlyClickedOutletform)
$('.loader').show();
$('.overlay').show();
$.ajax({
url: "LinkReportMain",
method: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
fromdate: $("#startdate").val(),
todate: $("#enddate").val(),
outlet: $("#all").val()
},
success: function(data) {
let formatedData = formatData(data);
renderTable(formatedData);
$('.loader').hide();
$('.overlay').hide();
}
});
});
NOTE to see the code of JavaScript2 file please see the snippet its not working but my code was not getting formatted so I have put that into snippet
So what I am trying to achieve is to use the Variable of JavaScript1 into JavaScript2
i am doing it right but its not working any one out here who can guide em please, it would be very helpfull
Without localStorage
First set type="button" of you search button or prevent form submit by e.preventDefault(); on click event.
$("#btn-search").click(function(){
e.preventDefault();
// your other code
//code to redirect to another html page
var queryString = "?para1=" + currentlyClickedOutletform + "¶2=" + currentlyClickedStartdateform;
window.location.href = "page2.html" + queryString;
})
for other page script:
var queryString = decodeURIComponent(window.location.search);
queryString = queryString.substring(1);
var oldParam = queryString.split("&");
var param1 = oldParam[0];
var param2 = oldParam[1];
Now you can use param1 and param2.
**localStorage ** :
in first page store object :
localStorage.setItem("outletFrom",currentlyClickedOutletform);
localStorage.setItem("startDate",currentlyClickedStartdateform);
in seond page get data:
var currentlyClickedOutletform = localStorage.getItem("outletFrom");
var currentlyClickedStartdateform= localStorage.getItem("startDate");
Hi I am using flask to create a web app in python.
In my profile.html page in template direcotiry I have profile.html as shown below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
<script src="../static/js/jquery-1.11.2.js"></script>
<script src="../static/js/getAcademic.js"></script>
</head>
<body>
<div class="jumbotron">
</div>
</body>
</html>
In the app.py,
#app.route('/getDetails')
def getDetails():
try:
#get data from mysql database and convert to a json and return
return json.dumps(academic_dict)
except Exception as e:
return render_template('error.html', error=str(e))
The returned json object is as follows,
In my js file,
$(function() {
$.ajax({
url: '/getDetails',
type: 'GET',
success: function(res) {
var div = $('<table>')
.attr('class', 'list-group')
.append($('<tr>')
.attr('class', 'list-group-item active')
.append($('<td>')
.attr('class', 'list-group-item-text'),
$('<td>')
.attr('class', 'list-group-item-text')));
var wishObj = JSON.parse(res);
var wish = '';
$.each(wishObj,function(index, value){
wish = $(table).clone();
$(wish).find('td').text(value.Title);
$(wish).find('td').text(value.Data);
$('.jumbotron').append(wish);
});
},
error: function(error) {
console.log(error);
}
});
});
json is converted and returned correctly but the data is not displaying in the profile.html page. I checked the console and it is displaying the error Uncaught ReferenceError: table is not defined in the .js file.
I want to display a table with the data returned as the json object but the table is not displaying when the profile.html page is loading. Please help me with this.
You've got one simple mistake (but don't worry, that happens to everyone...) on the line wish = $(table).clone(); – you use table to reference <table> you saved in variable div .
Either replace $(table) with $(div) there or (I would suggest this solution for readability) rename var div = $('<table>') in the beginning to var table = ...
(Sorry for reviving such an old post, but I'm on badge hunt :])
Oh, and one more point: please don't use screenshots of code, but the code itself (even just shortened) for us to test your problem and our solution:
[{'Title': 'Name', 'Data': 'john mark'},
{'Title': 'Faculty', 'Data': 'cs'}]`
I'm trying experiment with Semantic UI Calendar where you have a date input field and a calendar pops up when you select it as shown in this first example. I'm unfamiliar with this process so I'm unsure if I'm properly linking the .js file or if it's something else. I've looked at other problems and saw mention of jquery, but again unsure about how to even check if that's the problem.
TOOLS:
Webstorm, Node.js
PROCESS:
1: npm install --save semantic-ui-calendar (install instructions ref)
2: Added the below code and tried to link them together
3: npm start (running on local host)
4: Page loads, input field and everything else wdisplays, calendar failing to show
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/node_modules/semantic-ui-calendar/dist/calendar.min.js"></script>
<link rel="stylesheet" href="/node_modules/semantic-ui-calendar/dist/calendar.min.css" />
<script src="/utils/calendar.js"></script>
</head>
<body>
<div>
<div class="ui calendar" id="example1">
<div class="ui input left icon">
<i class="calendar icon"></i>
<input type="text" placeholder="Date/Time">
</div>
</div>
</div>
</body>
</html>
Javascript file:
$('#example1').calendar();
$('#example2').calendar({
type: 'date'
});
$('#example3').calendar({
type: 'time'
});
$('#rangestart').calendar({
type: 'date',
endCalendar: $('#rangeend')
});
$('#rangeend').calendar({
type: 'date',
startCalendar: $('#rangestart')
});
$('#example4').calendar({
startMode: 'year'
});
$('#example5').calendar();
$('#example6').calendar({
ampm: false,
type: 'time'
});
$('#example7').calendar({
type: 'month'
});
$('#example8').calendar({
type: 'year'
});
$('#example9').calendar();
$('#example10').calendar({
on: 'hover'
});
var today = new Date();
$('#example11').calendar({
minDate: new Date(today.getFullYear(), today.getMonth(), today.getDate() - 5),
maxDate: new Date(today.getFullYear(), today.getMonth(), today.getDate() + 5)
});
$('#example12').calendar({
monthFirst: false
});
$('#example13').calendar({
monthFirst: false,
formatter: {
date: function (date, settings) {
if (!date) return '';
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
return day + '/' + month + '/' + year;
}
}
});
$('#example14').calendar({
inline: true
});
$('#example15').calendar();
I think it doesn't works because you forget to import Jquery plugin, you can do it with a cdn :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
And your javascript files is not good if you use Jquery, you have to start the files by :
$(document).ready(function() {
/* YOUR JAVASCRIPT CODE INSIDE */
});
Peace
It will not work because Semantic UI v2.3.3 does not provide a calendar function. You can check in the inspect section; it will throw an error. If you want to use calendar you need to downgrade your semantic.js file to v2.1.4.
In a class, I was asked to make a dynamic drop-down menu in a form using HTML5 and JavaScript. I did that here.
Now, I need to call data from a JSON file. I looked at other answers on SOF and am still not really understanding how to use JQuery to get info from the JSON file.
I need to have 2 fields: the first field is a Country. The JSON key is country and the value is state. A copy of the JSON file and contents can be found here. The second drop-down field adds only the values / arrays related to its associated Country.
Here is a copy of my HTML5 file:
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="getData.js"></script>
<script type="text/javascript" src="moreScript.js"></script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="locationSelector" enctype='application/json'>
<br id="selectCountry"></br>
<select id='country'></select>
<br id="selectState">=</br>
<select id='state'></select>
</form>
</body>
</html>
Here is a copy of the JS file I wrote so far that tries to get the data from the JSON file and fails:
$(document).ready(function() {
var data = "countryState.JSON";
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the content from the other JS file that adds the field instruction:
var selectYourCountry = document.getElementById('selectCountry');
selectYourCountry.innerHTML = "Select Your Country: ";
var selectYourState = document.getElementById('selectState');
selectYourState.innerHTML = "Select Your State";
This was supposed to at least add the values to the field, but nothing but empty boxes appear on the web page.
I then need to make a conditional statement like the one at here but calling or referencing data from the JSON file.
I have only taken some HTML and JavaScript courses, not JQuery and JSON. So, your help will greatly increase my knowledge, which I will be very grateful for.
Thank you!!
I found this SOF answer and changed my JS file to the following:
$(document).ready(function()
{
$('#locationSelector').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
url:"countryState.JSON",
dataType: "json",
success: function (data) {
$.each(data.country,function(i,obj)
{
alert(obj.value+":"+obj.text);
var div_data="<option value="+obj.value+">"+obj.text+"</option>";
alert(div_data);
$(div_data).appendTo('#locator');
});
}
});
});
});
And, I edited my HTML document as follows:
<form id="locationSelector" enctype='application/json'></form>
I removed and added back the <select> tags and with the following at least I get a blank box:
`<form id="locationSelector" enctype='application/json'>
<select id="locator"></select>
</form>`
I feel like I am getting closer, but am still lost.
Can you try this:
$.get("countryState.JSON", function( data ) {
var html = "";
$.each(data.d, function(i, el) {
console.log(el);
html += "<option value='"+Your value+"'>"+Your displayed text+"</option>";
});
$('#state').html(html);
});
I have tried to implement the date picker in android. I want it to get the data and show it in the text format
<html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"></script>
<script type="text/javascript" charset="utf-8" src="datePickerPlugin.js"></script>
<script type="text/javascript" charset="utf-8">
function dateTest() {
var myNewDate = new Date();
window.plugins.datePicker.show({
date : myNewDate,
mode : 'date', // date or time or blank for both
allowOldDates : true
}, function(returnDate) {
var newDate = new Date(returnDate);
currentField.val(newDate.toString("dd/MMM/yyyy"));
// This fixes the problem you mention at the bottom of this script with it not working a second/third time around, because it is in focus.
currentField.blur();
});
}
</script>
</head>
<body bgcolor="#ffffff">
<hr>DatePicker Test<hr><br>
<input type="button" onClick ="dateTest()" value ="Today's Date!!" />
<div id="view"></div>
</body>
</html>
I am getting it as an alert...but unable to store it as a string on the same page
Why loose ur head?
A <input type="date"> will allways deppend on device's interpretation of it, in some android devices it doesn't even work,
There is plenty of plugins, addons, whatever, for it,
I personally like, and use mobiscroll: Link
Edit: Mobiscroll is now paid but there are loads of free frontend mobile frameworks and probably all of them have a datepicker, such as jQuery Mobile-datepicker.
It seems that your currentField is undefined. Did you check the chrome console before running it on AVD ? Pls try to post the element in which you are trying to display the date as well.
For now, I am assuming that you are trying to do what the following code does
$('.nativedatepicker').focus(function(event) {
var currentField = $(this);
var myNewDate = new Date(Date.parse(currentField.val())) || new Date();
// Same handling for iPhone and Android
window.plugins.datePicker.show({
date : myNewDate,
mode : 'date', // date or time or blank for both
allowOldDates : true
}, function(returnDate) {
var newDate = new Date(returnDate);
var newString = newDate.toString();
newString = newString.substring(0,15);
currentField.val(newString);
// This fixes the problem you mention at the bottom of this script with it not working a second/third time around, because it is in focus.
currentField.blur();
});
});
The element is as follows
<input type="text" class="nativedatepicker" readonly value = "Fri Jun 21 2013"/>
Works like a charm !! Hope it helps !!
What I want to happen is simple - I just want a datepicker to display when I click a certain field.
However, the same as Aleks, I don't know what to put in my html, how to use it in html, and what should I put in the html to invoke the datepicker on some input.
The documentation from the plugin is incomplete.
I found a solution from this test project.
Steps are as follows:
Pre-requisite: phonegap/cordova-cli installed
Install Cordova's device plugin: $ cordova plugin add org.apache.cordova.device
Install Dirk's datepicker plugin: $ cordova plugin add https://github.com/DURK/cordova-datepicker-plugin
Copy the nativedatepicker.js from the test project and place it on your project's js folder. This file has showDatePicker(), showDateTimePicker() convenience functions.
Add the ff. to index.html code:
Note: The datepicker won't show when you test it in your browser
....
<div class="form-group">
<label>Appointment</label>
<input type="text" class="form-control datepicker" id="appointment">
</div>
....
<script src="js/nativedatepicker.js"></script>
<script src="cordova.js"></script>
<script type="text/javascript">
(function($){
$(document).ready(function () {
$(document).on('click', '.datepicker', function () {
showDatePicker($(this), 'date');
});
$(document).on('click', '.timepicker', function () {
showDatePicker($(this), 'time');
});
$(document).on('click', '.datetimepicker', function () {
if (device.platform === "Android")
showDateTimePicker($(this));
else
showDatePicker($(this), 'datetime');
});
});
})(jQuery);
</script>
This is my working implementation. Input type is text, readonly.
$('.nativedatepicker').focus(function(event) {
var currentField = $(this);
var myNewDate = new Date();
window.plugins.datePicker.show({
date : myNewDate,
mode : 'date',
allowOldDates : true
}, function(returnDate) {
var array = returnDate.split("/");
var day = array[2], month = array[1];
if (day <= 9)
day = "0" + day;
if (month <= 9)
month = "0" + month;
currentField.val(array[0] + "/" + month + "/" + day);
currentField.blur();
});
});
Why would you want to implement a custom date picker if there is an ative one available ?
You can simply use <input type="date"> to create the commonly known iOS date picker.
For more infos on input fields on mobile devices I suggest: http://blog.teamtreehouse.com/using-html5-input-types-to-enhance-the-mobile-browsing-experience