Specific pop up with ajax and query from database - javascript

I use in a form a simple radio button with "YES" or "No", I wish that when I click yes a pop-up window will be automatically shown with this specific message:
Are you sure you want to sell a new membership to [User’s Full Real Name from database] with the number [ number of product from database ] ?
That means at the same time an ajax query will be established to return the name of user and the number of product from database.
I'm not very good in JS/Ajax, can anyone help me with this?
Edit :
I know to do what you wrote in the message bellow,what I'm not sure is how to run the pop-up window automatically when I choose "yes" radio button?

To use ajax, you first need to create a server-side function that does what you need. For instance, a php script that takes a userID and returns the user's full name. Let's suppose you create that script and call it "username.php".
On your page, you'll use a javascript function, such as the jquery .ajax function to send an asynchronous request to username.php. The function call will look something like this:
function lookupUsername(){
$.ajax({
type: "POST",
url: "username.php",
data: { ID: $("#userID").val() }
}).done(function( msg ) {
alert( "Username: " + msg );
});
}
In the above example, I've assumed that the user ID is embedded somewhere on your page in an element with ID="userID". The term $("#userID").val() is a jQuery function that looks up the value of the HTML element called "userID".
Next, you need to call the lookup function when the yes radio button is clicked. So something like:
<input type="radio" name="foo" id="foo" value="yes" onclick="lookupUsername()" />
Note that to use the JQuery framework (The .ajax() function and the $() selector function, you need to include the JQuery framework on your page:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
It's totally possible to do an ajax call without jQuery, but the code is a little messier.

Related

Use javascript to show data from sql as it is Typed in HTML form

I'm working on a SQL database page to store data but I'm stuck at displaying data from sql as it is typed.
Heres what html form looks like
Now in above image, the 'Model Group' and 'Model Varient' Fields are readonly. Now I want to fill the two forms as soon as I type the VIN number.
The typed vin number is already stored in sql database. Can anyone suggest what code should I use or some reference Documents? Google serach didn't help much with this one.
Incase you need, the sql database looks like this:
If you want user to write the input:
First thing to do is to select all vin values and store them as input for HTML data-list tag.
Then you can use the code below (instead of input tag that you are using now):
<input list="vinData" name="vinValue" required>
<datalist id="vinData">
<option value="89841321">
<option value="546123">
<option value="213134984">
</datalist>
You should make option using PHP with a loop
Or you can just simply use html select tag. This way user can't write anything and has to choose one of the options.
<select>
<option value="89841321">89841321</option>
<option value="546123">546123</option>
<option value="213134984">213134984</option>
</select>
You need to do perform ajax request on blur event of vinno.
$('body').on('.vin-no','blur', function(){
$.ajax({
type:'post',
dataType:'json',
url: 'server.php',
data: {vinno: $(this).val()}
success: function(response){
$('.model-group').val(response.modelgroup);
$('.model-variant').val(response.modelvariant);
}
});
})
Also as #ali said it need to be an select list so user can select one of existing value. If you use 'select' you can make the 'blur' event to 'change' event.
I have used jquery ajax calls and ajax request need to be performed on the server side.
As #RobertFrenette wrote (and if I undestand what you try to achieve) it will require multiple communications scripts between front html - via AJAX to PHP - from PHP to SQL - and all back to user-end html form. Try this approach
1 Call ajax to send user input (vin number)
HTML code:
<input type="text" id="vin-input">
<input type="text" id="model-group" disabled>
<input type="text" id="model-varient" disabled>
enter code here
Javascript (with jQuery) code:
//When only user change VIN number call this function.
$("#vin-input").keyup(function( event ){
var input = $(this).val();
//Regex validate to prevent AJAX request when not needed.
//#todo change regex to your VIN schema.
var properInput = new RegExp('^[0-9]{6,}$');
if (properInput.test(input)) {
//#todo remove this
alert(input + " ok - send ajax");
//Send AJAX to PHP script.
//#todo change "get-vin.php" to your PHP script name.
$.post( "get-vin-data.php", {"vin": input})
.done( function( data ) {
//Handle data returning from PHP script.
//#todo parse returning data and put it into form.
$( "#model-group" ).val( "model 45" );
$( "#model-varient" ).val( "varient 45" );
})
.fail(function() {
//Handle failure of AJAX call (here it will always fail).
$( "#model-group" ).val( "model 45" );
$( "#model-varient" ).val( "varient 45" );
});
}
})
You can see regex matching as you should try to improve performance and validate vin number to call AJAX only when it is needed. You should change regex to fit your VIN schema.
Front end fiddle
2 Get data in backend and return to your script
This part I must leave to you. You have to:
create script (in my example it is named get-vin-data.php but you can name it as you wish and in any technology you use.
It should return information to your user-end script - small and simple as possible eg. JSON {model-group: "group 32", model-varient: "reddish"}.
Append this data to proper inputs in HTML - in JS example its code part //#todo parse returning data and put it into form..
Good luck.

How do I pass Javascript variables from my html template page to a Django views function?

I am working on a Django environment.
I have created a form in my html page which contains a textbox for input for a label like "Enter your name" .
I have a submit button below the textbox.
I need to pass the inputted name to the button as a value and then this button value is to be passed to a python function in views.py.
Can anyone help me with this ?
To do this you need to use Ajax, its like calling a url in the background without affecting the user. but first to call a a url(view) we need a url and a view. so i will think you have something like this
url('^click/btn/(?P<data>[0-9]+)', views.click_btn, name="btn_click");
and the view
def click_btn(request, data):
# do whatever you want with the data....
return HttpResponse('Done')
now to call this from the fron-end we will use jQuery.ajax
first you have the button
<button id="btn_click">Click me!</button>
now create a script tag and type the following
the script tag must be after the button so he can see it
<!-- if you haven't included jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
// get your input value...
var data = $('#my_input').val();
$.ajax({
url: `/click/btn/${data}`,
success: function (res) {
// every code in this function will execute when Ajax call the url
alert(`Nice! you called the url and get this data: ${res}`)
}
});
</script>

JS Ajax OnClick: How to execute php code multiple times?

I have an html button with an onclick attribute which runs a jQuery AJAX function pointing to php code.
The php code writes HTML in an output HTML <select> element(the element remains hidden until the javascript runs.)
This is working great to populate the <select> when an "add another" button is clicked.
The problem is it adds one and only one. I want to be able to have a new <select> tag populate with each click of the "add another" button up to a max of 2.
The JS in question:
var genre_dropdown = function genre_dropdown() {
$('.genre_output').css('display', 'block');
$.ajax({
url:'../includes/functions/genre_dropdown.php',
complete: function (response) {
$('.genre_output').html(response.responseText);
},
error: function () {
$('.genre_output').html('Bummer: there was an error!');
}
});
return false;
}
The HTML in question:
<select name="genre_id[]" autocomplete="off" class="genre_output"></select>
<select name="genre_id[]" autocomplete="off" class="genre_output"></select>
<div class="button add-genre-button" onclick="return genre_dropdown();">+ Add Existing Genre</div>
I thought I could include 2 html <select> elements for the php to populate into, the code would execute from one to the next. I see why this is not correct, the code is running in both at the same time. I'm at a place where I'm considering have 2 buttons ("add one", "add another") but that seems redundant and not correct, especially considering I want a scale-able technique (the max may not always be 2.) I need help.
Your php request is fine.
I simply mean define a variable as your using javascript i.e.:
var sel = '<select name="genre_id[]" autocomplete="off" class="genre_output">' + response + "</select>';
and then each time you do a request it will include the response as the value of the element. This would allow you to append the parent div as many times as you want. Finally, use a simple if counter to decide whether to keep appending or not:
if ($(".genre_output").length <= 2){
$("PARENT_DIV_ID").append(sel);
};
Is this clearer? #kaari
Assuming you want to keep previous values in dropdown then you can try append() instead of html()
$('.genre_output').append(response.responseText);

change input field value via javascript in grails

In my Grails project I have a field that allows me to select between a list.
After user has selected a value, I store the id of the related object.
I would like that, after storing the id, I get a value related to the object with that id and show it into another input field.
Here is the javascript that I use to store the id:
$("#patient_textField").autocomplete({
source: data,
select: function (event, ui){
$('#patient_id').val(ui.item.id);
}
});
I've created a function in controller that allows me to get the value that I need to show into the second input field
def getPhoneNumberFromPatientId(int patientID)
{
int phone = Patient.findById(patientID).phone_1
if(phone == null)
phone = Patient.findById(patientID).phone_2
return phone
}
How can I solve it?
You need to use AJAX to accomplish what you want. In Grails you have some taglibs that are very useful to execute an AJAX call.
An example is g:remoteFunction. This taglib allows you to execute an AJAX call and update the content of an HTML element. It's a very useful taglib!
For this question I've wrote an example that allows the user to select an option in a list (HTML Select) and update the content of a textArea based on the user selection. The update is performed by an AJAX call.
Main GSP (test.gsp)
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<asset:javascript src="application.js"/>
<asset:stylesheet src="application.css"/>
<title></title>
</head>
<body>
<label>Select an option: </label>
<g:select name="cbOption" noSelection="['':'']" from="${options}" onchange="${remoteFunction(action: 'getPhoneNumberFromPatientId', onSuccess: '\$("#value").val(data)', params:'\'patientId=\' + escape(this.value)')}; \$('#value').focus()"></g:select>
<g:textArea name="value"></g:textArea>
</body>
</html>
The AJAX call happens in the onchange event of g:select. For simplicity I omit some attributes of g:select as optionValue and optionKey.
This GSP is rendered by the following action:
def test() {
def options = ["A","B","C"]
return [options:options]
}
As you can see, this action returns an model to the above GSP that must be called test.gsp since this is name of the action. The variable options is the list of elements that could be selected by the user.
Remote Function
The remote function calls an action called getPhoneNumberFromPatientId and on the onSuccess event updates the textArea called value. The update is performed using JQuery.
${remoteFunction(action: 'getPhoneNumberFromPatientId', onSuccess: '\$("#value").val(data)', params:'\'patientId=\' + escape(this.value)')}
See below the action getPhoneNumberFromPatientId:
def getPhoneNumberFromPatientId(String patientId) {
def phone
if (patientId == "A")
phone = "3332-2222"
else if (patientId == "B")
phone = "4444-2222"
else if (patientId == "C")
phone = "5555-2222"
render phone
}
The actions above doesn't return, the actions render the content. It's a very importante difference. See this answer to understand the difference: Grails updating values in form using Ajax
Basically when you're working with AJAX call you'll render the content. The content could be a variable (as above), an HTML snippet or a GSP template.
Please, check the source code of your page (in your browser) to understand that your g:remoteFunction was rendered as a JQuery AJAX call.
Bonus
After the AJAX call I set the focus on the textArea. This is done using JQuery too. See the end of the onchange event to understand this part.

Populating JScript Array for reuse on SELECTs

Forgive me if this is already 'somewhere' on StackOverflow, but I don't 100% know exactly what it would come under...
I'm trying to retrieve information from a WebService, store this in an array, and then for each <select> within my ASP.Net Datalist, populate it with the array AND have binding attached to an OnChange event.
In other words, I have an array which contains "Yes, No, Maybe"
I've an ASP.Net Datalist with ten items, therefore I'd have 10 <Select>s each one having "Yes, No, Maybe" as a selectable item.
When the user changes one of those <Select>s, an event is fired for me to write back to the database.
I know I can use the [ID=^ but don't know how to:
a) Get the page to populate the <Select> as it's created with the array
b) Assign a Change function per <Select> so I can write back (the writing back I can do easy, it's just binding the event).
Any thoughts on this?
I have built a simple example that demonstrates, I think, what you are attempting to accomplish. I don't have an ASP.Net server for building examples, so I have instead used Yahoo's YQL to simulate the remote datasource you would be getting from your server.
Example page => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource.html
Example steps:
query datasource to get array of select questions
build HTML of selects
append HTML to page
attach change event listener to selects
on select value change submit value
Example jQuery:
// get list of questions
$.ajax({
url: url,
dataType: "jsonp",
success: function(data) {
// build string of HTML of selects to append to page
var selectHtml = "";
$(data.query.results.p).each(function(index, element) {
selectHtml += '<select class="auto" name="question'+index+'"><option value="Yes">Yes</option><option value="No">No</option><option value="Maybe">Maybe</option></select> '+element+'<br/>';
});
// append HTML to page
$(document.body).append(selectHtml);
// bind change event to submit data
$("select.auto").change(function() {
var name = $(this).attr("name");
var val = $(this).val();
// replace the following with real submit code
$(document.body).append("<p>Submitting "+name+" with value of "+val+"</p>");
});
}
});
Example datasource => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource-datasource.html
Example loaded:
Example select value changed:

Categories

Resources