I encountered a difficulty when trying to update form data in MySQL utilizing PHP and jQuery

So here's the situation: I've managed to insert and delete records from a form using jQuery and PHP scripts to interact with a MYSQL database. However, I'm facing a challenge when it comes to updating data that has been retrieved from the database. Let me explain the file structure:

In index.php, there are jQuery functions that display a form for adding new data to MYSQL using save.php. Additionally, all records are displayed without refreshing the page by calling load-list.php from index.php, which works smoothly. The delete function in index.php also successfully deletes a record from the MySQL database by calling delete.php.

The issue arises with the update function called from index.php to update data using update-form.php after retrieving a specific record from the MySQL table. While the update process works fine up to this point, there seems to be a problem when trying to transfer data from update-form.php to update.php, where the actual update query for MySQL is written.

The main problem lies in transferring data from update-form.php to update.php (where the update query is executed in MySQL).

I've attempted various approaches, and upon investigation, I discovered that the data isn't being transferred from update-form.php to update.php. There appears to be an issue with the jQuery AJAX function as it fails to send data to the update.php page. Something crucial is missing in the way update.php is being called; it never gets accessed.

If you'd like to review the files related to this, please use the link below to download a ZIP file containing all the necessary documents (virus-checked):

Download mysmallform files in ZIP format, including MySQL queries


<pre>
<body>
<div class="container">  
    <form id="submit" method="post">  
        <fieldset>  
            <legend>Enter Information</legend>  
            <label for="Name">Name    : </label>  
        <input id="name" class="text" name="name" size="20" type="text">
            <label for="gender">Gender : </label>  
            <input id="gender" class="text" name="gender" size="20" type="text">
            <label for="dob">DoB     : </label>  
            <input id="dob" class="date" name="dob" size="20" type="text">  <button> Add  </button>  
        </fieldset>
    </form>  
    <div class="name_list"></div>
    <div class="update_form"></div>  
</div>

<script type="text/javascript">
$(document).ready(function(){
    function loadList(){
        $.ajax({
            url: "load-list.php",
            cache: false,
            success : function(html){
                $(".name_list").html(html);
            }
        });
    }
    loadList();

    $("form#submit").submit(function() {
        // we want to store the values from the form input box, then send via ajax below
        var x=window.confirm("Are you sure you want to delete this item?")
        var name = $('#name').attr('value');
        var gender = $('#gender').attr('value');
        var dob = $('#dob').attr('value');
        if (x==true){
                     $.ajax({
                type: "POST",
                url: "save.php",
                data: "name="+ name +"& gender="+ gender +"& dob="+ dob,
                success: function(){
                    loadList();
                               }
                 });
                 }
        return false;
    });

    $(".delete_button").live("click", function(){
        //this deletes the row clicked on with an alert and then reloads the list
        var id = $(this).attr("id");
        var x=window.confirm("Are you sure you want to delete this item?")
        if (x==true){
            $.ajax({
                type: "POST",
                url: "delete.php",
                data: "id="+ id,
                success: function(){
                    loadList();
                }
            });
        }
        return false;
    });

    $(".update_button").live("click", function(){
        //this loads the update form
        var id = $(this).attr("id");
        $.ajax({
            url: "update-form.php",
            data: "id="+ id,
            cache: false,
            success: function(html){
                $(".update_form").html(html);
            }
        });
        return false;
    });

      $("#updateform").ajaxform("submit",function(){
    //$("form#update").live("submit",(function() {
    // we want to send via ajax and empty the html from the update_form element
        var name = $('#name_update').attr('value');
        var gender = $('#gender_update').attr('value');
        var dob = $('#dob_update').attr('value');
        var id = $('#id').attr('value');
        alert (name);
            $.ajax({

                url: "update.php",
                type: "POST",
                data: "name="+ name +"& gender="+ gender +"& dob="+ dob,
                error: function(){
                    alert('Error loading document');
                             },
                success: function(){
                alert (" i  am  in success below load list ");
                    $(".update_form").empty();
                    loadList();

                        }

            });
        return false;
    });
});
</script> </body>
</pre>

Answer №1

After pasting your code into a PHP file, I encountered an error stating "$ is not defined" in JavaScript. Upon reviewing your code, it appears that you may have forgotten to include the jQuery file. I recommend utilizing Firefox as your browser and Firebug for debugging purposes to prevent encountering these minor issues in the future.

Answer №2

It is worth mentioning that JQuery offers a post function as well. There is no issue with using basic HTML to manage requests. It is not necessary for everything to be processed through listeners.

function updateQuery(){

    var name = $('#name_update').attr('value');
    var gender = $('#gender_update').attr('value');
    var dob = $('#dob_update').attr('value');

    $.post('update.php', { name:name, gender:gender, dob:dob }, function(data){
        if(data == 'success')
            {
                $(".update_form").empty();
                loadList();

            }
            else
            {
                alert('fail');
            }
    });
}

Answer №3

There are times when jQuery may not cooperate well with single variable $.post requests. Have you experimented with introducing a second null variable?

I haven't examined your code, but if the add and delete functionalities are functioning correctly, then the update feature should work as well unless there's an obvious oversight or you're encountering the same issue with single variable calls that I previously experienced.

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

Using a foreach loop to update the database is causing the array to be altered prior to

There seems to be an issue with my PHP code where the last key in the array is getting somehow changed during a foreach loop while updating data for football teams in a table. Before the loop: [18] => Array ( [team_code] => ...

Is this session/token authentication mechanism suitable for my web API?

Today, I successfully implemented a session and token authentication system for my web api using http get/post rpc style. Here is the plan I followed: Key: action (param1, param2) : returnvalue1, returnvalue2 login (username, password) : sessionkey, tok ...

The Rails text area fails to load through JavaScript when a line break is detected

My comment form has a feature that displays the content of the text area using js. It functions properly unless a new line is entered in the text area, in which case it does not show up right away. However, after refreshing the page, the comment appears wi ...

Using ASP.NET MVC 5, connect JSON to the action parameter

I encountered a problem while developing a basic app using ASP.NET MVC 5. The issue arose when I attempted to convert JSON into an entity. Below is the code snippet: Entity public class PlayListViewModel { public PlayListViewModel() { Track ...

The Ajax request is successfully looping through multiple files, however, it is not properly sending them to the server. As a result, only one file

I have been working on an ajax request that successfully retrieves information about files, such as the number of files, their names, and looping through them. Now, I am faced with the challenge of saving these files to a local folder on my computer. I hav ...

Is it possible to use jQuery to initiate a change event without losing focus

Here is a script that I am currently using: $(".b").hide(); $(".uid").bind("change", function() { if($(this).val().length>0) { $(".b").show(); } else { $(".b").hide(); } }); The current functionality requires me to click ou ...

Presenting Findings Generated by the AWS CloudSearch Solution

Looking for a solution to efficiently display JSON results from AWS CloudSearch? Check out the example link provided below. I want to create a user-friendly interface that integrates facet functionality and is easy to implement. Attached is a demo search i ...

Leveraging AJAX for fetching data from a deeply nested JSON structure

My AJAX request is functioning properly: $.ajax ({ url: 'api.php', type: 'GET', data: {search_term: data}, dataType: 'JSON', success: function(data) { $('#div').html('<p>Consti ...

Determining if a URL is a subdomain URL using PHP

I created a function to check whether a URL is a subdomain URL or not. <?php header("Content-Type: text/plain"); function checkSubDomain($url) { $url = parse_url($url)["host"]; if(strstr($url,'.',true)=='www') { ...

What are the steps to validate an Ajax form using Dojo JavaScript?

Currently, I am in the process of validating a form that has been written in Javascript/Dojo before sending it via Ajax. Here is the code snippet: <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6/dojo/dojo.xd.js" type="text/javascript" djConf ...

Obtaining IDs of Divs that have been Dragged into a Drop Zone upon Clicking a Button using JavaScript

I'm currently working on a solution to extract the ids of dragged divs once they have been placed in the drop zone. Each drag component is assigned an id ranging from drag1 through drag8, while the drop zone is labeled as div drop zone. Since there a ...

Having trouble loading items into the dropdown menu

Having trouble getting my drop down list to populate. I'm trying to retrieve data from a service class function. Currently, I am utilizing Ajax calls, a Servlet, and HTML for this task. If you have any examples that involve using a Servlet class, Aj ...

Connecting a Router with CakePHP

Router::connect( 'mylogin', array('controller' => 'User', 'action' => 'xyz', 5) ); Is there a method for transforming the string '/User/xyz/5' stored in a database into an array arr ...

Using jQuery with ASP.NET DropdownList allows for dynamic manipulation of dropdown lists

Currently, I have multiple dropdown lists and I am looking to change the event handler for each one. Specifically, when a particular item is selected from a dropdown list, I want the event to be triggered only for that specific dropdown list. Below are two ...

Is the user consistently experiencing redirection to a failure page with passport?

I've been struggling with the user login redirection issue on my website. No matter what changes I make, it keeps redirecting to failure instead of success. I'm not sure if I missed something or did something wrong. The documentation for passport ...

In what way can I incorporate additional functions or multiple functions within an Express route to modify database information?

Currently, I am working on a project that involves Express and MySQL. One of the challenges I am facing is retrieving data from a connection.query and then utilizing that data in other functions within the same route. My goal is to use the array created in ...

Display the input in the text box before making a selection from the dropdown menu

Latest Technologies: $(document).ready(function(){ $('#userID').change(function(){ $('#username').val($('#userID option:selected').data('username')); }); }); Coding in HTML: <select class="form- ...

Escaping single quotes within parameters of PDO prepared statements

It seems that using PDO Prepared Statements protects against SQL injection and ' escapes. I recently tested the following code... if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["id"])) { $id = $_POST["id"]; //$id = "2&ap ...

Struggling with Implementing jQuery for Triggering Multiple Functions on a Single Change Event?

I am currently developing jQuery functions that create dependencies between the css classes of different inputs in a web form. For example, when a specific input has a certain value, the "hide" class is removed from another input. One working example of t ...

Incorporate External Data Source into Magento Admin Products Grid

I'm working on creating a split screen view with one grid displaying products from a remote repository, and another grid showing products from a local repository. To simplify things, all I really need help with is incorporating the remote source into ...