Why is event parameter forgotten after recursion? - javascript

Consider the following code:
<html>
<head>
<meta charset="UTF-8">
<title>title...</title>
<link type="text/css" rel="stylesheet" href="jquery-ui-1.10.4.custom.css" />
<script type="text/javascript" src="jquery-1.10.2.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.4.custom.min.js"></script>
</head>
<body>
<div id="dialog1" style="display: none">
<p>some text</p>
</div>
<input id="but1" type="button" value="clickme" />
</body>
<script>
$("#but1").on ('click', {valu: 1}, f);
$("#dialog1").dialog({ autoOpen:false });
function f (event) {
console.log(event.data.valu); // EXISTS
$.ajax({
type: "POST",
url: "event.xml",
dataType: "xml",
success: function (result) {
console.log(event.data.valu); // DOESN'T EXIST
var promptDialog = $("#dialog1");
var promptDialogButtons = {};
promptDialogButtons['ok'] = function(){
$("#dialog1").on('click', { valu: 0 }, f);
$("#dialog1").click();
$("#dialog1").dialog('close');
};
promptDialogButtons['cancel'] = function(){
$("#dialog1").dialog('close');
};
promptDialog.dialog({ width:333, modal: true, title: "sometitle", buttons:promptDialogButtons});
$("#dialog1").dialog('open');
}
});
}
</script>
</html>
When clicking on "clickme" and then "ok" the output will be:
1
1
0
TypeError: event.data is null
Why is event.data.valu forgotten in the $.ajax() after recursion? No redeclaration of parameter event in the $.ajax(). Please fill in the valid path to the JQuery libraries. Use any valid event.xml file.

Apparently the jquery-ui dialogue does handle the click event of the ok button differently. your problem could be solved by calling the function f directly within the success function.
f({ data:{
valu: 0
}
});
see http://jsfiddle.net/klickagent/3L1zro7w/8/
for a working example

Related

Print the arguments inside a handler function

Passing parameters on JQuery .trigger
The passed arguments are unable to display,
I get undefined even if the arguments are passed. How do I alert the passed arguments when a button is clicked.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$("#btn1").on('click', function(event, one, two) {
alert(one)
});
});
$("#btn1").trigger('click', [1, 2]);
</script>
<button id="btn1">Click here to display args passed</button>
</body>
</html>
you can do it by bellow code.
$(document).ready(()=>{
$("#myBtn").on('click',{ extra : 'you parameter value' }, function(event) {
var data = event.data;
myFunction(data.extra);
});
})
function myFunction(parameter)
{
alert(parameter)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="myBtn">Button</button>

openweathermap weather data by zip code not working?

i need to make it so that when a zip code is typed into the box and the submit button is clicked, the name of the city shows up under it. when i click the button after putting a zip code the city name doesn't show up. it says the error is that wallOfText is not a function but i'm not sure how to fix it. any help would be appreciated!! here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
Enter your zip code:<br><input type="text" id="zipBox" name="zipCode"><br><br>
<button onclick="weatherFunction()">Submit</button>
<p id="result"></p>
<script>
function weatherFunction() {
var zip = document.getElementById("zipBox").value;
jQuery(document).ready(function ($) {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?zip=" +zip+ ",us&appid=b3456f9acbfa64fc4495e6696ecdc9a5",
dataType: "jsonp",
success: function (wallOfText) {
city = wallOfText("name");
if (zip != null) {
document.getElementById("result").innerHTML = wallOfText;
}
}
});
});
}
</script>
</body>
</html>
The issue you have is that you're attempting to call wallOfText like it's a function, when in fact it's the object which has been deserialised from the response of the AJAX call. As such, you need to access the object's name property to set the city variable, then use that to set the text() of the #result element.
Note that the document.ready handler within the function is redundant, and you should be doing the zip value validation before you make the request. I also updated the logic to use jQuery to bind the event handler on the button instead of the outdated onclick attribute. Try this:
jQuery(function() {
$('#send').click(function() {
var zip = $("#zipBox").val();
if (zip !== '') {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?zip=" + zip + ",us&appid=b3456f9acbfa64fc4495e6696ecdc9a5",
dataType: "jsonp",
success: function(wallOfText) {
var city = wallOfText.name;
$("#result").text(city);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter your zip code:<br>
<input type="text" id="zipBox" name="zipCode" value="90210" /><br /><br />
<button type="button" id="send">Submit</button>
<p id="result"></p>

Dialog Box with Input Element

I want to have a dialog window with an input. I could use the default jQuery-ui one, but I am using one that incorporate bootstrap. However, the input only appears the first time that it is opened, any subsequent times the dialog is opened, the input is missing. How would this be remedied?
Here is the HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<link rel="stylesheet" href="../bower_components/jquery-ui/themes/base/jquery.ui.all.css">
<link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="../bower_components/bootstrap3-dialog/css/bootstrap-dialog.min.css">
<link rel="stylesheet" href="../bower_components/bootstrap-datepicker/css/datepicker3.css">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h3>Hello!</h3>
<div>
<span>Enter a Zip Code: </span>
<input type="text" id="zip">
<button id="getEvents" class="btn btn-primary">Get events!</button>
</div>
<div class="datepicker"></div>
<div id="events"></div>
<button id="addItemButton">Add an item</button>
<div id="addItemDialog"><input type="text" id="newItem"></div>
<script src="../bower_components/jquery/jquery.min.js"></script>
<script src="../bower_components/jquery-ui/ui/jquery-ui.js"></script>
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="../bower_components/bootstrap3-dialog/js/bootstrap-dialog.js"></script>
<script src="../bower_components/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<script src="js/calendar.js"></script>
</body>
</html>
Here is the JS:
$(function () {
"use strict";
var url,
year,
month,
zip,
date,
events = [],
newItem;
$("#addItemDialog").hide();
$(".datepicker").datepicker({dateFormat: "yy-mm-dd"}).click(function(){
$("#events").empty();
date = $(".datepicker").datepicker("getDate");
//console.dir(date.toISOString().substr(0, 10));
$(events).each(function(i, event){
//console.log(event);
if(event.date.substr(0, 10) === date.toISOString().substr(0, 10)){
console.log(event.title);
$("#events").append("<h4 class='event'>" + event.title + "</h4>");
}
});
});
$("#getEvents").on("click", function () {
zip = $("#zip").val();
if(isValidUSZip(zip)){
zip = zip.substr(0, 5);
getCalendar();
}else{
BootstrapDialog.show({
message: "You must enter a valid zip code!",
buttons: [{label:"OK", action: function(dialog){dialog.close();}}],
draggable: true
});
}
});
function isValidUSZip(sZip) {
return /^[0-9]{5}(?:-[0-9]{4})?$/.test(sZip);
}
function getCalendar() {
$.ajax({
type: "GET",
url: "http://www.hebcal.com/hebcal/?v=1&cfg=json&nh=on&nx=on&year=now&month=x&ss=on&mf=on&c=on&zip=" + zip +"&m=72&s=on",
success: function (data) {
console.dir(data);
$(data.items).each(function(index, item){
//console.dir(item.date.substr(0, 10));
events.push(item);
});
}
});
}
$("#addItemButton").on("click", function(){
BootstrapDialog.show({
message: $("#newItem"),
buttons: [{
label: "Enter",
action: function(dialog){
newItem = $("#newItem").val();
events.push({date: new Date(date).toISOString(), title: newItem});
dialog.close();
}
}]
});
});
});
I took a time and make this fiddle, aparently everything is working fine:
I doubt about this line for a moment, but still uncommented is going right:
$(function () {
//"use strict";
var url,
year,
month,
zip,
date,
events = [],
newItem;
http://jsfiddle.net/r2FyC/3/

jQuery AJAX POST; Not posting

I'm fairly certain the issue I'm having is related to the jQuery's $.ajax({...}); function . When printing the array in PHP i get Notice: Undefined index.
I'd sincerely appreciate it if i could get some advice here.
<script>
$(document).ready(function(){
$("#submit").click(function() {
var platform_var = $('input[name="platform"]').val();
var bandwidth_var = $("#bandwidth-widget").val();
alert(bandwidth_var); // Returns the array as an alert.
$.ajax({
url: "index.php",
type: "POST",
data: {
platform_var: platform_var,
bandwidth_var: bandwidth_var
}
});
});
});
</script>
<?php
print_r($_POST['platform_var']);
?>
Demo (w/o PHP)
You need to assign the values to the variables on document load.
$(document).ready(function() {
platform_var = $('input[name="platform"]').val();
bandwidth_var = $("#bandwidth-widget").val();
});
EDIT: if the values are not instanciated on document load, you need to assign them when they actually have the correct value, just before you do the Ajax request.
$(document).on('submit', '#compare', function(e) {
var platform_var = $('input[name="platform"]').val();
var bandwidth_var = $("#bandwidth-widget").val();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: {
platform: platform_var,
bandwidth: bandwidth_var
}
});
});
Currently, you are assigning them before the values actually exists.
Hope this helps.
Your have two problems in your code:
The selector is wrong - you're searching for an input with the name attribute which equals to platform and in the html you have an array input with the name platform[]. Therefore it will not find any matching inputs, which is why the var platform_var is undefined or null.
To fetch the checked checkboxes, you need to add :checked to the selector, otherwise jQuery will return all of the checkboxes regardless of their checkbox status.
To fix this, simply change
var platform_var = $('input[name="platform"]').val();
to
var platform_var = $('input[name="platform[]"]:checked').map(function(){return $(this).val();}).get();
Also, have in mind that in your php script, the $_POST['platform'] variable will be an array.
I would advice you to have a look at the jQuery API documentation to further understand how the selectors work.
Here is the edited fiddle.
Edit:
I've code I've added below confirms that the code in the fiddle is working fine. Apparently you are having trouble with your own php code rather than your JavaScript.
I believe you should sit down and check your code.
<?php
// Save everything here in a file called "test.php"
if (isset($_POST) && !empty($_POST)){
print_r($_POST);
exit();
}
?>
<html>
<head>
<title>Testing page</title>
<link rel="stylesheet" type="text/css" href="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/styles/jquery.selectBox.css"/>
<link rel="stylesheet" type="text/css" href="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/styles/jquery.nouislider.min.css"/>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/scripts/jquery.selectBox.js"></script>
<script type="text/javascript" src="http://www.hostingarchive.com/wp-content/themes/My-theme/assets/scripts/jquery.nouislider.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.cmp-select').selectBox();
$("#price-widget").noUiSlider({
range: [5, 150], start: [5, 75], step: [5], connect: true, direction: 'ltr', serialization: {
mark: '.', resolution: 1, to: [
[$("#low-price"), 'html'],
[$('#high-price'), 'html']
]
}
});
$("#bandwidth-widget").noUiSlider({
range: [0, 2000], start: [10, 1000], step: [10], connect: true, direction: 'ltr', serialization: {
mark: '.', resolution: 1, to: [
[$("#low-bandwidth"), 'html'],
[$('#high-bandwidth'), 'html']
]
}
});
$("#submit").click(function () {
var platform_var = $('input[name="platform[]"]:checked').map(function () {
return $(this).val();
}).get();
var bandwidth_var = $("#bandwidth-widget").val();
alert(bandwidth_var);
console.log(platform_var);
console.log(bandwidth_var);
$.ajax({
url : "test.php",
type: "POST",
data: {
platform_var : platform_var,
bandwidth_var: bandwidth_var
}
});
});
});
</script>
</head>
<body>
<div id="compare">
<h3>Platform</h3>
<input name="platform[]" type="checkbox" value="shared" checked="checked">Shared</input>
<input name="platform[]" type="checkbox" value="dedicated">Dedicated</input>
<input name="platform[]" type="checkbox" value="cdn">CDN</input>
<input name="platform[]" type="checkbox" value="vps">VPS</input>
<input name="platform[]" type="checkbox" value="vds">VDS</input>
<h3>Bandwidth</h3>
<div id="bandwidth-slide">
<p class="inline-block"><span id="low-bandwidth"></span><span><small>GB</small></span></p>
<div class="inline-block" id="bandwidth-widget"></div>
<p class="inline-block"><span id="high-bandwidth"></span><span><small>GB</small></span></p>
</div>
<h3>Price</h3>
<div id="pricing-slide" class="clearfix">
<p class="inline-block">$<span id="low-price"></span></p>
<div class="inline-block" id="price-widget"></div>
<p class="inline-block">$<span id="high-price"></span><span>/mo</span></p>
</div>
<input type="submit" id="submit" value="enter">
</div>
</body>
</html>

Dropzone not showing when using jquery post

I have a function that receives data from a server and shows a dropzone.js form,
function requestData() {
// showDropzone(); // displaying dropzone from here works,
$.post("/userids/",null, function(data, status) {
jsonarray = JSON.parse(data);
showDropzone(); // here, it calls the function but dropzone is not displayed
});
}
function showDropzone(){
$("#content").html('<form id="dropzone" action="/target" class="dropzone"></form>');
}
Dropzone doesn't show when I call it from inside the post method, but it does when I call it from outside of it. I have no idea what is causing this, there is no error or warning, and I've tried with all possible dropzone configurations, but even forceFallback set to true doesn't work.
EDIT:
Here is the complete html,
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="dropzone.js"></script>
</head>
<body>
<div id="container">
<div id="content"></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
requestData();
});
function requestData() {
// showDropzone(); // displaying dropzone from here works,
$.post("/userids/",null, function(data, status) {
jsonarray = JSON.parse(data);
showDropzone(); // here, it calls the function but dropzone is not displayed
});
}
function showDropzone(){
$("#content").html('<form id="dropzone" action="/target" class="dropzone"></form>');
}
</script>
</body>
</html>
:D I bet form#dropzone adds to the #content, but you don't see it ... because it's EMPTY!! (no input inside) :D Check out my fiddle!
http://jsfiddle.net/U5wCw/
Change your code to
$("#content").html('<form id="dropzone" action="/target" class="dropzone"><input type="text"/></form>');

Categories