I want my submit button to pull the value from the input box next to it, change the '#' to a '-' and then pass it on so that I can pull information respective to that user and then populate the field in HTML. But the page just refreshes and a '?' gets added to the url.
$("#usernameBtn").click(function() {
var unTouchedID = $("#userid").val();
var usrID = unTouchedID.replace("#", "-");
$.ajax({
url: "https://owapi.net/api/v3/u/" + usrID + "/stats",
dataType: 'json',
data: "",
success: function (data) {
$('#heroStats_elims').html('<h2>'+ data.us.stats.competitive.average_stats.eliminations_avg + '</h2>');
//var avgElims = //data.us.stats.competitive.average_stats.eliminations_avg
}
}); });
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Battle.net Tag" id="userid">
</div>
<button type="submit" class="btn btn-default" id="usernameBtn">Submit</button>
You need to use event.preventDefault(); as #Andrew mentioned to prevent the default behavior of submitting the page.
$("#usernameBtn").click(function(e) {
e.preventDefault();
var unTouchedID = $("#userid").val();
var usrID = unTouchedID.replace("#", "-");
$.ajax({
url: "https://owapi.net/api/v3/u/" + usrID + "/stats",
dataType: 'json',
data: "",
success: function (data) {
$('#heroStats_elims').html('<h2>'+ data.us.stats.competitive.average_stats.eliminations_avg + '</h2>');
//var avgElims = //data.us.stats.competitive.average_stats.eliminations_avg
}
});
});
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Battle.net Tag" id="userid">
</div>
<button type="submit" class="btn btn-default" id="usernameBtn">Submit</button>
Related
Ok, so i have a API based on Laravel, i'm trying to return its JSON response in a view with it's own form data.
HTML:
<form id="translate" action="translate" method="GET">
<div class="form-group"><label for="from" name="from">Translate from</label><select class="form-control" id="from"><option value="latin" selected="selected">Latin alphabet</option><option value="deepling">Jekhr</option></select></div>
<div class="form-group"><label for="message" name="message">Message</label><textarea class="form-control" id="message"></textarea></div>
<div class="form-group"><div class="form-row"></div></div>
<button class="btn btn-primary btn-block" type="submit">Translate!</button>
</form>
Base API URL:
http://localhost/translate?text=Hello World&method=Latin&pronunciation
So i'm trying to write a Ajax request to get JSON response with form data and display it on DOM table, like:
Translated Message = $json["translated"]
Pronunciation = $json["pronounce"]
Can anyone help me?
Edit:
Here's a solution that I got based on comment:
$("#translate").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "GET",
url: url,
data: form.serialize(),
success: function(data)
{
$('#translateTable tbody tr').remove();
$('#translateTable tbody').append("<tr><td>Request</td><td>" + data.requested + "</td></tr><tr><td>Translation</td><td>" + data.translated + "</td></tr><tr><td>Pronounce</td><td>" + data.pronounce + "</td></tr>");
$('#translateTable').show();
}
});
});
I'm having a hard time sending a form using POST as well as JS. The reason for this setup is sending a form to DotMailer emailing program as well as Magento through AWS at the same time, with both having different means of sending. I'm thinking it gets sent to AWS before it actually has a chance to POST?
The data is JSON-ified before being sent to AWS which i presume would be an issue for POST for the mailing program?
Help will be much appreciated!
The code form code:
<form name="signup" id="signup" action="https://example.com/signup.ashx" method="post" autocomplete="off" class="redeye-form loyalty-form" onsubmit="return validate_signup(this, true)" data-form-id="loyalty-form">
<input type="hidden" name="ci_isconsentform" value="true">
<input type="hidden" name="userid" value="230531">
<input type="hidden" name="SIGb7f7109acfe72442f3b9937c47f1c0e7a78f60e9bec1ba7a7084e947eebceef2" value="">
<input type="hidden" name="addressbookid" value="574883" />
<input type="hidden" name="ReturnURL" value="">
<input type="hidden" id="ci_consenturl" name="ci_consenturl" value="">
<div>
<label class="wrap" for="FIRSTNAME">Imię: <span class="requiredfield">*</span></label>
<input name="cd_FIRSTNAME" id="FIRSTNAME" type="text" data-parameter="firstname" class="text regex" placeholder="" data-regex="^.{1,}$" data-regex-message="Wpisz poprawne imie (przynajmniej jeden znak)"aria-required="false" />
</div>
<div>
<label class="wrap" for="LASTNAME">Nazwisko: <span class="requiredfield">*</span></label>
<input name="cd_LASTNAME" id="LASTNAME" type="text" data-parameter="lastname" class="text regex" placeholder="" data-parameter="lastname"aria-required="false" />
</div>
<div>
<label class="wrap" for="POSTCODE">Kod pocztowy:</label>
<input type="text" class="text regex" name="cd_POSTCODE" id="POSTCODE" aria-required="false" />
</div>
<div>
<label class="wrap" for="email">Adres e-mail: <span class="requiredfield">*</span></label>
<input type="text" name="email" id="email" required aria-required="true" data-parameter="email" class="text regex">
</div>
<div class="newsletter text">
<p>
<input type="checkbox" name="ci_userConsentCheckBox" id="ci_userConsentCheckBox" data-parameter="doubleoptin" value="c">Consent text 1</p>
<input type="checkbox" name="sprawdzanko" id="sprawdzanko" value="1"><span>Consent text 2</span>
<p>Consent text 3</p>
<p>Kliknięcie w przycisk "Wyślij" znajdujący się poniżej oznacza akceptację Regulaminu.</p>
</div>
<input type="submit" class="c-btn c-btn--secondary" onmousedown="doSubmitEvents();" name="btnsubmit" id="btnsubmit" value="Wyślij" disabled> <p><span class="requiredfield">*</span>Wymagane pola</p>
</form>
The sending JS:
<script>
jQuery( document ).ready(function() {
const storeCode = "rg_pl";
var site = {
"url" : "https://reporting.example.com",
"id" : "14555",
"notify" : "examplesingleoptinwelcome"
};
var form = document.getElementsByTagName("form")[0];
var loyaltyForm = form.classList.contains('loyalty-form') == true;
jQuery("form.redeye-form .c-btn--secondary").click(function(e) {
e.preventDefault();
jQuery('.popup').remove();
var validityErrors = 0;
jQuery("input.required").each(function( index ) {
jQuery(this).removeClass("invalid");
if (!jQuery(this).val()) {
jQuery(this).after("<div class='popup'>Please enter something here</div>");
setTimeout(function() {
jQuery('.popup').remove();
}, 7000);
jQuery(this).addClass("invalid");
validityErrors++;
}
});
jQuery("select.required").each(function( index ) {
jQuery(this).removeClass("invalid");
if (!jQuery(this).val()) {
jQuery(this).after("<div class='popup'>Please enter something here</div>");
setTimeout(function() {
jQuery('.popup').remove();
}, 7000);
jQuery(this).addClass("invalid");
validityErrors++;
}
});
jQuery("input.regex").each(function( index ) {
jQuery(this).removeClass("invalid");
var patt = new RegExp(jQuery(this).data("regex"));
var result = patt.test(jQuery(this).val());
if (result !== true) {
var message = jQuery(this).data("regex-message");
jQuery(this).after("<div class='popup'>" + message + "</div>");
setTimeout(function() {
jQuery('.popup').remove();
}, 7000);
jQuery(this).addClass("invalid");
validityErrors++;
}
});
if (validityErrors == 0) {
var result = {};
var location = (window.location != window.parent.location)
? document.referrer
: document.location.href;
result["form-location"] = location;
var url = site.url + "/cgi-bin/rr/blank.gif";
var formTitle = jQuery("form.redeye-form").data("form-id");
result["subject"] = formTitle;
url = url.concat("?nourl=" + encodeURI(formTitle));
url = url.concat("&" + encodeURI(formTitle) + "=" + encodeURI(formTitle));
jQuery("form.redeye-form input").each(function( index ) {
if ( jQuery(this).is("input:text") ){
var parameter = jQuery(this).data("parameter");
var value = jQuery(this).val();
}
if ( jQuery(this).is("input:checkbox") ){
var parameter = jQuery(this).data("parameter");
var value = jQuery(this).is(':checked');
}
if ( jQuery(this).is("input:hidden") ){
var parameter = jQuery(this).data("parameter");
var value = jQuery(this).val();
}
result[parameter] = value;
url = url.concat("&" + encodeURI(parameter) + "=" + encodeURI(value));
});
jQuery("form.redeye-form select").each(function( index ) {
var parameter = jQuery(this).data("parameter");
var value = jQuery(this).val();
url = url.concat("&" + encodeURI(parameter) + "=" + encodeURI(value));
});
if (jQuery("input[data-parameter='doubleoptin']").is(":checked") == true) {
url = url.concat('¬ify=' + site.notify);
url = url.concat("&emailpermit=" + "yes");
url = url.concat("&newsletter=" + site.id);
} else {
url = url.concat("&emailpermit=" + "no");
url = url.concat("&newsletter=" + site.id);
}
url = url.concat("&domain_id=" + site.id);
var date = new Date();
result["date"] = date.getFullYear() + '-' + ('0' + date.getDate()).slice(-2) + '-'
+ ('0' + (date.getMonth()+1)).slice(-2);
result["url"] = window.location.href;
result["storeCode"] = storeCode;
var redEyeForm = jQuery( "form.redeye-form" );
redEyeForm.replaceWith( "<div class='successmessage'>Dziękujemy za wysłanie formularza</div>" );
// if (result["doubleoptin"] == "c") {
// result["doubleoptin"] = 1;
// } else {
// result["doubleoptin"] = 0;
// }
if (loyaltyForm == true){
console.log(result);
jQuery.ajax({
type: "POST",
url: 'https://example.execute-api.eu-west-1.amazonaws.com/Deployment',
contentType: 'application/json',
data: JSON.stringify(result),
success: function(res){
redEyeForm.replaceWith( "<div class='successmessage'>Dziękujemy za wysłanie formularza</div>" );
},
error: function(){
redEyeForm.replaceWith( "<div class='successmessage'>Wystąpił błąd</div>" );
}
});
}
}
});
});
</script>
EDIT: Could this accomplish what I need?
if (loyaltyForm == true){
console.log(result);
jQuery.ajax({
type: "POST",
url: 'https://h3uxa21uxf.execute-api.eu-west-1.amazonaws.com/Deployment',
contentType: 'application/json',
data: JSON.stringify(result),
success: function(res){
var $form = $(#signup);
$.ajax({
type : "POST",
cache : false,
url : $form.attr('action'),
data : $form.serializeArray(),
success : function(data) {
redEyeForm.replaceWith( "<div class='successmessage'>Dziękujemy za wysłanie formularza</div>" );
},
});
}
error: function(){
redEyeForm.replaceWith( "<div class='successmessage'>Wystąpił błąd</div>" );
}
});
}
}
});
});
I have a couple of examples you can build on.
Option 1 - You can submit to URL 1 via ajax and then submit the form as if user has clicked the button to URL 2.
Option 2 - Submit to URL 1 and then on success - submit to URL 2 - both via AJAX
// Option 1 - Ajax to submit first and then conduct default submit action for form
function ajaxAndSubmit(e){
e.preventDefault(); // Stop the default action of the submit button
var formData = $('#sample-form').serialize(); // Serialize the data
// Start ajax 1
$.ajax( {
type: "POST",
url: 'some url',
data: formData,
success: function( response ) {
console.log( response );
//Mimic default action
$('#sample-form').submit();
}
} );
}
// Option 2 - handle both in ajax
function ajaxAndSubmitWithAjax(e){
e.preventDefault(); // Stop the default action of the submit button
var formData = $('#sample-form').serialize(); // Serialize the data
// Start ajax 1
$.ajax( {
type: "POST",
url: 'some url',
data: formData,
success: function( response ) {
console.log( response );
// Submit via ajax
$.get('some-url.php?' + $('#sample-form').serialize()); // Using GET
$.post('some-url.php', $('#sample-form').serialize()); // Using POST
}
} );
}
I am making a weather app and want my weather data to open on new page but it's currently opening underneath the search bar. I want it to redirect to another HTML-page with the weather data from the Javascript code when I push the search-button. How do I do that the easiest way?
This is my Javascript code that gets the weather data:
$(function() {
$("#city-form").on('submit', function(e){
e.preventDefault();
e.returnValue = false;
search($("#city-input").val());
});
function search(city){
$("#city").html("");
$("#description").html("");
$("#temp").html("");
$("#humidity").html("");
$("#wind").html("");
var query = {
'q' : city,
'lang': 'SE',
'units': 'metric',
'APPID' : '31fb7e0aa1f90896809571484a8b13cc'
};
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather",
type: 'get',
async: true,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
dataType: "json",
data: query,
error: function (request, status, error) {
alert(JSON.parse(request.responseText).message);
console.log(request.responseText);
},
success: function (data) {
// Logs server reseponse
console.log(JSON.stringify(data));
// Sends data for presentation
present(city, data);
}
});
}
function present(city, data){
$("#city").html(city);
$.each(data.weather, function(i, weather) {
$("#description").append("<img class='w-icon' src='http://openweathermap.org/img/w/" + weather.icon + ".png' />");
$("#description").append(weather.description + " ");
});
$("#temp").html(data.main.temp + " °C");
$("#humidity").html("Luftfuktighet: "+ data.main.humidity + "%");
$("#wind").html("Vind: "+ data.wind.speed + " m/s");
}
});
And this is my HTML-code with the search bar and weather data:
<form id="city-form">
<input type="text" id="city-input" class="form-control" placeholder="Sök på stad" required>
<button type="submit" id="submit-btn" class="btn btn-primary">Sök</button>
<input type="reset" value="Reset">
</form>
<div id="weather">
<div id="city"></div>
<div id="temp"></div>
<div id="description"></div>
<div id="humidity"></div>
<div id="wind"></div>
</div>
I recomend you create another page that receives the city as a query param.
myPage?city="london"
Code for redirect:
function search(city){
window.location.href = 'myPage?city=' + city
}
If you prefer open in a new tab: Open a URL in a new tab (and not a new window) using JavaScript
On the new page you recover the city from params
How to get the value from the GET parameters?
And do the ajax request the same way you do now, you gonna move the display info to the new page:
<div id="weather">
<div id="city"></div>
<div id="temp"></div>
<div id="description"></div>
<div id="humidity"></div>
<div id="wind"></div>
Hi I have a View Which Contains a ADDBasicDetailsForm (This JSP view is rendered using spring MVC)
BasicDetailView.jsp
<div data-bind="if: profileDto.basicDetailsDTO">
<div class="basicDetails">
Contact No :
<b data-bind="value: profileDto.basicDetailsDTO.contactNo"> </b>
contactMailId :
<b data-bind="value: profileDto.basicDetailsDTO.contactMailId"> </b>
</div>
</div>
<form id="BasicDetailsform" method="POST">
<fieldset class="contactMailId">
<input id="contactMailId"
type="text" placeholder="Mail Id" maxlength="32"
name="contactMailId"></input>
</fieldset>
<fieldset class="contactNo name">
<input id="contactNo"
type="text" placeholder="contactNo" maxlength="32" name="contactNo"></input>
</fieldset>
<fieldset class="buttons">
<button class="saveactionbutton" type="submit">SAVE</button>
</fieldset>
</form>
</div>
Inially contact no and conatct mail ID is not shown in UI. It should be shown when i submit the form and i am using knockout for automatic UI referesh.But It is not working
BasicDetails.js
function BasicViewModel() {
var self = this;
}
var viewModel = new BasicViewModel();
$(document).ready(function(){
$("#BasicDetailsform").submit(function(e)
{
var form = $(this);
e.preventDefault(); //STOP default action
var input = '{';
input += '"contactMailId":"'+$('#contactMailId').val()+'",';
input += '"contactNo":"'+$('#contactNo').val()+'"';
input += '}';
alert(input);
$.ajax({
type: "POST",
dataType: "json",
url : "addBasicDetails",
contentType: "application/json; charset=utf-8",
data: input,
dataFilter: function (response) {
return response;
},
async:false,
success: (function(data, textStatus, jqXHR) {
alert("ajax Success");
form.hide();
data = ko.toJSON(data);
alert("JSON Data in Alert"+data );
ko.mapping.fromJSON(data, {}, self);
ko.applyBindings(viewModel);
}),
error : function(data,textStatus,error){
alert("ajax failure");
}
});
});
});
My JSON response from server
{
"basicDetailDTO":{
"contactNo":"86878",
"contactMailId":
"rahuljain#gmail.com"
}
}
After the Form submission details are not getting reflected in my jsp view .
Please let me know where is the issue in my code.
I am Trying to upload file without reloading or redirecting page to other page.
I have tried...
upload.php
<form enctype='multipart/form-data' action='/' method='POST' class="AjaxSubmit" id='newwork' name='newwork'>
Choose New Work<br />
<input name='uploadednewwork' type='file' /><br />
<button id="btnFrmPost1" class="button" onclick="up()" >New Work</button>
</form>
script.js
function up() {
$('#btnFrmPost1').click(function() {
event.preventDefault();
var $form = $(this);
var url = "/subpages/upload_new_work.php";
var data = $form.serialize()
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: data,
success: function (resp) {
var jdata = eval(resp);
var $jAlrtSuccess = $('<div>' + jdata.responseText + '</div>');
$($jAlrtSuccess).dialog({modal:true});
},
error: function (xhr, status, error) {
var $jAlrtError = $('<div>' + xhr.responseText + '</div>');
$($jAlrtError).dialog({modal:true});
}
});
return false;
});
}
I have tried all this code...
but i wont get result...
can any one please tell me how to solve this problem...