A guide to accurately accessing form data in Jquery Ajax requests

My beforeSend function is not working properly, as the background color does not change. I suspect it may be due to not correctly referencing the id variable posted from the form. Below is the relevant HTML and JS code:

HTML

<div id="rec<?php echo $id; ?>"class="del_box">
 <form method="post" class="delform">
  <input name="id" type="hidden" id="id" value="<?php echo $id; ?>" />
  <input name="ad_link" type="hidden" id="ad_link" value="<?php echo $ad_link; ?>" />
  <input name="listing_img" type="hidden" id="listing_img" value="<?php echo $listing_img; ?>" />
  <button type="submit">Delete</button>
 </form>
</div>

JS

   $("document").ready(function() {
$(".delform").submit(function() {
    data = $(this).serialize();
    if (confirm("Are you sure you want to delete this listing?")) {
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "delete_list.php",
            data: data,
            beforeSend: function() {
                $("#" + "rec" + data["id"]).animate({
                    'backgroundColor': '#fb6c6c'
                }, 600);
            }
            success: function(response) {
                if (response.success) {
                    $("#rec" + response.idc).slideUp(600, function() {
                        $("#rec" + response.idc).remove();
                    });
                } else {
                    console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
                }
            },
            error: function() {
                alert("An Error has ocurred contacting with the server. Sorry");
            }
        });
        return false;
    }
});
});

CSS

.del_box {
background-image: none;
background-color:#9F9F9F;
}

Answer №1

It appears that you may not need the beforeSend function for what you are trying to achieve. Animating an object does not necessarily have to be directly tied to the Ajax request. You can simply perform the animation independently from the request, like this:

data = $(this).serialize();   
if (confirm("Are you sure you want to delete this listing?")) {
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "delete_list.php",
            data: data,   
        });
        $("#rec" + data["id"]).animate({'backgroundColor': '#fb6c6c'}, 600);
        return false;
    }

Answer №2

What is the reason for the separation of # from rec?

$("#" + "rec" + data["id"])

An alternative way to write this is:

$("#rec" + data["id"])

In any case, Ramsay Smith's response is correct!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to render a child div completely opaque using the opacity attribute

I am currently working on a popup feature that, when displayed, will blur the background of the page to a grey color. The .cover element is responsible for this overlay effect. Unfortunately, I am facing issues overriding its default opacity:0.6; property ...

Is there a way to prevent hover effects on the outer div when hovering over the inner div?

I am facing an issue with disabling hover effects on an outer div when hovering over an inner button. I have tried various methods but haven't been successful in achieving the desired outcome. .container { background-color: #e6e6e6; width: 400p ...

Is <form> tag causing code deletion after an ajax request?

I'm working on a form that looks like this: <form> <input class="form-control" id="searchField" type="text"> <button type="submit" id="searchUserButton">SEARCH BUTTON</button> </form> When I click on SEARCH BUT ...

Utilizing REST API calls for querying data in MongoDB

My goal is to send an XMLHttpRequest to mongoDB using AJAX to retrieve a document. This is the code I have written: function getJsonDocumentByModeldid(model_id) { var inputVal = document.getElementById('inputModelId').value; alert(input ...

Storing user's input data from a multi-step form into a cookie with the help of ajax

Is there a way to create a multipage form that saves data into a database, allows users to close their browser before completing it, and repopulates with previous session values when they return? I understand that using a cookie is necessary for this tas ...

Is there a way to make the text on my Bootstrap carousel come alive with animation effects?

My website features a Bootstrap Carousel with three elements structured like this: <a><img data-src="img" alt="Third slide" src="img"> </a> <div class="carousel-caption"> <h2> <u ...

Is there a way to prevent SignalR from disconnecting when the settings window is moved?

I am currently developing a webpage that utilizes SignalR events to trigger ajax requests to our servers. These requests return a URL with a custom URI scheme that, when accessed, opens up a specific program on the client's device without leaving the ...

After using JSON.parse(), backslashes are still present

Recently Updated: Received server data: var receivedData = { "files":[ { "filename": "29f96b40-cca8-11e2-9f83-1561fd356a40.png", "cdnUri":"https://abc.s3.amazonaws.com/" ...

Adjust the height of a <div> element to fit the remaining space in the viewport or window automatically

I am working with the following HTML code: <html> <BODY> <DIV ID="holder"> <DIV ID="head_area">HEAD CONTENT GOES HERE....</DIV> <DIV ID="main_area">BODY CONTENT GOES HERE</DIV> ...

Transferring an item from JavaScript to a controller method in MVC

Recently, I've encountered an issue with passing an object from a razor view to an action method. In my view: <section> <script type="text/javascript"> function saveExpense() { var expenseobject = { date:$(' ...

Encountering a JSON Parse error when using jQuery Ajax with the Wikipedia API

When I attempt to Parse JSON data using the Wikipedia API, the URL successfully returns json data. I am specifically looking for the snippet part of the search notation in the response, but encountering errors. I have included the code below for your revie ...

When jQuery's fadeOut function is used with a callback, two elements appear simultaneously when the action is performed quickly

This problem seems straightforward, but I've hit a roadblock. Here's the code snippet in question: When I quickly move through all the elements, both p.hidden and form remain visible despite the intended behavior. I attempted to include stop ...

Safari browser experiencing issues with JQuery Slider functionality

I am facing an issue with a slider that works perfectly in all browsers except Safari. I have been struggling to figure out the root cause of this problem. You can view the fiddler code here: http://jsfiddle.net/sjramsay/UyvvL/ It appears that when the co ...

Exploring the `zoom` CSS attribute and adjusting font sizes on Safari

While my website is somewhat responsive on desktop, the display on iPad or tablet-sized devices leaves much to be desired. Despite having an acceptable layout, everything appears too large, making navigation difficult. It's worth noting that my websit ...

The tag <li> is not allowing enough room for the content to expand as needed

I am trying to create a list using ul li elements. When the content inside the li exceeds the width, a scrollbar appears. However, I am encountering an issue where the li tag does not cover the entire width and spills outside. .container{ b ...

Cease animation upon hovering

I have an animated footer that opens, stays open for 5 seconds, and then closes. I want to prevent the closing animation if the mouse is over the footer. Below is the code snippet: if(jQuery('body').hasClass('page-template-template-home&ap ...

The background image does not appear on the animated div until the browser window is resized

Encountering an unusual problem - I have styled a div element using CSS to be initially hidden: .thediv { width: 100%; height: 87%; position: fixed; overflow: hidden; background-image: url(pics/FrameWithBG1280.png); background-attachment: fixe ...

retaining the scroll position of a window when refreshing a div

There's this issue that's been bothering me lately. I update the database via an ajax call, refresh the div, everything works fine, but it still scrolls to the top of the page. Here's what I have attempted: function postdislike(pid, user, ...

Bug with IOS double tap on Element UI VueJS select input element

Encountering a strange problem on iOS safari or chrome. When attempting to select an option from a dropdown input, the options show up correctly on the first tap, but when trying to actually select an option, it requires two taps to work properly. This is ...

WebDriver: Verify that the Ajax request does not return any data to populate the dropdown menu

Is there a way to verify with WebDriver that an Ajax call does not return any items to populate a drop-down list? I've experimented with various timeout and element waiting strategies, but none have been successful. Imagine this scenario from the ...