jQuery Modal - button action - javascript

I have a bootstrap 3 modal that is launched via a button on the parent and then populate the modal-body with form data coming from my MySQL database. Among the populated data is small gallery showing attachment pictures and one unique delete-button underneath each picture to launch a query to delete the attachment from a specific attachment folder.
Gallery and delete button ON THE MODAL:
<div class=\"row\">
<div class=\"box box-widget widget-user-2\">
<div class=\"widget-user-header bg-gray\">
<div class=\"lightBoxGallery\">";
$files = scandir($log_folder);
foreach ($files as $attachment) {
if (in_array($attachment, array(".",".."))) continue;
echo "
<span class=\"input\"><button type=\"button\" id=\"DeleteAttachmentButton\" name=\"DeleteAttachmentButton\" class=\"form-btn btn-danger btn-xs\" data-filename=\"".$attachment."\"><i class=\"fa fa-trash\"></i></button><img src=\"".$log_folder.$attachment."\" style=\"height:100px; width:150px;\"></span> ";
}
echo "
</div>
<!-- ./lightbox gallery -->
The problem now is that nothing happens when I press the delete button for the specific attachment. I believe this to be caused by the JavaScript code below which is located ON THE PARENT right after the modal.
// DELETE ATTACHMENT - DELETE BUTTON ON EDIT MODAL
$("#DeleteAttachmentButton").click(function(e){
var modal = $(this);
if (confirm('Are you sure you want to delete this attachment?')) {
var attachment_name = $(e.relatedTarget).data('filename'); // Extract info from data-* attribute
$.ajax({
url: "../../plugins/MySQL/ajax_action.php",
type: "POST",
async: true,
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(), LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#logbook_output').html(data);
drawVisualization();
},
error: function(data) {
console.log(err);
}
});
// close modal and refresh page
$('#EditLogModal').modal('hide');
}
});
I checked with Chrome Debugger to see whether any AJAX call is made, but I do not even get to the JavaScript Confirm Alert nor do I receive any error message in the console.
Any hints please?
Thanks

You have an invalid JSON data in your AJAX call (may be you can see errors in your browser's console),
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(),
LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
//------------------^ don't use this
Just use Filename:attachment_name}
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(),
LogID:$("#dataLogID").val(), Filename:attachment_name)}

change this
$("#DeleteAttachmentButton").click(function(e){
to this
$(document).on("click","#DeleteAttachmentButton",function(e){
Read about event-delegation

$(document).on('click', '#DeleteAttachmentButton', function(e){
var modal = $(this);
if (confirm('Are you sure you want to delete this attachment?')) {
var attachment_name = $(e.relatedTarget).data('filename'); // Extract info from data-* attribute
$.ajax({
url: "../../plugins/MySQL/ajax_action.php",
type: "POST",
async: true,
data: { action:"delete_attachment",Holidex:$("#dataLogID").val(), LogID:$("#dataLogID").val(), Filename:attachment_name).val()}, // form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#logbook_output').html(data);
drawVisualization();
},
error: function(data) {
console.log(err);
}
});
// close modal and refresh page
$('#EditLogModal').modal('hide');
}
});

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

Submit form and call Ajax on <a> click

I want to add something to database using Ajax. I have a link which submits the form and then Ajax call should work, but it's not. I use this same Ajax call on different page, but in that form I'm using simple button with type submit. But on this page, I want to submit with ...
This is the form
{!! Form::open(['id' => 'ajax-form', 'style' => 'float:right']) !!}
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idCampaign" id="idCampaign" value="{{$campaign->id}}">
<a class="fa fa-bookmark fa-2x" onclick="document.getElementById('ajax-form').submit();" aria-hidden="true" href="javascript:{}" style="color:#fd8809"></a>
{!! Form::close() !!}
This is the Ajax:
$("#ajax-form").submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: form.serialize(),
success: function(data){
if(data.status == 'failedd'){
swal("Error!", "You have already added this campaign to favorites! If you want to remove it, go to your Favorites list page", "error")
}
else{
swal("Success!", "You added the campaign "+ data.idCampaign + " to favorites!", "success")
}
},
error: function(data){
swal("Error!", "error")
},
complete: function (data) {
}
});
});
When I click on this link, it redirects me to another page which throws: MethodNotAllowedHttpException.
Change your ajax url to this:
url: '/addFavorites',
and your route to this:
Route::post('/addFavorites', 'SearchController#addFavorites');
Just to make sure you point at the same url
EDIT:
make sure that you have one route with get and the same route with post. see bellow:
Route::get('/addFavorites', 'SearchController#loadFavorites'); <-to load the page
Route::post('/addFavorites', 'SearchController#submitFavorites'); <-to submit the data
Change this: $("#ajax-form").submit(function(event) {
To this: $('#yourid').click(function(){
Remove the onclick in the 'a' element and add the id='yourid' with the name you want.
MethodNotAllowedHttpException usually comes when you haven't defined route or you have defined route for get method and you are using the route for post method. please check your routes.php

Passing JSON through AJAX Plus Button Dilema

so I am attempting to pass some information in a JSON object and have a php page insert the data into a database. However, I am running into some trouble. The "update" button exists in a popup window. The user then clicks "update" and the inputted data should be processed accordingly. However, I fear that I am not even reaching my .click function. None of my alerts seems to be triggered. Below I will point out where issues are occurring. Thank you!
<script>
function updateTable()
{
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
$('#update').click( function() {
alert("help!");
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
#.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
//data: 'popUpString = '+ popupString,
data: popupObj,
cache: false,
success: function(data) {
updateTable();
alert("testing tests");
}
});
});
</script>
<html>
<button onClick="openPopup(<?php echo $row['ID'];?>);"><?php echo $row['ID'];?></button> <!--opens a popup with input options-->
<button id="update">Update</button> <!-- this button is supposed to cause the javascript above to run when clicked, however none of my alerts seem to be reached.-->
</html>
Thank you for looking!
1)I can only guess that you're trying to use JQUERY?
Where do you include the library?
2 )#.ajax isnt valid Jquery function
try $.ajax instead

JQUERY/ AJAX Request not going through and conflicts

I have included a contact form in my page. In the same page I have a script that gets prices depending on the value of a dropdown. Now when I try to submit the contact message I have a conflict with the script for prices. Basically it tries to run it and I have no clue why. Also the contact form when submitted never works...I just get a new page to open with URL..?message=blablabla
Any idea what is going wrong?
I am working on Laravel 4.2 and so the route you see redirects to my php function.
Here is the JSfiddle and here is the php code:
public function postSendMessage() {
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks!</span><br><br>";
}
Cancel the click so the form will not submit
$("button#send").click( function(evt){
evt.preventDefault();
New error, form has an id of contact, not a class
data: $('form.contact').serialize(),
needs to be
data: $('form#contact').serialize(),
This is what I do for the same situation
//For your drpbox use this code
$(document).on("change", "#yorDropBoxId", function(){
dropBoxValue=$("#yorDropBoxId").val();
var request = $.ajax({//http://api.jquery.com/jQuery.ajax/
url: "samePagePHPcript.php",
type: "POST",
data: {
ObjEvn:"dropBoxEvent",
dropBoxValue: dropBoxValue //You will use $myVar=$_POST["dropBoxValue"] to retrieve the information from javascript
},
dataType: "json"
});
request.done(function(dataset){
//If you want to retrieve information from PHP sent by JSON.
for (var index in dataset){
JsResponse=dataset[index].phpResponse;
}
if(JsResponse test someting){
"do dometing"
control the beheaivor of your HTML elements
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
//To submit your form use this code. You must use Prevent default if you are using a button or using a <a> link tag to trigger the evenrmrnt
$(document).on("click", "#btn_sendForm", function(e){
e.preventDefault();
var dt={
ObjEvn:"FormEvent",
input1:$("#txt_input1").val(),
input2: $("#txt_input2").val(),
input3: $("#txt_input3").val()
};
var request = $.ajax({//http://api.jquery.com/jQuery.ajax/
url: "samePagePHPcript.php",
type: "POST",
data: dt,
dataType: "json"
});
request.done(function(dataset){
//If you want to retrieve information from PHP send by JSON.
for (var index in dataset){
JsResponse=dataset[index].phpResponse;
}
if(JsResponse test someting){
"do dometing"
control the beheaivor of your HTML elements
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
//In the samePagePHPcript.php you can do this:You will return your information from PHP using json like this
$event = $_POST["ObjEvn"];
if(event==="FormEvent"){//Event to insert in your form
$arrToJSON = array(
"phpResponse"=>"data you want to send to javascript",
"asYouWant"=>"<div class=\".class1\">more data</div>"
);
echo json_encode(array($arrToJSON));
}
elseif(event==="dropBoxEvent"){//Event to your dropbox - if you want
$arrToJSON = array(
"phpResponse"=>"data you want to send to javascript",
"asYouWant"=>"<div class=\".class1\">more data</div>"
);
echo json_encode(array($arrToJSON));
}

jQuery AJAX post to PHP everytime a click is fired off

I want to keep a record of every click that occurs within a specific DIV and child DIVS on page. The client should not be aware of this. Inside of the div is a link to an external website.
Client clicks link inside div > ajax inserts record in db > client is sent to site of link clicked
PHP on page
include('quotemaster/dbmodel.inc.php');
if(isset($_POST['dataString'])) {
clickCounter();
}
PHP Model Function
function clickCounter() {
global $host, $user, $pass, $dbname;
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
$stmt = $DBH->prepare("INSERT INTO clickcounter (counter) VALUES (1)");
$stmt->execute();
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
AJAX POST
$(function() {
$("body").click(function(e) {
if (e.target.id == "results" || $(e.target).parents("#results").size()) {
//alert("Inside div");
ajax_post();
}
});
})
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: dataString });
}
The problem I am having (I think) is that the AJAX post is not being sent. Any ideas? Thanks!
on your PHP you have
if(isset($_POST['dataString'])) {...
you are expecting a parameter named dataString so you can fix it on your javascript ajax_post function with something like
var postData={dataString:true, CC:1}
$.ajax({ type: "POST", url: "tq/--record-events.inc.php", data: postData });
this way jQuery will create the proper dataString parameter.
Hope this helps
Try changing the POST check to:
if(isset($_POST['CC'])) {
clickCounter();
}
Also, if your DIV contains a link that navigates away from the page, clicking the link may cause the page location to change before the event bubbles down to the body tag. If so, you could try attaching an event to the link which calls preventDefault and therefore allow the event to bubble. If so, you could then detect that the user clicked the link and perform the navigation manually after recording the click. To show code as to how this can be achieved you need to post your full div code (including the link).
To add callbacks to the ajax call:
function ajax_post() {
var dataString = 'CC='+1;
$.ajax({
type: "POST",
url: "tq/--record-events.inc.php",
data: dataString,
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}

Categories