I want to know about how to retrieve data from map.
I have three button.
Register, Update and Delete from Jsp page.
There are two JSP. First.jsp and Second.jsp.
I included first.jsp in second.jsp.aaa
The buttons are in second.jsp.
At First.jsp.
I have combobox for language change. It must be change language only when click button.
There are two language English and Japanese.
I send API class using ajax according to language id. If id=1(Japanese) and id=2(English).
I Wrote ajax api inside of combobox change function. Below is my code.
$.ajax({
url : 'aa/idsend',
cache : false,
type : 'GET',
dataType : 'json',
contentType : 'application/json; charset=utf-8',
data : "lid="+select,
success: function(data) {
},
});
I receive data from server the following format.
{data = Object {1: "Would you like to register?", 2: "Would you like to update?", 3: "Would you like to delete?"}
Above data are come from database. If I add new data into database the id become 4:"something have".
I want to know how to retrieve these data according button click event.
If click register button I want to take register sentence only. The other is also like that.
It could be GET method also, but i prefer POST.
function ajaxRequest(dataObj, cbFunc) {
$.ajax({
method: 'POST',
url: 'aa/idsend',
data: dataObj
}).done(function(dataFromServer) {
cbFunc(dataFromServer);
});
}
function useData(dataFS) {
//do something with data from server dataFS
}
function getCurrentLanguage() {
var cL = 'en';//default language
//some code to get language from checkboxes
return cL
}
$('.button').on('click', function(e) {
var id = $(this).attr('id'),
jsonData = {},
curLang = getCurrentLanguage();
switch (id) {
case 'register' :
jsonData = {req: 'register', lang: curLang};
break;
case 'update' :
jsonData = {req: 'update', lang: curLang};
break;
case 'delete' :
jsonData = {req: 'delete', lang: curLang};
break;
default:
break;
}
ajaxRequest(jsonData, useData);
});
Then in the aa/idsend serverside script you can prepare data to send according to req POST variable received. Now you even don't need to send back questions like 'Would you like to register?'. Instead you can do action according to req value and send back information about the operation - Success! or Fail!
Related
I'm using django-autocomplete-light with the select2 "select multiple" widget for a M2M form.
I have it set up to enable "Create New" when the input is not found.
However, my model has additional required fields beyond the initial input of the "select multiple" widget.
I am trying to create a way to prompt the user for the additional fields when trying to create, and then sending that data through ajax to my django view.
Right now, if I pre-supply the other required fields within my view, the user can create a new object with the name that they've entered (and clicked "Create New") for, and the other fields will be determined in my view. This shows me that the code is working, but ideally I'd like to prompt the user for the additional data.
I have created a prompt, however I cannot the correct syntax for transmitting the data.
As an example, pretend I have a model with required fields "Name" and "Location".
On the Select2 widget, the user types a "Name" which doesn't exist as an object, and clicks "Create New". Now, I'd like the script to prompt them for the location, then transmit that in as a get_or_create parameter.
Code below:
**views.py**
class Videoautocomplete(autocomplete.Select2QuerySetView):
create_field = 'name'
def create_object(self, text):
"""Create an object given a text."""
object = Model.objects.all()[0]
return self.get_queryset().get_or_create(name=text, location=object.location)[0]
def get_queryset(self):
"""This is the code for the initial search within the select2 field"""
qs = Model.objects.order_by('name')
if self.q:
qs = qs.filter(name__icontains=self.q)
return qs
**select2.js**
$(this).on('select2:selecting', function (e) {
var data = e.params.args.data;
if (data.create_id !== true)
return;
e.preventDefault();
var select = $(this);
$.ajax({
url: $(this).attr('data-autocomplete-light-url'),
type: 'POST',
dataType: 'json',
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", document.csrftoken);
"""Below is prompting the user for the location, and assigning it to the variable location"""
var location = prompt("Please enter the location", "");
},
"""How do I add the contents of the variable Location into the data below?"""
data: {
text: data.id,
forward: yl.getForwards($(this))
},
success: function(data, textStatus, jqXHR ) {
select.append(
$('<option>', {value: data.id, text: data.text, selected: true})
);
select.trigger('change');
select.select2('close');
}
});
});
If I intercept the transmitted JSON object as a string (using "test" as the input), I get this:
{"id":"test","text":"Create \"test\"","create_id":true}
I need to figure out how to inject the Location variable into that object, but I can't figure out the syntax. Any help?
I have different cards displayed on an app, the information is coming from the database in a loop. I have the option to put a 'redeem button' on cards if it's something a user can use just once. When the user clicks the redeem button, I get in the database the information (card name, clientID). Then, I made another AJAX call to get the information from the database and what I want is to check if the clientID and the carndame are already in the database then delete it just for that user. I don't wanna use localStorage or cookies because if the user delete the cookies they would see the card again and I don't want this to happen.
-- AJAX CALL TO POST --
$(`#promotion-container .promo${i} .redddButt`).click(function(e){
e.stopPropagation();
var esc = $.Event("keyup", { keyCode: 27 });
$(document).trigger(esc);
$('#deletePromo').on('click', function(){
if (eventName && customerID)
$(`#promotion-container .promo${i}`).remove() // this removes it but if you reload the page it appears again.
})
$('#just-claimed-popup2').addClass('reveal');
var theDiv = document.getElementById("card-just-claimed");
var content = document.createTextNode(eventName);
theDiv.appendChild(content);
$.ajax({
type: 'POST',
url: '/api/promotions_redemption',
crossDomain: true,
dataType: 'json',
data: {
eventName : eventName,
dateReedem : dateReedem,
}
});
})
--AJAX CALL TO GET INFO FROM DATABASE --
let success = function(res, eventName) {
let cardData = res['cardData'] //cardData is the info from database
for(i=0; i<cardData.length; i++){
let nameEvent = cardData[i]['event_name']
let customerID = cardData[i]['customer_id']
let clicked_button = cardData[i]['clicked_button']
let eventName1 = promotions['event_name'] // getting the names of all cards displayed
if(customerID && nameEvent == eventName1){
$(`#promotion-container .promo${i}`).remove(); // HERES THE PROBLEM
}
}
}
$.ajax({
type: 'GET',
url: '/api/promotions-check',
crossDomain: true,
dataType: 'json',
success: success,
});
The problem is that my conditional on my GET call is successful but it forgets the id of the card, meaning that when I try to console.log the id of the promo it comes as 0, instead of the actual number, so it's forgetting the information of the cards rendered and don't know what to delete.
What would be the best way to achieve the card to be deleted? Do I need to do it in the click event too? and if yes, can I have 2 Ajax calls in the same function?
If you change the approach you would be able to achieve this more easily. When you send a post request to delete the item or redeem the code in your case, upon success return same data and upon some condition just delete the item from DOM. On page load it shouldn't load whichever was redeemed.
I personally don't see a point of doing another GET to delete the code which was redeemed.
$.ajax({
type: 'POST',
url: '/api/promotions_redemption',
crossDomain: true,
dataType: 'json',
data: {
eventName : eventName,
dateReedem : dateReedem,
},
success: function(result){
//on success, ie when the item is deleted -> delete from the DOM.
}
});
I have a form and a jQuery function which is triggered if user changes a html select field. The function collects all of the information what it needs and posts to a php script with an ajax post.
I want to extend this function with a new feature: if the selected value equals to a predefined value I want to display a dialog with two buttons. The user needs to click one of these buttons and if he does the new information will attached to the post.
An easy example:
The select has 3 options:
- Lemon
- Banana
- Apple
If the user selects lemon or banana, the scripts sends the info to the server without further actions. But if he selects apple, I need an extra dialog, because I want to ask if he needs a red or a green one. And it needs to be attached to the information which I want to send to the server.
Could you help me guys how should I do it?
I have only the first part:
$('select.myList').change( function()
{
var e = $(this)
var val = $(this).val();
var id = $(this).attr('data-id')
var url = 'index.php?process'
$.ajax({
type: "POST",
url: url,
data: { id: id, val: val },
success: function(data){
var o = $.parseJSON(data);
if( o.error )
{
console.log('error:' + o.message);
} else
{
console.log('success:' + o.message);
}
return false;
}
})
return false
})
First, I would say you should be extremely careful with your variable names. You should NEVER use e as a variable if it can be avoided. I would also change id and val.
In any case you should be able to use the beforeSend property in ajax: http://api.jquery.com/jquery.ajax/, so assuming that 'apple' would be the val of the element:
$.ajax({
type: "POST",
url: url,
data: { id: id, val: val },
beforeSend: function() {
if (val === 'Apple') {
//do stuff
}
},
// rest of ajax call
}
The thing is that i have an embedded python interpreter and after a user presses "Run", the output from interpreter gets transferred to a pre element. I want to take that data from pre element and send it to django server through AJAX. The problem is that even after assigning of that data to a variable, django gets nothing. Also i can start interpreter and AJAX script only after pressing "Run", both work work with onclick. I am using POST request.
`$(document).ready(function(){
$('#run').click(function(){
var input_string = String(document.getElementById("output").innerHTML);
alert(input_string);
$.ajax({
url: '/courses/python3/lesson_validate/{{ lesson_number }}/',
data: {"text": input_string, csrfmiddlewaretoken: '{{ csrf_token }}'},
dataType: "json",
type:"POST",
success: function(data, textStatus){
alert('get_response');
alert(data);
},
error : function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
});
});
`
So that code works perfectly
var input_string = String(document.getElementById("output").innerHTML);
alert(input_string);
but when i try to use that variable in ajax, server fails to get it.
I tried using async: false, it doesn't change anything.
This is view code:
`def lesson_validate(request,lesson_number):
args = {}
args.update(csrf(request))
out_compare = Lessons.objects.get(id=lesson_number).lesson_output
if request.method == "POST" and request.POST.get('text') == out_compare:
text = "they are equal"
return HttpResponse(json.dumps(text), content_type='application/javascript')
else:
args['testtest']=request.POST.get('text')
return render_to_response('course_lesson.html', args, context_instance=RequestContext(request))`
After i check request.POST.get('text') it is empty
The question is how can i get data from ajax, from a variable assigned before, not just from a sting?
It looks like you're sending JSON to the server in that request, so to get the variables in Django you'd need to do:
def lesson_validate(request,lesson_number):
import json
data = json.loads(request.body)
text = data.get('text')
# Do stuff.
I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}