Using jAlert as a simple Prompt - javascript

I'm using with satisfaction the library jAlert v4 available here
But I noticed that is not possible to use this library such as a simple "prompt" (that is a simple alert with a textbox) as shown in the following code:
var qnt = prompt("Insert")
Also this library is excellent because it automatically recognize all "alert()" functions in my code and applies his styles without any further implementation (it needs only to add its libraries inside <head> tag).
I discovered that there is also the "jQuery Alert Dialogs" library for my purpose, but it isn't customizable as jAlert v4.
So I would like to know if is possible to use the same library (jAlert v4) for my purpose, because I like the jalert customization (for ex. themes and animations) and it is very easy to use.
And I want to keep the same style like my jAlert as picture below: jAlert example but with a input TextBox.

That library is overriding the browser's built-in alert() function. You can do the same with prompt(), and have it open a jAlert with a text box on it.
window.prompt = function(title, value){
$.jAlert({
# Add an input field
'content': '<form><label>'+title+'</label><input value="'+(value||'')+'"></form>'
# Add the buttons or whatever else you need to the jAlert
});
};

The browser dialog stuff, such as alert, confirm and prompt are all blocking. JavaScript execute stops as those run.
There is simply no way to reproduce that behavior in external code, which means that one has to resort to using callbacks.
For some things, such as alert it may not be an issue .. if the code continues while the alert is still displayed, but it will fall apart if you try to show several alerts in a row.
For prompt and confirm, however, you will have to restructure your code.
I did a quick read of the jAlert docs and I saw both alert and confirm -- they didn't seem to have a prompt replacement, so I couldn't show their demo code
It might be worth checking out this library instead:
http://alertifyjs.com/

Yes, you can. If you just put the input box into the content, that will not appears, it's true. This is why you have the onOpen callback:
$.alertOnClick('.getTopClose', {
'title':'Textbox example',
'content':'', //Add nothing to the content
'onOpen': function(alert){
//This is the important part!
//Append a text input to the class .ja_body
$('.ja_body').append('<input type="text" name="something" value="" />');
}
});

I find a solution for my issue. And It's simply because always using the same jalert library. In my cause I use the returned value of my alert to perform an UPDATE via ajax. This is my code:
$.jAlert({
'title': 'Inserimento numero colli',
'content': '<form style="text-align:center;"><label>Quantita</label><br><input id="id_qnt" type="text" style="text-align:center"></form>',
'btns': [
{
'text': 'Save',
'closeAlert': 'false',
'onClick': function (e, btn) {
var item = btn.parents('.jAlert'),
form = item.find('form'),
error = false;
var field = form.find('input:text').val();
if (field == 'undefined' || field == '') {
error = "Empty quantity!";
}
if (!($.isNumeric(field))) {
error = "IsNan!"
}
if (field < 0) {
error = "IT'S < 0"
}
if (error) {
errorAlert(error);
return false;
}
// 'field' is the returned value... such as when using 'prompt'
// In my case I use it for AJAX
var obj = {};
obj.value = field;
$.ajax({
type: "POST",
url: "Master.aspx/UpdateItem",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
successAlert('SUCCESSFULLY SENT!', r.d);
}
});
// DYNAMICALLY CHANGE VALUE INSIDE PAGE change clicked_id by passing your id
document.getElementById(clicked_id).textContent = obj.value;
}
},
{
'text': 'Cancel'
}
]
});
It looks like this screenshot
I hope will be helpful to everyone!

Related

Ajax call inside of function

I am working inside of an Oracle package. I am trying to use an AJAX call to call a procedure from a button click. The ajax call is inside of a function. I am not getting any syntax errors from Oracle or when I'm using the browsers debug mode so I'm not sure what the problem is. Function is below.
htp.p('
function ApplyTest(_ht) {
var _inst = "";
var _pidm = '||v_web_pidm||';
var _inst = document.getElementById("Test").value;
alert("Heat Ticket value is: " + _ht);
alert("the instance is: " + _inst);
var resp = confirm("Are you sure you want patch applied to TEST8?");
if (resp == true) {
alert ("user pidm is: " + _pidm);
return $.ajax ({
type: "POST",
cache: false,
dataType: "json",
url: "gyapatch.p_update",
data: {"v_instance" : _inst, "v_ht" : _ht},
success : function(data) { alert("success"); }
});
alert("Got here");
alert("value: " + _inst);
window.location.reload;
alert("got to the end");
} else {
return;
}
}
');
code for the button is:
<button name="TestApply" id = "Test" onclick="ApplyTest('||val_patch.heat_ticket||')" type="button" value="T">Apply to TEST8</button>'
When I try to return the ajax call nothing is happening and I can't even reach the "Got Here" alert. When I remove the "return" keyword, I can reach the alerts but either way, nothing is happening. GYAPATCH.p_update is the package/procedure I wish to have executed when this is ran
I'm not sure what the problem is. Any help on this would be greatly appreciated. Thanks in advance.
So after a couple of hours, I had figured out the problem. This was more of a learning lesson as the issue was pretty simple. I needed to remember that I was working inside of an Oracle database AND also using WebTailor. The code posted above is correct. It turns out that the procedure I was trying to call (p_update) was not registered.
WebTailor allows you to build web applications utilizing Banner. In WebTailor, any pages that are used (usually stemming from a package.procedure), need to be registered or else they are not recognized.
I found this while debugging. Under the Network tab in my debugger, I noticed that when I click my button, I am getting a 404 error when my package.procedure is called. So I then realized it couldn't find my package and then proceeded to check if it was registered. This was a simple, silly error on my part. I am grateful for the feedback, but this will probably serve as a learning lesson or reminder to anyone trying to use ajax while working with Banner data.

ASP getting the value of a variable rather than a reference with Ajax

Currently I've been stuck on this code for almost two days now looking up everything I can on it but nothing I've tried has quite panned out, this could partly be due to me implementing it incorrectly or something else, but I figured I would finally ask. I should start by saying that I'm inside of a fancybox. The value of true that I want bIsError to be, shows up in console.log, however window.alert shows me that it's set to false. I did notice that the value changes once I run through my code. For example - If the username is incorrect it returns false then sets bIsError to true and displays an error message. However I just need it to return true and then give the error so that my code works. Anyways, here's my code, thanks for any feedback anyone will have as well, I really appreciate it.
if (typeof bFirstLoginPrep == 'undefined') {
var bFirstLoginPrep = true;
}
if (typeof $ != 'undefined') $(function () {
$(".ajaxformsubmit").unbind("click");
$(".ajaxformsubmit").click(function (event) {
setTimeout("lfSubmitForm()", 100);
return false;
});
});
function lfSubmitForm()
{
$form = $(".ajaxformsubmit").parents("form");
response = $.ajax({
url: $form.attr("action"),
type: "POST",
async: false,
data: $form.serialize()
}).responseText;
var responseList = false;
if (responseList == <%=LCase(bisError)%>) {
lfLoginSuccess();
} else {
$("#fancybox-inner").html(response);
$.fancybox.resize();
}
}
DinoMyte
<%=bIsError%> gives you the value of an instance server-side variable. If you are updating it via Ajax, it wouldn't work because you are probably making an ajax call to a pagemethod which is declared as static and static methods cannot manipulate the instance members of the page. In order to make it work with ajax, you need to return bIsError as part of the ajax response.
Amos
Yes, as DinoMyte says. Also you could set blsError as a session variable in this script before it is sent to the browser and then the script that the ajax calls can read it server-side.

Clear dropdown using jQuery Select2

I'm trying to programmatically clear a drop down using the fantastic Select2 library. The drop down is dynamically filled with a remote ajax call using the Select2 query option.
HTML:
<input id="remote" type="hidden" data-placeholder="Choose Something" />
Javascript:
var $remote = $('#remote');
$remote.select2({
allowClear: true,
minimumInputLength: 2,
query: function(options){
$.ajax({
dataType: 'json',
url: myURL + options.term,
error: function(jqXHR, textStatus, errorThrown){
smoke.alert(textStatus + ": server returned error on parsing arguments starting with " + options.term);
},
success: function(data, textStatus, jqXHR){
var results = [];
for(var i = 0; i < data.length; ++i){
results.push({id: data[i].id, text: data[i].name});
}
options.callback({results: results, more: false});
}
});
}
});
Unfortunately, the call to $remove.select2('val', '') throws the following exception:
Uncaught Error: cannot call val() if initSelection() is not defined
I've tried setting the attr, setting the val, text and the Select2 specific data function. Can't seem to make the guy clear and work in a radio button like manner. Anyone got suggestions?
This works for me:
$remote.select2('data', {id: null, text: null})
It also works with jQuery validate when you clear it that way.
--
edit 2013-04-09
At the time of writing this response, it was the only way. With recent patches, a proper and better way is now available.
$remote.select2('data', null)
In case of Select2 Version 4+
it has changed syntax and you need to write like this:
// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});
// clear and add new option
$("#select_with_data").html('').select2({data: [
{id: '', text: ''},
{id: '1', text: 'Facebook'},
{id: '2', text: 'Youtube'},
{id: '3', text: 'Instagram'},
{id: '4', text: 'Pinterest'}]});
This is the proper one, select2 will clear the selected value and show the placeholder back .
$remote.select2('data', null)
For select2 version 4 easily use this:
$('#remote').empty();
After populating select element with ajax call, you may need this line of code in the success section to update the content:
success: function(data, textStatus, jqXHR){
$('#remote').change();
}
Using select2 version 4 you can use this short notation:
$('#remote').html('').select2({data: {id:null, text: null}});
This passes a json array with null id and text to the select2 on creation but first, with .html('') empties the previously stored results.
You should use this one :
$('#remote').val(null).trigger("change");
Method proposed #Lelio Faieta is working for me, but because i use bootstrap theme, it remove all bootstrap settings for select2. So I used following code:
$("#remote option").remove();
I'm a little late, but this is what's working in the last version (4.0.3):
$('#select_id').val('').trigger('change');
This solved my problem in version 3.5.2.
$remote.empty().append(new Option()).trigger('change');
According to this issue you need an empty option inside select tag for the placeholder to show up.
These both work for me to clear the dropdown:
.select2('data', null)
.select2('val', null)
But important note: value doesn't get reset, .val() will return the first option even if it's not selected. I'm using Select2 3.5.3
I found the answer (compliments to user780178) I was looking for in this other question:
Reset select2 value and show placeholdler
$("#customers_select").select2("val", "");
From >4.0 in order to really clean the select2 you need to do the following:
$remote.select2.val('');
$remote.select2.html('');
selectedValues = []; // if you have some variable where you store the values
$remote.select2.trigger("change");
Please note that we select the select2 based on the initial question. In your case most probably you will select the select2 in a different way.
Hope it helps.
For Ajax, use $(".select2").val("").trigger("change"). That should solve the issue.
this code remove all results for showing new list if you need:
$('#select2Elem').data('select2').$results.children().remove()
For example, in the list of provinces and cities, when the province changes and we click on the city input, the list of old cities is still displayed until the new list is loaded.
With the code I wrote, you can delete the old list before calling ajax
Since none of them all worked for me (select2 4.0.3) is went the std select way.
for(var i = selectbox.options.length - 1 ; i >= 0 ; i--)
selectbox.remove(i);
You can use this or refer further this https://select2.org/programmatic-control/add-select-clear-items
$('#mySelect2').val(null).trigger('change');
This is how I do:
$('#my_input').select2('destroy').val('').select2();

Jquery autocomplete with jquery 1.4

Referring to this post and this one. I'm trying to implement tag search for my blog/website something similar to SO tag system using jquery autocomplete plugin, I'm using jquery 1.4 latest version so I'm not sure whether it works with it or not, I've used this plugin before once. So without further jibr-jabr here is my html for autocomplete :
<input id="post-tags" class="ac_input" type="text" autocomplete="off" value="" name="post_tags"/>
Here is my javascript:
<script type="text/javascript">
$(document).ready(function(){
function findValueCallback(event, data, formatted) {
$("<li>").html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result");
}
function formatItem(row) {
return row[0] + " (<strong>id: " + row[1] + "</strong>)";
}
function formatResult(row) {
return row[0].replace(/(<.+?>)/gi, '');
}
$("#post_tags").autocomplete("http://localhost/tags/filter/", {
width: 260,
selectFirst: false
});
$("#clear").click(function() {
$(":input").unautocomplete();
});
});
</script>
I'm sure my php part is ok, it works like this when I manualy type the url http://localhost/tags/filter/p
I returns the following :
php (1)
asp (1)
Meaning all tags containing p, for now I have only these two. My question is, what am I doing wrong, I'm really stuck on this one, I've changed things around so many times now I can't think of anything new I'd like to do. Thank you
The trick is to use post instead of get, when using get / gets erased but when using post complete thing is passed so the autocomplete needs some adjustments(extra one line) here it is :
$.ajax({
type: "post", // This is the new line
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
Everything worked like a charm now..

Issue with jQuery $.get in IE

I have a login form which appears at the top of all of my pages when the user is logged out. My current jQuery/javascript code works in Firefox 3 but not IE 7. The code queries a page which simply returns the string "true" or "false" depending on whether the login was successful or not. Inside my $.ready() function call I have the following...
$('#login_form').submit(function() {
var email = $('input#login_email').val();
var pw = $('input#login_password').val()
$.get('/user/login.php', { login_email: email, login_password: pw }, function(data) {
alert('get succeeded');
if(data == 'true') {
$('#login_error').hide();
window.location = '/user/home.php';
alert('true');
}
else {
$('#login_error').show();
alert('false');
}
});
alert('called');
return false;
});
In FF, I am successfully transferred to the intended page. In IE, however, the below alerts "called" and nothing else. When I refresh the page, I can see that I am logged in so the $.get call is clearly going through, but the callback function doesn't seem like its being called (ie. "get succeeded" is not popping up). I also don't appear to be getting any javascript error messages either.
Why isn't this working in IE?
Thanks
EDIT: Since a couple people asked, whenever I enter a correct email/password or an incorrect one, nothing in the callback function happens. If I manually refresh the page after entering a correct one, I am logged in. Otherwise, I am not.
EDIT 2: If I alert out data in the callback function nothing happens in IE (I do not get an alert popup). In FF, it alerts true for valid email/pw combos and false for invalid ones. I am using jQuery 1.3.2.
EDIT 3: Ok, guys, I tried R. Bemrose's thing down there and I'm getting a "parseerror" on the returned data. I'm simply echoing 'true' or 'false' from the other PHP script. I also tried 'yes' and 'no', but that still gave me a parse error. Also, this works in Chrome in addition to FF.
In your response type use:
header("content-type:application/xml;charset=utf-8");
As stupid as this sounds... perhaps IE7 is being anal retentive about the missing semicolon on the var pw line?
Probably not, but the only way I can think of getting more information is to convert it to an $.ajax call in order to add an error hook and see which error type it think is happening. Oh, and to check out the exception object.
$.ajax({
type: 'GET',
url: '/user/login.php',
data: { login_email: email, login_password: pw },
success: function(data) {
alert('get succeeded');
if(data == 'true') {
$('#login_error').hide();
window.location = '/user/home.php';
alert('true');
}
else {
$('#login_error').show();
alert('false');
}
},
error: function(xhr, type, exception) {
alert("Error: " + type);
}
});
If the error type is parse, IE may be complaining because the data coming back has extra commas at the end of comma separated arrays/lists.
IE uses cached data for get requests. Maybe that's your problem? What happens if you try different user id, password?
In any case, isn't it a better idea to send password in POST? :)
I'm am having a similar problem with the following code:
var listOrder = $(this).sortable('toArray').toString();
var otherVariable = whatever
$.get('process_todo.cfm?method=sortToDos', {listOrder:listOrder,otherVariable :otherVariable });
The variable displays through an alert as 'test_123,test_456'. I can hard code the same values and it does not fail. It must have something to do with the 'toArray'? I have been trying to debug this one thing for hours. Works perfectly in Firefox, Safari and Chrome... of course!
Instead of:
if(data == 'true')
try:
if(data)
then in your server just return either a 1 (or true) and a empty value.
What you've posted (at least after Edit 2) looks good. I think the problem is in what you haven't posted.
First, have you checked your server logs to ensure that it's sending back what you presume?
If so, I'd recommend dropping the submit mechanism and using a 'button' type with an 'onclick' handler, and not 'submit' button w/a 'onsubmit' handler...
<input type="button" id="login_submit" value="Login" />
Then switch the submit handler:
$('#login_form').submit(function() { ... });
from the form to the button with:
$('#login_button').click(function() { ... });
If that doesn't help, can you post the HTML for the form, too?
[Edit 3] - try adding the 4th 'type' parameter of "text" to the $.post() call.
Have you used Fiddler to have a good look at what's actually being transferred? (http://www.fiddler2.com)
if you are testing/checking your script in local machine then you will not see any thing in any version of internet explorer because IE on localmachine send datatype as text and not xml and in your case again its matter of datatype not compatible with your document datatype so it worth checking if your datatypes are matching
as far as xml goes solution is here
http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
you may check this and find some inspiration :)
salman

Categories

Resources