The user selects one of the options and submits the form.
Then without submitting the form, I need to display data from json file.
I am storing ajax call in a global variable display_this and calling that variable as a function after form is submitted.
When I select option and press submit I get this error:
TypeError: display_this is not a function
When I refresh the page, it displays the data.
My code:
<form id="form">
<select name="op" id="op">
<option value="A">A</option>
<option value="B">B</option>
</select>
<input value="Submit" type="submit" id="submit">
</form>
My JSON data:
[
{"key":"A","val":"apple"},
{"key":"A","val":"orange"},
{"key":"B","val":"carrot"},
{"key":"B","val":"onion"}
]
My jQuery code:
$(document).ready(function () {
var output;
var display_this = function () {
var val = $("#op").val();
$.ajax({
async: 'false',
type: 'post',
url: 'abc.php',
data: {
"val": val
},
dataType: 'json',
success: function (response) {
var data = JSON.stringify(response);
var resp = JSON.parse(data);
$.each(resp, function (i, item) {
if (val == "A" && resp[i].key == "A") {
output += resp[i].val + "</br>";
} else if (val == "B" && resp[i].key == "B") {
output += resp[i].val + "</br>";
}
});
return results.html(output);
}
});
}();
$('#form').submit(function (e) {
e.preventDefault();
display_this();
});
});
You function is not available to your form submit. I suggest this
$(function () {
$('#form').submit(function (e) {
e.preventDefault();
var output;
var val = $("#op").val();
$.ajax({
// async: 'false', // do NOT use async false
type: 'post',
url: 'abc.php',
data: {
"val": val
},
dataType: 'json',
success: function (resp) {
$.each(resp, function (i, item) {
if (val == "A" && resp[i].key == "A") {
output += resp[i].val + "</br>";
} else if (val == "B" && resp[i].key == "B") {
output += resp[i].val + "</br>";
}
});
$("#results").html(output);
}
});
});
});
Related
I would like, that when the Enter button is pressed, the application will search a city, the action now is started by pressing the Search button. Below is my code:
const ENTER_KEY_CODE = 13;
document.querySelector('#city').addEventListener('keyup', function(e) {
if (e.keyCode === ENTER_KEY_CODE) {
var city = $(this).val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
});
} else {
$("error").html('Field cant be empty')
}
};
});
All you need to do is add a keyup events listener to your input element. When the handler is called, simply check the e.keyCode to see if it's enter was pressed. If it was, do your thing:
const ENTER_KEY_CODE = 13;
document.querySelector('#textEl').addEventListener('keyup', function(e) {
if (e.keyCode === ENTER_KEY_CODE) {
var city = $(this).val();
var url = `http://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&units=metric&APPID=bb037310921af67f24ba53f2bad48b1d`;
if (city !== '') {
console.log(`Make ajax call to ${url}`);
//Make your AJAX call here
} else {
console.log('City cannot be blank!');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="textEl" type="text" />
<div id="error"></div>
This a sample code please use this a reference code.
HTML code
<input id="InputEnter" >
Javascript code
var input = document.getElementById("InputEnter");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
$(document).ready(function () {
$('#submitWeather').click(function () {
var city = $("#city").val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
}
});
This should work. I assume that your ajax request is correct.
document.querySelector('#submitWeather').addEventListener('keypress', function(e){
if(e.which === 13){
// your ajax request
}
})
I'm creating a phonegap app.
This code is going to get by a json, the content on de database. Then I want to insert in the database the vote with the device.uuid. The problem is that the on("click") or on("touchstart") is not firing, not even in the alert(). Please help!!
$(document).ready(function() {
var url = "http://filmpix.esy.es/json.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id;
$('.music-box').append("<button class='btn btn-default insert' value='" + id + "'>Votar</button>");
});
});
$(".insert").on("touchstart", function() {
alert("asdasd");
var music_id = $(this).val();
var dataString = "music_id=" + music_id;
$.ajax({
type: "POST",
url: "http://filmpix.esy.es/insert.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#insert").val('A votar...');
confirm("Tens a certeza que queres votar nesta musica?");
},
success: function(data) {
if (data == "success") {
alert("inserted");
$("#insert").val('Votado');
} else if (data == "error") {
alert("Não foi possível votar");
}
}
});
return false;
});
});
The return false statement should come after the function's "}" on your touch event.
So, I have a jQuery submit event handler, that on submit queries a database, and if no records are returned, prevents the form page from reloading, and if records were found, should then redirect the user to another page using document.location.href.
But what is actually happening is that records are being found, and instead of then redirecting the user to another page, the form page itself reloads.
What am I overlooking here?
jQuery('#MyForm').submit(function(e) {
console.log("getUserIDs is successfully hit.");
alert("The submit event has been hit");
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object') {
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data: {
action: "showcountries",
makeselection: "getUserIDs",
countryID: countryVal,
cityID: cityVal,
townID: townVal,
categoriesID: categoriesVal,
locationHref: url,
serialized
},
dataType: "json",
success: function(data) {
alert("Success of the submit event has been hit.");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
jQuery.post('', function(data) {
document.location.href = window.location.hostname + '/index.php/anotherpage/';
});
},
error: function(data, status, error) {
alert("No records were returned for your search. Please make another selection.");
e.preventDefault();
return false;
console.log(data);
console.log(status);
console.log(error);
}
});
});
<form id="MyForm" method="Post">
<input type="submit" name="fl-button" id="fl-button" role="button" value="SEARCH" class="fl-button" disabled="disabled" value="Send" />
</form>
jQuery('#MyForm').submit(function (e) {
e.preventDefault();
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object') {
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data: serialized + '&action=showcountries&makeselection=getUserIDs&countryID=' +
countryVal + '&cityID=' + cityVal + '&townID=' + townVal + '&categoriesID=' +
categoriesVal + '&locationHref=' + url,
dataType: "json",
success: function (data) {
alert("Success!");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
window.location.href = url + '/index.php/anotherpage/';
},
error: function (data, status, error) {
alert("No records were returned for your search. Please make another selection.");
}
});
return false;
});
jQuery('#MyForm').submit(function (e) {
e.preventDefault(); //use prevent default here
console.log("getUserIDs is successfully hit.");
alert("The submit event has been hit");
var countryVal;
var cityVal;
var townVal;
var categoriesVal;
var serialized = jQuery('#MyForm').serialize();
var url = window.location.hostname;
countryVal = jQuery("#CountryList").val();
cityVal = jQuery("#CityList").val();
townVal = jQuery("#TownList").val();
if (typeof townVal == 'object'){
townVal = "object";
}
categoriesVal = jQuery("#CategoriesList").val();
jQuery.ajax({
cache: false,
type: "POST",
async: false,
url: gymRegions.ajaxurl,
data:{action: "showcountries",
makeselection: "getUserIDs",
countryID: countryVal,
cityID: cityVal,
townID: townVal,
categoriesID: categoriesVal,
locationHref: url,
serialized},
dataType: "json",
success: function (data) {
alert("Success of the submit event has been hit.");
localStorage.setItem('dataObjectTemp2', JSON.stringify(data));
var numericRecCount = parseInt(data.c);
document.location.href = window.location.hostname + '/index.php/anotherpage/';
},
error: function (data, status, error) {
alert("No records were returned for your search. Please make another selection.");
console.log(data);
console.log(status);
console.log(error);
}
});
});
This script works well, the town that it generates function must register in but he generates so city
how to insert/pass value #city into input field
value="cityname"
<input id="city" name="input" value="cityname" />
<script>
$(document).ready( function () {
var lat = 37.42;
var long = -122.08;
$.ajax({
type: 'GET',
dataType: "json",
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&sensor=false",
data: {},
success: function(data) {
$('#city').html(data);
$.each( data['results'],function(i, val) {
$.each( val['address_components'],function(i, val) {
if (val['types'] == "locality,political") {
if (val['long_name']!="") {
$('#city').html(val['long_name']);
}
else {
$('#city').html("unknown");
}
console.log(i+", " + val['long_name']);
console.log(i+", " + val['types']);
}
});
});
console.log('Success');
},
error: function () { console.log('error'); }
});
});
</script>
Directly write :
$('#city').val(val['long_name']);
To assign a value to an input field use .val():
$('input#city').val(newValue);
Substitute
$("#city").val(/* value to set */)
for each occurrence of
$("#city").html(/* value to set */)
I have an input form which has three text fields and a checkbox input section where the user can select more than one value. I also have an ajax request which sends a POST request to an api. I have written a function to iterate over the form inputs and parse them to JSON, however, it has come to my attention that this wont work for checkbox values. Here is my function:
<script>
console.log(document);
var form = document.getElementById("myform");
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var info = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
info[input.name] = input.value;
}
addPerson(info);
}
}
function addPerson(info) {
$.ajax({
type: "POST",
url: "http://example.com",
data: JSON.stringify(info),
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
alert("success");
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
}
});
}
</script>
I've been trying to get the checkbox values into JSON using
$.each($('input[id="data[i].id"]:checked'), function() {
var value = $(this).val();
qualifications.push(value);
});
but I cant figure out how to add these values to the JSON that is being posted to the server, can anyone help?
Have tried .serialize() and I THINK it is working-
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('myform').submit(function() {
$('#result').text(JSON.stringify($('myform').serializeObject()));
return false;
});
});
function addPerson(result){
$.ajax({
type: "POST",
url: "http://example.com",
data: JSON.stringify(result),
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
alert("success");
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
}
});
}
</script>
If anyone has thoughts/ comments as to how effective the above is, or if there is a better way of doing it, I would like to hear them?
Try this:
var input = form[i];
if (input.name) {
if(input.tagName.toLowerCase() === 'input' &&
(input.type.toLowerCase() === 'checkbox' || input.type.toLowerCase() === 'radio') &&
input.checked)
info[input.name] = input.value;
else
info[input.name] = input.value;
}
addPerson(info);
EDIT:
I suggest using jQuery form.serialize() method as #Drixson Oseña mentioned.