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.
}
});
Related
I have an AJAX post method that works in two places both on "Ladder" page, but not another, a "matches" page. This method sets posts the "player ID" which php picks up and sets a session variable
$("form .singles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Working page form:
<form><button type='submit' id='playerInfo' class='singles-player-name' name='viewPlayer' value='",$sglsPlayerID,"'>", $curSGLSRankLName, ", ", $curSGLSRankFName, "</button></form>
Sets session variable
if (!empty($_POST['viewPlayerID'])){
$viewPlayer = isset($_POST['viewPlayerID']) ? $_POST['viewPlayerID'] : 'No data found';
$viewPlayerSql = "SELECT * FROM `PLAYERS` WHERE `ID` LIKE '".$viewPlayer."'";
$viewPlayerQuery = #$conn->query($viewPlayerSql);
$viewPlayerRow=mysqli_fetch_assoc($viewPlayerQuery);
$_SESSION['playerID'] = $viewPlayerRow["ID"];
echo "", $_SESSION['playerID'],"";}
Second working version that lives on the same page as the first but is for doubles players:
$("form .doubles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Form for that ajax method:
<form><button type='submit' id='playerInfo' class='doubles-player-name' name='viewPlayer' value='",$dblsPlayerID,"'>", $curDBLSRankLName, ", ", $curDBLSRankFName, "</button></form>
Then on complete, the ajax methods redirect to the player page and pulls up that players info on that page (ex. https://urlexample.com/Player). This part, from this point-up, works! However, I have another page, the "Matches" page, where I want it to do the same exact thing, and set that session variable, then redirect to the player page, so I have this method below. But for some reason, this one does not work:
$("form .singlesMatch-player1-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
console.log(data);
window.location.href = "Player";
});
});
Not working form:
<form><button type='submit' id='playerInfo' class='singlesMatch-player1-name' name='viewPlayer' value='",$sglsPlayer1ID,"'>", $P1LN, ", ", $P1FN, "</button></form>
For some reason, all this second method does is post it to the URL (ex. https://urlexample.com/WeeklyMatchUps?viewPlayer=1) instead of setting the session variable and redirecting to the player page (ex. https://urlexample.com/Player). All thats different between the 2 is the class name of the button.
$sglsPlayer1ID should probably be $sglsPlayerID.
Also, try adding a success and error condition to your AJAX conditions instead of just using a done operator. This will allow you to dump helpful error codes on a failure to better resolve these kinds of issues in the future.
I had a function being called on the page that was commented out causing an error before jQuery was added in a script at the bottom of the page. removing that function from being called fixed the issue.
S/O to #line88 for the assistance!
How to show "Live Feedback" on a script using jQuery?
I have a button that I use to submit a form for processing. Processing takes a long time. I want to have a <div id="progress"></div> where I show live progress report of what order processing script is doing. If all goes well I want to redirect to the View Order script, and if not, just show the progress report (not redirect to view order)
How? Currently I have this:
$("#placeorderbutton").click(function(e) {
e.preventDefault();
this.innerHTML = 'Placing Order...';
this.disabled = true;
$.ajax({
type: 'post',
url: 'process_order.php',
data: $('form#order').serialize(),
success: function(data) {
$("#main").load('view_order.php');
}
});
});
and even though I have print statements in my process_order file, they are not being displayed anywhere on the screen. Well, of course not ... I don't know how to build my jQuery/AJAX to make them show.
I am not sure how to proceed.
You would need to start the long process and then start a timer to poll the status. Keep in mind it doesn't take much for this to become more expensive than it's worth.
$("#placeorderbutton").click(function(e) {
e.preventDefault();
this.innerHTML = 'Placing Order...';
this.disabled = true;
$.ajax({
type: 'post',
url: 'process_order.php',
data: $('form#order').serialize(),
success: function(data) {
$("#main").load('view_order.php');
}
});
setTimer($.ajax({
type: 'post',
url: 'view_order.php',
data: $('form#order').serialize(),
success: function(data) {
$("#main").append(data);
}
}), 30000); //check every 30 Seconds
});
I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});
I've got a simple form submission that upon success I've got an alert and a call to clear the form. I do get the alert, the info gets successfully added to the database, but the second call--for the form to clear, is not being carried out. I'm sure it's something simple I'm doing wrong, but I can't figure it out.
$('#contact_submit').click(function(e){
if ($("#submit_form_contact").valid()) {
var post_data = {
"name" : $('#name').val(),
"email" : $('#email').val(),
"inquiry" : $('#inquiry_dropdown option:selected').text(),
"message" : $('#message').val()
};
$.ajax({
type: "POST",
url: "process-contact.php",
data: post_data,
success: function(data) {
alert("Thank you for contacting us.");
$('#submit_form_contact').reset();
}
});
e.preventDefault();
}
Also, the submit button is just a button, not a submit input. Is it necessary to preventDefault()? I'm new at this.
jQuery doesn't have a .reset() method.
Do this instead:
$('#submit_form_contact')[0].reset();
This grabs the first DOM element, and invokes the native .reset(). If there's any chance the form won't be found, then test for the element.
var f = $('#submit_form_contact')[0];
if (f)
f.reset();
And of course you don't really need jQuery to get an element by ID, especially if you're not going to use any jQuery methods.
var f = document.getElementbyId('submit_form_contact');
if (f)
f.reset();
Another alternative would be to set the submit button as the context: of the ajax call, then use its form property.
$.ajax({
context: this,
type: "POST",
url: "process-contact.php",
data: post_data,
success: function(data) {
alert("Thank you for contacting us.");
this.form.reset();
}
});
this line can be used too
$("#submit_form_contact").trigger('reset');
I wrote a little chat plugin that i'll need to use on my site. It works with a simple structure in HTML, like this:
<div id="div_chat">
<ul id="ul_chat">
</ul>
</div>
<div id="div_inputchatline">
<input type="text" id="input_chatline" name="input_chatline" value="">
<span id="span_sendchatline">Send</span>
</div>
There's a 'click' bound event on that Span element, of course. Then, when the user inserts a message and clicks on the "Send" span element, there's a Javascript function with calls an Ajax event that inserts the message into the MySQL database:
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
function_get_newchatlines();
}
});
}
And, in case the message is successfully inserted into DB, it calls a function to read new lines and put them in HTML structure i posted before:
function function_get_newchatlines()
{
$.ajax
({
type: "POST",
url: "ajax-chat-loadnewlines.php", //1: ok, 0: errore
data: '',
dataType: "text",
cache: false,
success: function(ajax_result) //example of returned string: 'message1>+<message2>+<message3'
{
//explode new chat lines from returned string
var chat_rows = ajax_result.split('>+<');
for (id_row in chat_rows)
{
//insert row into html
$('#ul_chat').prepend('<li>' + chat_rows[id_row] + '</li>');
}
$('#span_sendchatline').html('Send');
}
});
}
Note: 'ajax_result' only contains html entities, not special chars, so even if a message contains '>+<', it is encoded by the php script called with Ajax, before being processed from this JS function.
Now, comes the strange behaviour: when posting new messages Opera, Firefox and even IE8 works well, as intended, like this:
But, when i open Chrome window, i see this:
As you can see, in Chrome the messages are shown multiple times (increasing the number each time, up to 8 lines per message). I checked the internal debug viewer and it doesn't seem that the "read new lines" function is called more than one time, so it should be something related to Jquery events, or something else.
Hope i've been clear in my explanation, should you need anything else, let me know :)
Thanks, Erenor.
EDIT
As pointed out by Shusl, i forgot to mention that the function function_get_newchatlines() is called, periodically, by a setInterval(function_get_newchatlines, 2000) into Javascript.
EDIT2
Here's is a strip of the code from the PHP file called by Ajax to get new chat lines (i don't think things like "session_start()" or mysql connection stuff are needed here)
//check if there's a value for "last_line", otherwise put current time (usually the first time a user logs into chat)
if (!isset($_SESSION['prove_chat']['time_last_line']) || !is_numeric($_SESSION['prove_chat']['time_last_line']) || ($_SESSION['prove_chat']['time_last_line'] <= 0))
{
$_SESSION['prove_chat']['time_last_line'] = microtime(true);
}
//get new chat lines
$result = mysql_query("select * from chat_module_lines where line_senttime > {$_SESSION['prove_chat']['time_last_line']} order by line_senttime asc; ", $conn['user']);
if(!$result || (mysql_num_rows($result) <= 0))
{
mysql_close($conn['user']); die('2-No new lines');
}
//php stuff to create the string
//....
die($string_with_chat_lines_to_be_used_into_Javascript);
Anyway, i think that, if the problem was this PHP script, i would get similar errors in other browsers, too :)
EDIT4
Here's the code that binds the click event to the "Send" span element:
$('#span_sendchatline').on('click', function()
{
//check if there's already a message being sent
if ($('#span_sendchatline').html() == 'Send')
{
//change html content of the span element (will be changed back to "send"
//when the Ajax request completes)
$('#span_sendchatline').html('Wait..');
//write new line
function_write_newchatline();
}
//else do nothing
});
(Thanks to f_puras for adding the missing tag :)
I would do one of the following:
option 1:
stop the timer just before the ajax call in function_write_newchatline() and start the timer when the ajax call returns.
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
stop_the_timer();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
function_get_newchatlines();
},
complete: function() {
start_the_timer();
}
});
}
option 2:
Not call function_get_newchatlines() at all in the success event of the ajax call. Let only the timer retrieve the chat entries.
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
// do nothing
}
});
}
I think there is some race condition between the function_get_newchatlines() that is called after a chat entry is added by the user and the periodical call of function_get_newchatlines() by the timer.
option 3:
Use setTimeout instead of setInterval. setInterval can mess things up when the browser is busy. So in the end of the setTimeout function call setTimeout again.