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

I am utilizing client-side JS to send a large number of requests. What methods can I implement to enable my server to cache this content

Here's a bit of an unusual question from someone who is new to this - I have client-side JavaScript that is making API calls using the getJSON method. Since the content doesn't change frequently, I would like to store the results on my server an ...

CSS grid is organizing itself neatly on larger screens

I'm currently facing an issue with displaying a CSS grid on my page. When viewed on desktop, the grid appears stacked up instead of in separate columns. I've tried various methods like dividing it into 4 columns and using spans for width but noth ...

Where can I find the JavaScript code that controls the button function?

Is there a method to identify the trigger that activates a button's specific action and page refresh, such as this example: <input type="submit" name="name" value="some value" id="mt1_main_btn" class="btn_next"> Simply copying the button does ...

Issue with Font Awesome 5 icons not displaying properly after integrating Bootstrap

Trying to spruce up my buttons by adding some fontawesome icons from bootstrap. The icons I'm using are: fas fa-user fas fa-users They display fine without any styling. However, when I apply the bootstrap button css, the "fa-users" icon appears as ...

Is it possible to use jQuery to create a slide-up effect from the

Could I reverse the animation direction of my dropdown menu? Currently, it expands from the top to bottom. Is there a way to make it expand from the bottom to the top? Code snippet: animate({height:'show',opacity:'show'}, ddsmoothmenu ...

Having trouble with my $.ajax() call function, it's not behaving how I expected

When I send an ajax request like this: $.ajax({ type: "POST", url: "/videos", data: { title: oembed.title } }); within the function call to the Embedly API: $('a.oembed').embedly({maxWidth:300,'method':'replace'}). ...

The cascading dropdown feature is not displaying the dropdown options

Currently, I am in the process of developing a dependent dropdown feature where users can select a specific shop based on their region (south, north, east, west). To achieve this functionality, I have set up a database with four columns - id, region_id, re ...

Struggling to show labels in the correct position for each button?

I need help with aligning labels under buttons. I have 3 buttons, each with a corresponding label. I want the labels to be displayed in line under the buttons, and if the length of a label exceeds the button width, it should wrap to the next line. I'v ...

The mobile menu toggle functionality is malfunctioning on actual mobile devices, however, it is operational when tested on various mobile sim

Recently, I noticed that on , the menu collapses into a hamburger icon for mobile. However, when tapping on it on my phone and other devices, nothing happens. Surprisingly, it works perfectly fine when clicking on it in mobile simulators within Google Chro ...

Show product name when hovering over the image

Trying to achieve a hover effect where product titles appear in a contained box when hovering over the product image on the bottom overlay, instead of below the image itself. Tried CSS code recommended by Shopify, but it had no effect: <noscript> ...

The collapsible navbar vanished, where did it go?

While experimenting with the carousel template page, I noticed that the NavBar collapses when the screen width is reduced below a certain pixel size. Initially, everything was working fine as intended. However, after making some modifications to the carou ...

What could be causing the div to not respond to ngAnimate?

Recently, I encountered an issue with adding animations to a list of <div>'s in my webapp. After incorporating ngAnimate into the app.js file and including ng-animate="'animate'" in the <div>, I was disappointed to find that the ...

Bringing PHP Back into the World of Ajax

I created a form for users to upload new avatars and now I am experimenting with using AJAX to display error messages on the same page if any occur. However, my current issue is that the AJAX call is not receiving any response from the PHP file it's c ...

Building HTML tables with JQuery for handling large datasets of over 4,000 rows and beyond

My goal is to create a table with 4000+ rows and 18 columns displaying parsed pages from my site. I need it all on one page for the following reasons: I require the use of filters in the table I need to be able to sort by more than 5 columns Every cell ...

Ways to manage drag and drop functionality within Cypress when traditional Cypress techniques are not effective

I need help with the drag and drop function in Cypress. I have tried three different methods but none of them seem to work. I have included my code below, which is not functioning as expected. Does anyone have any suggestions on what might work better in t ...

Confirm that the input into the text box consists of three-digit numbers separated by commas

Customers keep entering 5 digit zip codes instead of 3 digit area codes in the telephone area code textbox on my registration form. I need a jQuery or JavaScript function to validate that the entry is in ###,###,###,### format without any limit. Any sugge ...

Send the id of the chosen row to the Component tag within the blade file

I'm working on passing the id of the currently selected row within a for loop when it's clicked on. The goal is to then pass that id to a Vue component. In my index.blade file: @foreach($cats as $cat) <tr> <td class="catme" d ...

Utilizing an array of font styles in a single line while maintaining a consistent width

I am creating a simple webpage with fixed width text. Check out this sample HTML: <div id ="wrap"> <h1>An Annoying Heading</h1> <p>Some text some text some text some text some text some text some text some text some text so ...

Send error messages directly to the client side or retrieve status codes and messages

When responding to an AJAX request, encountering an app error like data validation failure can be tricky. How can we effectively communicate this to the user? 1. Returning a Status Code and Fetching Message with JS $.ajax(options).done(function(response) ...

Adjust the content to expand and occupy the entire height using Material UI cut-off Drawer

I am using the provided Material UI code for a persistent clipped drawer, but I am encountering an issue with the content height. I have set the background of the content section to red in my demo sandbox to showcase the problem. My goal is for the content ...