jQuery dialog before ajax post - javascript

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
}

Related

Remember the state of clicked button with AJAX

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.
}
});

Adding to JSON array by HTML button

I have an AJAX call, as below. This posts data from a form to JSON. I then take the values and put them back into the div called response so as to not refresh the page.
$("form").on("submit", function(event) { $targetElement = $('#response'); event.preventDefault(); // Perform ajax call // console.log("Sending data: " + $(this).serialize()); $.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#RearPillarNS").empty();
$("#RearPillarNS").append("Rear Pillar Assembly Part No: " + response["RearPillarNS"]);
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call }) });
This generates a new <select id="mySelect">
I need to now extract the value that has been selected by the newly generated select and amend my JSON array. Again, without refreshing the page.
I was thinking of doing this via a button called CreateDrawing
The JS function for this would be:
> $(function() {
$('a#CreateDrawing').bind('click', function() {
$.getJSON('/Printit',
function(data) {
//do nothing
});
return false;
});
});
This is because I will be using the data from the JSON array in a Python function, via Flask that'll be using the value from the select.
My question is, what is the best way (if someone could do a working example too that'd help me A LOT) to get the value from the select as above, and bring into Python Flask/JSON.

How to fill AJAX with values from multiple inputs?

So i have an AJAX function and I want to search every element with particular class, take its value and add it into the AJAX in the right format. Is that possible?
I have this AJAX function:
function sendOrders(button) {
$.ajax({
url: "external_file.php",
method: "POST",
data: {
/*Here I need to add the data*/
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
}
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};
and I need to collect data from hidden-type inputs on the page with class="order".
I know that I can acces each element by class with jquery, but I have no idea how to add the properties to my AJAX, when it's already written. Number of those elements is variable and they have non-repeating ids, class is the same. Inputs look like this:
<input class="order" type="hidden" name="some_name" id="some_id" value="some_value">
Can anyone help?
From what I understand, you want to make that ajax call with several different values that you get from the inputs with class order?
Assuming you want to just add the value from those fields, you can do something pretty simple:
First, update your ajax function with an additional input variable,
function sendOrders(button, val) {
$.ajax({
url: "external_file.php",
method: "POST",
data: {
value : val,
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
}
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};
Then, to get data from all of your 'order' class inputs, you can use Jquery's 'each' function. For example, if you want the value from each of those inputs, you can use your new sendOrder function in the each function:
$('.order').each(function(){
sendOrder(buttonId, $(this).val())
});
Not quite sure how you are using 'button' in your ajax function, but I assume it's associated with your save or submit button, so buttonId would be whatever the id is of that button. This will iterate over all inputs with class order and make the ajax call with those values.
If you're using the button as a submit you can probably take it out all together from the ajax function, and have something like this:
function sendOrders(val) {
$.ajax({
url: "external_file.php",
method: "POST",
data: {
value : val,
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
}
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};
$('#buttonId').click(function(){
$('.order').each(function(){
sendOrder(buttonId, $(this).val())
});
});
Create the data object, loop over all the inputs, and add the values to the object.
function sendOrders(button) {
var data = {
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
};
$(button).closest("form").find("input[type=hidden]").each(function() {
data[this.name] = this.value;
});
$.ajax({
url: "external_file.php",
method: "POST",
data: data
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};

Javascript works fine with a hard-coded string but not with variable

I have a problem I have bee struggling over all morning so I felt it was time to get some help! I have a javascript function which gets the value entered by a user into an autocomplete box, uses AJAX to send that value to a php script which queries the database and then populates the following box with the possible options. The problem is this all works fine when I hard-code in the selected option as so:
var selected="Ed Clancy";
but not when it pulls it from the box, as so:
var selected = this.getValue();
I have tried debugging this using an alert box and both boxes come up with the same string in them so I am completely puzzled! Any ideas? Full code below:
$(riderSelected).on('selectionchange', function(event){
var selected = this.getValue();
//var selected="Ed Clancy";
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: { name: selected },
success: function(data) {
console.log(data);
$('#nap4').append(data);
}
});
});
Based on magicsuggest documentation - http://nicolasbize.com/magicsuggest/doc.html , you probably could do this
var selected = this.getValue()[0];
IF you do not allow multiple selection
Change your code as I have written below for you .
Code
$(riderSelected).on('change', function (event) {
var selected = this.value;
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: {name: selected},
success: function (data) {
console.log(data);
$('#nap4').append(data);
}
});
});

Ajax sends two files at one time through one onclick event in JavaScript

jQuery AJAX seems to be sending two requests at once when I use the onclick event with JavaScript in a tag. I click once, and that seems ok, but when I change the id value to an invalid id value, it sends two requests to the PHP file. I think the problem may be caused by the browser caching JavaScript code.
Here's is the JavaScript code I'm using to generate the query:
function unlike_image(id, image_id, obj) {
var url_unlike_image = base_url + 'profile/unlike_image';
$.ajax({
type: "POST",
data:
{
user_id: id,
image_id: image_id
},
url: url_unlike_image,
success: function(data) {
if (data.status=='error_exists') {
alert('This image not exists');
}
if (data.status=='success') {
//like = like - 1 for view
var str = $(obj).next().text();
var n = str.length;
str_like = str.substring(1, n-1);
var number_likes = parseInt(str_like) - 1;
$(obj).next().text('('+number_likes+')');
//change event click unlike
$(obj).text('Like');
$(obj).attr('onclick', 'like_image('+id+' ,'+image_id+ ',this); return false');
}
}
});
}
After changing the true id to the wrong id, I check the website traffic, I see two instances where unlike_image is called. The first is with the true id, and the second is with the wrong id.

Categories