Popup using jQuery? - javascript

I'm trying to do a pretty simple thing, I believe. I need to popup a success confirmation dialog after a user clicks to add someone to his friends list. Simply there's an add link on the page with the url (mysite.com/add/friendname). I needed to make issue this request asynchronously so I used jQuery.ajax built-in function to send the request. Take a look at the following code:
$(document).ready(function() {
$('.track_links').click(function() {
if (confirm("are you sure you want to track <firstname lastname>?")) {
$.ajax({
type: "GET",
url: this.href,
success: function() {
alert("Congratulation! you're now tracking <firstname lastname>");
},
error: function() {
alert("Oops! An error occured, plz try again later!");
}
});
return false;
}
else {
return false;
}
});
});
Now, here's what I need to do in short:
1- I need to use an already designed Html form as the success or failure confirmation message, instead of just alerting!
2- I also need to replace a placeholder (###username###) on that html page with the actual user name (firstname space lastname) which is the value of another field on the document. How to manipulate this html before poping it up on the client?
p.s: My Html/Javascript skills is totally awesome ;) (well, not really)!

For the first part
You can use the
show
function to show a div in the ajax success function.
$("#divResult").show();
if divResult is the id of the div to be shown
For the second part
you can get the value of first name and last name using
$("#txtFirstname" ).val();
and
$("#txtLastname" ).val();
if your first name text box id is txtFirstname and last name text box id is txtLastName

This is how I setup an Acknowledgement dialog, which could quickly be modified to be a confirmation for an action like yours.
http://professionalaspnet.com/archive/2009/06/02/Displaying-a-Confirmation-Dialog-with-the-JQuery-UI-Dialog.aspx

For the Form, I would suggest the html() Method, which injects raw HTML you have to provide. Since you already have it, you can give it to the Method via parameters.
For the Placeholder Part, I would suggest the val() Methods, coupled with Javascript's built-in regex functions.
If your placeholder is "###firstname###", then you should try something like
var firstname = jQuery('input#firstname').val();
var lastname = jQuery('input#lastname').val();
var text = jQuery('span#ThePlaceMyPlaceholderIsAt').text();
text = text.replace(/\#\#\#firstname\#\#\#/,firstname);
text = text.replace(/\#\#\#lastname\#\#\#/,lastname);
jQuery('span#ThePlaceMyPlaceholderIsAt').text(text);

Related

AJAX call to differrent page in same domain works, but does not load everything

So, a little context: I'm trying to do an ajax call to a webpage in the same domain to get a telephone number to show up as soon as I specify the client on the first page. I do get the data but it seems like not the whole page is loaded in.
I need this:
<div id="1">
<div id="2">
<a id="ineedthis"></a>
</div>
</div>
but instead it's giving me this:
<div id="1">
</div>
This is a website that I'm writing a script for, since I can't edit the source code. This is managed from our ERP program and is pretty limited in customizability.
My best guess is that the target webpage is also still loading in the information from the database, but my ajax call returns the webpage before that happens.
Here is my js code:
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
console.log(href);
if(href !== "https://52134.afasinsite.nlundefined"){
$.ajax({
url:href,
type:'GET',
success: function(data){
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
}
});
}
}
setInterval(updateClasses, 1000);
I'm running this once per second to check for a change in the input field on the first page, I don't know if there is a better way for this?
Firstly, you could try running the script/function once a change has been detected.
Something along the lines of :
$('input[name="{inputFieldName}"]').on('change',function(){
updateClasses();
});
//You can also use "keyup" instead of "change", depending on the type of action that you are looking for.
For the Ajax, you could try using Promises. Basically, set up the ajax call and then set a ".done" case for the ajax call has been completed and received some result. A ".fail" can also be used to catch non-code related issues.
function updateClasses(){
var link = $('a[href^="/organisatie-beknopt-prs?BcId="]');
var href = "https://52134.afasinsite.nl" + link.attr("href");
var getPhonePromise = $.ajax({
url: href
});
getPhonePromise.done(function(data) {
var tel = $(data).find("#P_C_W_Title_Content");
console.log(tel);
});
getPhonePromise.fail(function(errRes) { console.log(errRes);});
}

place results in a textbox after click

i'm working on an auto complete with jquery which is working perfectly. the results get displayed as the user types. Now the problem is when the user starts typing and the results appear, when the user clicks on the desired results, it doesn't get placed in the textbox
JS
$(function(){
$(".search_tab").keyup(function()
{
var searchid = $(this).val();
var dataString = 'fname='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "http://localhost/myapp/search.php",
data: dataString,
cache: false,
success: function(html)
{
//console.log(html)
$("#result").html(html).show();
}
});
}return false;
});
$('.search_tab').click(function(){
jQuery("#result").fadeIn();
});
});
HTML
<input type="text" class="search_tab" placeholder="Search" autocomplete="off">
<div id="result"></div>
You'll need to do some event delegation over the items that get placed into the div#result element. You'll want something like this:
$('#result').on('click', 'RESULT_ITEM', function (event) {
$('input.search_tab').val(event.target.innerHTML);
});
Where RESULT_ITEM is a selector that matches the individual items that are listed in the autocomplete results.
While i dig into this have you considered using jQuery UI to acomplish this?
https://jqueryui.com/autocomplete/
This is a nice and polished way of doing exactly what you are wanting.
Not quite sure why I am getting down voted really as my suggestion is a perfectly valid solution to this problem...
That being said here is a working fiddle for you.
https://jsfiddle.net/wxr5y5gu/
The main part you seem to be missing is something like this:
$('#result').on('click','li',function(){
/* I used li as the element as im unsure what your response html looks like */
let newValue = $(this).text();
$('.search_tab').val( newValue );
$('#result').html('').hide();
});
That will clear the results, set the clicked value, and hide the results box for you.
That contains a working soution for you. As i dont have access to AJAX your local resources I had to extrapolate and create my own auto fill to show how it works in principal however i can certainly help you tailor the solution to your needs.
This solution uses your code and is compatible with all current jQuery versions.

Having issues calling an ID after I have appended data from an ajax call

Ok,
So I have a .on click event which is called to an ajaxed script. The script returns a set of HTML information.
Now, what I seem to be having an issue with and maybe I am just not typing the right search terms in for this so my apologies if this was answered already.
When the html is appended to the correct box, the user is then able to click a link on that box, drop down the box and see a new input box. The user should be able to type the text in and hit the enter key and it should work.
When I run an inspect element, I do see the element's ID properly inserted, but it is like javascript doesn't even recognize the new element id.
UPDATE: I am really not sure why you need code to be able to answer this question, however here it is. The code works normally unless the above happens so yes I am appending it, and yes I am SURE i am appending it, please make sure to read everything before posting a comment, thanks!
$('body').on('keypress', '.peapComment', function(event) {
if(event.which == 13) {
var peap_id = $(this).attr('rel');
var comment = $(this).val();
$.ajax({
type: "POST",
url: "index.php",
data: {
page: "postPeapComment",
peap_id: peap_id,
comment: comment,
}
}).done(function(msg) {
console.log(msg);
$('#comment_' + peap_id).append(msg);
});
console.log('Send to Peap #' + peap_id + ': ' + comment);
$('#commentbox_' + peap_id).val('');
}
});
I have tested your code, and it seems to work without problems for me. My assumption would be that the data returned from your ajax call, is failing to return the proper "Peap_ID" or not returning anything all around, as this is the only way I can reproduce what you have claimed your error is, otherwise the code you have posted looks great.

How to submit the ID of input field

Is it possible (and if so, how) to submit the ID of the input field in focus when clicking it?
I've made an autosave-feature in a online-tool, that saves every time an input field is blurred.
However, since the page itself is updated on every field blur, it loses focus when another field is clicked, so I would like it to submit the ID of the field, just clicked so that I can set it in focus, manually.
(off-topic) I don't use jQuery anymore when updating, since I need the page to process a lot of numbers, serverside... so in my opinion, it's most convenient that it works as described.
I've done some researching and ended up with two possibilities:
focusobject = $(':focus');
and
document.activeElement
but when doing a JS alert, it just says [object Object] and [object HTMLBodyElement] instead of "fieldEmail"
Any ideas?
UPDATE
I previously used this to update in the background:
function writeNow(datastring) {
$.ajax( {
type: 'POST',
url: 'update.php',
data: datastring,
success: function(data) {
// Do nothing
}
});
}
This updates the fields just fine on onBlur, but the page itself calculates a lot of results, based on several class methods on runtime. If I use AJAX to update the database values, I don't see how I can set the class variables and display the correct result without reloading.
When you click on an element, it's more likely that it will get focus (unless there is some wizardry that prevents the click from requesting the focus). You may simply handle the onclick event of an input group and save it.
Let imagine some input fields that all have classname txt-group-1:
Plain JS
var lastFocus = null;
if (document.activeElement.className == 'txt-group-1') {
lastFocus = document.activeElement.id; // get the field that already has focus
}
var inputs = document.getElementsByClassName('txt-group-1');
for (var i=0;i<inputs.length;i++) {
inputs[i].addEventListener('click', function(evt){
alert(this.id+' has focus!');
lastFocus = this.id;
},true);
}
jQuery
var lastFocus = null;
if (document.activeElement.className == 'txt-group-1') {
lastFocus = document.activeElement.id; // get the field that already has focus
}
$('.txt-group-1').click(function(evt){
alert(this.id+' has focus!');
lastFocus = this.id;
});
Then, lastFocus will always have the ID of the last element that had focus so you can put it back if needed.
UPDATE:
in case of a CMS that needs to save the fields:
Your best friend in that situation will be ajax. The idea is to be able to save the new value in database without having to refresh the whole page, hence stopping any action that goes after.
I suggest that you take a look at the method that saves the fields and optimize it in a way that it doesn't need to refresh the page:
$.ajax({
url: "save.php",
data: {inputFieldName:'txtEmail', inputFieldValue:'foobar#mail.com'}
})
.done(function(data) {
console.log('saved'); // after the request is complete
});
Any post-save client-side action may be specified in the .done event. It's also possible to get a response from the server-side script that execute your request.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<input name="testfield" type="text" id="mtTextField" onClick="alertId(this.id);">
<script type="text/javascript">
function alertId(getid)
{
alert(getid);
}
</script>
</body>
</html>
Try out this code.
Use's Harsha's snippet except hang it on the "onchange", otherwise you will create an issue with tab navigation. You will have to modify your save function slightly so it won't trigger with every character.
Also instead of updating the entire page I suggest using AJAX.

Jquery stop submit and get data from form

I'm trying to use jquery to get data from a form and stop the form submiting using this code:
$form = $('form#signup')
$form.submit(function(event){
event.preventDefault();
var $input=$('#signup :input')
console.log($input.username)
alert($input.username)
})
but the form still posts the data and the alert box does not appear.Also firebug brings up the error $ is not defined and Node.js crashes
the form (writen in jade):
html
head
script(src='javascripts/signupValidation.js')
script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js')
script(src='javascripts/validator.js')
body
form(id='signup',method='post',action='/signup')
label Firstname
input(type='text', name='firstname')
label Lastname
input(type='text', name='lastname')
label Username
input(type='text', name='username')
label Password
input(type='password', name='password')
label Password again
input(type='password', name='password2')
label Email
input(type='email', name='email')
input(type='submit',value='Sign up', onclick="")
If your form-related JS is in the file signupValidation.js, you need to move the script call that includes that file to be after the jquery include.
I'd probably clean up the form code a tiny bit, too:
$('form#signup').on('submit', function(event){
event.preventDefault();
var $input = $(this).find('[name=username]');
console.log($input.val());
alert($input.val());
})
You might be interested in looking at .serialize(), too.
Problem with your code [not issue with form submission]
$input.username is not valid jQuery to reference another element.
var usernameInput = $input.filter('[name="username"]');
Looks like you are not adding the code on document.ready so you probably are attaching it to nothing. Change it to be:
jQuery( function() {
$form = $('form#signup');
$form.submit(function(event){
});
}
Also looks like you are including the validation code before the jQuery code. I bet looking at the JavaScript console in the browser has some nice error messages.
You need to prevent the form from submiting with return false :
$form.submit(function(event){
var $input=$('#signup :input');
console.log($input.username);
alert($input.username);
// data = array of all the information collected from the input tags
//data = $form.serizalize(); will also work
data = $(this).serialize();
return false;
});
data would be an array with the information you need, i recommend console.log(data) so you can see all of it's structure and then you can use it as you wish for example:
if(data.something == anything){
doThis();
}
And i highly recommend adding an ; at the end of your javascript sentences
Like other people I've had luck with code like this:
$(document).ready(function(){
// Prevent form submission
$( "form" ).submit(function( event ) {
event.preventDefault();
});
});
To prevent form submission. But also, these days it's pretty common that there are scripts on the page which go behind your back and add little candy-coated features like animations and "shake-off" effects to HTML forms. It's possible for those script to get in the way in situations like this, because they might have their own javascript-fu for submissions.

Categories

Resources