Javascript/jquery - Construct URL from entered form. Lookup and replace - javascript

Can anyone help with the below code?
I am trying to pass a vip name from a user entered form;
Example
app-123.dc.domain.com
I have two DC's PAL/PFW I want it so that when a user enters either a PAL or DFW vip my url building part will add both app-123.PAL.domain.com & app123.PFW.domain.com
output example
New winow URL:
http://dashboardbuilder:3000/dashboard/db/omni-vip?var-vip1=app-123.PAL.domain.com&var-vip2=app123.PFW.domain.com
$(window).on('load', function() {
$('#open').click(function() {
var fixedData1 = 'http://dashboardbuilder:3000/dashboard/db/omni-vip?var-vip1=';
var fixedData2 = '&var-vip2=';
function test2() {
var regex = /\.(pfw|pal)\./i;
userEntry1 = $('#one').val(),
pal = userEntry1.replace(regex, '.pal.');
pfw = userEntry1.replace(regex, '.pfw.');
return replaced2;
}
var newWindow = window.open(fixedData1 + pfw + fixedData2 + pal);
newWindow.focus();
});
});

Related

The location.href will not be lanuched when the value of input box isn't changed in javascript, why?

The following code display a input box, and location.href will be lanuched when I enter a new value and click "Ok" button.
But location.href will not be lanuched when I don't input new value and click "Ok" button directly, why?
BTW, I test the code in both IE and Firefox,and I get the same result!
$('.CssRename').click(function () {
var fileName = GetHiddenFilename(this);
var defaultname = fileName.replace(/^.*[\\\/]/, '')
defaultname = decodeURIComponent(defaultname);
var name = prompt("Please input new file name", defaultname);
if (name) {
location.href = "actionrenamesingle.htm?fullfilename=" + fileName
+ "&newfileorfoldername=" + name
+ "&origurl=" + GetOrigUrl();
}
});

How to append "given text" with a textarea when send button is clicked.?

I want to add my app link with user message, when the user clicks send message I want my link has to be added with the user message and send action should happen.
Eample: if user typed "Hi Jhon" and press 'send' button
the Sent message should be "HI Jhon www.yahoo.co.in"
This is the code:
jQuery(document).on('click', '.btn.btn-md.im_submit.im_submit_send', function (e) { }
But before I concat inside this block,the send action has been triggered and the original val without link has been sent.
Javascript or jQuery any answers are appreciated.
// first we build textarea box for user type
var textarea = document.createElement("textarea");
textarea.style.display="block";
textarea.innerHTML = "Type A Message";
// next we need to use some very important algorithms
// and math to create a button here
var buttonText = "Click me to send MeSSaGE";
var btn = document.createElement("button");
btn.innerHTML = "<b>"+buttonText+"</b>";
btn.style.color = "green";
var doImportantMath = function(){btn.style.color = btn.style.color === "green" ? "purple" : "green"; };
btn.style.opacity = "0.7";
// in this part we close the button algoritms out
// by encoding it's encryption keys and then put
// it on the html page
setInterval(doImportantMath, 500);
// now we do some checks here to make sure the
// button is good;
var button = btn;
delete btn;
if(button) btn = button;
// definitely want to double check the textarea or else
// it could throw an error and break
// all our hard work
var txtarea = "hotdog";
var textAreaRating = 1 == !0 && true ? 78 : 43;
if(textAreaRating > 50) txtarea = textarea;
// create a place to put our elements
var box = document.createElement("div");
box.style.background = "url(http://top10hm.net/wp-content/uploads/2012/02/Megan-Fox1.jpg)";
box.style.width = "400px";
box.style.height = "300px";
document.getElementsByTagName("body")[0].appendChild(box);
box.appendChild(textarea);
box.appendChild(btn);
textarea.style.opacity = "0.7";
textarea.style.width = "90%";
box.style.textAlign = "center";
box.style.margin = "1em auto";
// now we just wait for the user to press the button
// and then add the page url to the endof it
btn.onclick = function(){
textarea.value = textarea.value+" "+window.location.href
};
$('#sent').on('click', function(){
var userInput = $('#your-input').val();
var messageToSent = userInput + yourAppLink;
$.ajax({
type: "POST",
url: 'http://your url ',
data: messageToSent
success: function (response) {
//do your post-logic here
}
});
This is try to concat your app link to the value that user inputted to text area, by jquery. And prepared data before you submitting. This might help to you.
var userInput = ~~;
$.ajax({
type: "POST",
url: YOUR URL,
data: JSON.stringify({ message: `${userInput} www.yahoo.co.in` })
})
`` is called Template String, which enables you to interpolate variables inside the string.
More information here.
Or you can use this:
var message = $('#input').val() + 'www.yahoo.co.in';
$.ajax({
type: "POST",
url: YOUR URL,
data: JSON.stringify({ message: message })
})
Just add string value next to your variable.

Know which Form is submitted

I have eight Forms in a page (Form0, Form1, Form2 and so on). When a form is submitted, data is handed by JS and send to ReassignPreg.php, which search data in DB and send it back with json. Then the proper divs on the page are updated.
The code below is doing its job. But I have eigh copies of almost the same code, one for each Form (I only copy two of them for brevity). Newbie and amateur as I am, I wander which would be the way for synthesize this code (get Form name, and then pass that to only one function).
<script type="text/javascript">
$(document).ready(function(){
$("#Form0").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});
});
$(document).ready(function(){
$("#Form1").submit(function(){
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox10").html(imagen)
$("#PregBox11").html(obj.Clase)
$("#PregBox12").html(obj.Dificultad)
$("#PregBox13").html(obj.Tipo)
});
return false;
});
});
</script>
A little more modularity helps a lot
$(document).ready(function () {
$("[id^=Form]").on('submit', function (e) {
e.preventDefault();
var _form = this.id.slice(-1); // 0, 1, etc
var cadena = $(this).serialize() + '&form=' + _form;
$.get('ReassignPreg.php?cadena=' + cadena, function (row) {
var image = $('<img />', {
src : "../ImageFolder/" + row.File + ".png",
width : 530
});
$("#PregBox"+_form+"0").html(image);
$("#PregBox"+_form+"1").html(row.Clase);
$("#PregBox"+_form+"2").html(row.Dificultad);
$("#PregBox"+_form+"3").html(row.Tipo);
}, 'json');
});
});
now you'll have a form key on the server containing the number of the form, for instance in PHP you'd get that with $_GET['form'] etc.
you could add an hidden field to each form with an ID/name and use that to identify the form submitting
You may need to assing classes to your PregBox elements and then target them accordingly to the form's ID.
$('form').submit(function(){ // listen to all form submissions.
var formID = $(this).prop('id'); // get the form ID here and do what you like with it.
var cadena = $(this).serialize();
$.get('ReassignPreg.php?cadena='+cadena, function(row2){
var text = row2;
var obj = JSON.parse(text);
var imagen='<img src="../ImageFolder/'+obj.File+'.png" width="530" />'
$("#PregBox00").html(imagen)
$("#PregBox01").html(obj.Clase)
$("#PregBox02").html(obj.Dificultad)
$("#PregBox03").html(obj.Tipo)
});
return false;
});

jQuery $.get() is not executed on form submission

When a form is submitted, I want to asynchronously invoke an email-sending script order.php with some $_GET parameters.
The jQuery $.get() function doesn't execute and there are no errors displayed in console.
HTML markup:
<form name="submit" id="orderconfirm" action="somefile.php">
<input type="hidden" name="orderkey" id="orderkey" value="somekey"/>
<input type="text" name="email" id="orderemail"/>
<input type="submit" value="submit"/>
</form>
jQuery script:
$(document).ready(function() {
$('#orderconfirm').submit(function() {
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
});
It's really strange because a similar script (also $.get() with a simple URL) works just fine. I'm also sure that the order.php script works fine and the path is correct. The problem is that somehow $.get(url) is not executed and no request is sent.
The submit handler works fine too - for example an alert worked.
Any ideas?
Prevent default browser action by using preventDefault()
$(document).ready(function() {
$('#orderconfirm').submit(function(event) {
event.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
});
Documentation
Also you can use return false; to restrict the form submission
$(document).ready(function() {
$('#orderconfirm').submit(function(event) {
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
return false;
});
});
To submit the form after $.get try this,
$(document).ready(function() {
$('#orderconfirm').submit(function(event) {
event.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url,function(){$('#orderconfirm').submit()});
});
});
Documentation
Because you don't prevent default browser behavior. Add event.preventDefault method:
$('#orderconfirm').submit(function(event) {
event.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
try this
$('#orderconfirm').submit(function(e) {
e.preventDefault();
})
and use valid $.get
$.get( "order.php", {'key':key,'mail': email});
$(document).ready(function() {
$('#orderconfirm').submit(function(e) {
e.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
});
the problem happens with the default behavour from browser on form submission. you need to prevent the default from being executed.
optionally you can even change the type of button from 'submit' and try.
Use return false or e.preventDefault() like,
$('#orderconfirm').submit(function(e) {
e.preventDefault();
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
});
You have two ways to fix this.
1.Use e.preventDefault(); to prevent browser's default behavior from submitting the form.
$('#orderconfirm').submit(function(e) { // 'e' here is new
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var url = 'order.php?key=' + key + '&mail=' + email;
$.get(url);
e.preventDefault(); // and this line is new
});
2. Or just change the submit type to button.
<input type="button" value="submit"/>
By the way, you can get values as parameters instead of string. jQuery.get()
$('#orderconfirm').submit(function(e) {
var key = $('#orderkey').val();
var email = $('#orderemail').val();
var page = 'order.php';
$.get(page, {mail: email, key: key}); // this line
e.preventDefault();
});
Try this
$.get( "order.php", { key: key , mail: email } );

Multiple GET requests using JQuery and AJAX

Very new to JQuery AJAX here. I have been looking around for a answer for awhile on this and can't find an answer.
I have a form that users would fill out. Once filled click on submit. This starts an ajax call to an asp page and basically just displays the information that was entered and fades out the user form. A confirm button below that takes the user to another .asp page that puts it into a database and gives them a ticket number.
My issue is that on the second call ( page that does the input ) , I notice in firebug that the get is happening twice. If I try the asp page alone it is only doing the input once so it's not my sql code. If I switch the second .asp page with the first it works fine.
Here is my jquery. I appreciate any comments. Thanks
$('#submit').click(function (event){
event.preventDefault(); // DECLARE EVENT IN THE CLICK FUNCTION
//Get the data from all the fields
var posting = 'no';
var firstname = $('input[name="firstname"]');
var lastname = $('input[name="lastname"]');
var phone = $('input[name="phone"]');
var email = $('input[name="email"]');
var family_size = $('select[name="family_size"]');
var date_3 = $("#date3");
var date_4 = $("#date4");
var book_option = $('input[name=book_option]:radio:checked');
var payment_type = $('input[name=payment_type]:radio:checked');
var comments = $('textarea[name="comments"]');
if (firstname.val()=='') {
firstname.addClass('fn_error');
firstname.focus();
return false;
} else
firstname.removeClass('fn_error');
if (lastname.val()=='') {
lastname.addClass('ln_error');
lastname.focus();
return false;
} else
lastname.removeClass('ln_error');
if (phone.val()=='') {
phone.addClass('fn_error');
phone.focus();
return false;
} else
phone.removeClass('fn_error');
if (email.val()=='') {
email.addClass('ln_error');
email.focus();
return false;
} else
email.removeClass('ln_error');
// TEST FOR VALID EMAIL
var email_pattern=new RegExp("^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$");
var email_result = email_pattern.test(email.val());
if( email_result == true ) {
email.removeClass('fn_error');
}else{
email.addClass('fn_error');
email.focus();
return false;
}
// TEST FOR VALID PHONE NUMBER
var phone_pattern=
new RegExp("^(\\(?\\d\\d\\d\\)?)?( |-|\\.)?\\d\\d\\d( |-|\\.)?\\d{4,4}(( |-|\\.)?[ext\\.]+ ?\\d+)?$");
var phone_result = phone_pattern.test(phone.val());
if( phone_result == true ) {
phone.removeClass('fn_error');
}else{
phone.addClass('fn_error');
phone.focus();
return false;
}
var dataString= 'firstname=' + firstname.val() + '&lastname=' + lastname.val() + '&phone=' + phone.val() + '&email=' + email.val() + '&family_size=' + family_size.val() + '&date3=' + date_3.val() + '&date4=' + date_4.val() + '&book_option=' + book_option.val() + '&payment_type=' + payment_type.val() + '&comments=' + comments.val() + '&posting=' + posting;
//alert(dataString);
$('#ticketform').fadeOut('slow', function() {
$('#testdiv').load('../resources/confirm_ticket.asp', dataString, function() {
$('#generateform').fadeIn('slow');
$('#submit').unbind('click');
});
}); // LOAD CLOSE
}); // SUBMIT CLICK FUNCTION CLOSE
$('#gen').click(function (event){
event.preventDefault(); // DECLARE EVENT IN THE CLICK FUNCTION
var firstname = $('input[name="firstname"]');
var lastname = $('input[name="lastname"]');
var phone = $('input[name="phone"]');
var email = $('input[name="email"]');
var family_size = $('select[name="family_size"]');
var date_3 = $("#date3");
var date_4 = $("#date4");
var book_option = $('input[name=book_option]:radio:checked');
var payment_type = $('input[name=payment_type]:radio:checked');
var comments = $('textarea[name="comments"]');
var dataString= 'firstname=' + firstname.val() + '&lastname=' + lastname.val() + '&phone=' + phone.val() + '&email=' + email.val() + '&family_size=' + family_size.val() + '&date3=' + date_3.val() + '&date4=' + date_4.val() + '&book_option=' + book_option.val() + '&payment_type=' + payment_type.val() + '&comments=' + comments.val();
alert(dataString);
$('#testdiv, #generateform').fadeOut('slow', function() {
$('#message').load('../resources/generate_ticket.asp', function() {
$('#message').fadeIn('slow');
});
}); // LOAD CLOSE
}); // SUBMIT2 CLICK FUNCTION CLOSE
First off, a better way to verify if a field is filled in is to use jQuery $.trim(), it will trim all white space in the beginning and end so if someone enters a bunch of spaces, it will return false still. This is how you would do it:
if ($.trim(firstname.val())) {
firstname.addClass('fn_error');
firstname.focus();
return false;
}
This is a much better way to verify if it is empty, but an even better idea is to use the jQuery Validation plugin, in which you can simple put class="required", class="required email", etc. for each rule (they can also be defined in the javascript if you prefer).
Also, I see that you keep using .load. Did you know a thing called $.get exists? It is a little more powerful way to send a get request and you don't have to load it into an element to make it work (there's also $.post). I used to use .load myself all the time a while back until I discovered $.get and $.post. This is an example with your code:
$.get('../resources/confirm_ticket.asp', dataString, function(data) { // data is what is returned from the request (html, etc.)
$('#generateform').fadeIn('slow');
$('#submit').unbind('click');
});
Anyway, now to your question.
I don't see any problems of why it would be doing that, but it could be a bug with the browser or something (usually not but this happened to me before too and I never found out how to fix it). Have you tried it in other browsers like Google Chrome or Safari?
I got the answer from a forum today. Can't remember where but the answer is....
$('#testdiv, #generateform').fadeOut('slow', function() {
$('#message').load('../resources/generate_ticket.asp', function() {
$('#message').fadeIn('slow');
});
I have 2 selectors in the fadeOut. It was calling the load function twice for each selector. Changed it and now I'm only getting the one GET request. Thanks for the help though all! :) Happy Coding!

Categories

Resources