Transferring user input from UI Dialog using AJAX requests

Check out this code snippet:

HTML

<div id="resume-begin" style="background:#CCCCCC; display:inline-block;">
    <img src="/images/plus-plus.png" style="display:inline;" class="trigger"/>
</div>
<div class="input-resume-data" style="display:none;">
    <form id="project-form">
        <label for="resume-create-name">Resume Project Name:</label>
            <input type="text" id="resume-create-it" name="resume-create-it" class="text ui-widget-content ui-corner-all">
    </form>
</div>

jQuery

<script>
    $(document).ready(function() {
        $('#resume-begin').click(function() {
        ('#resume-begin').hide();
        $('.input-resume-data').dialog("open");
        });
    });
</script>

When the #resume-begin div is clicked, it triggers a UI Dialog box to open. Here's the jQuery code for it:

<script>
    $(function() {
        $( ".input-resume-data" ).dialog({
            title: 'Name your Resume Project',
            autoOpen: false,
            resizable: false,
            height: 450,
            width: 380,
            show: { effect: 'drop', direction: "up" },
            modal: true,
            draggable: true,
            buttons: {
                "Submit": function() {
            var $this = $(this);
        var string = $('#resume-create-it').serialize();
                $.ajax({
                    url: 'functions.php',
                    type: 'POST',
                    data: string,
                    success: function(data){
            alert("Project created!");
                        $this.dialog('close');
                    }
                });
            },
                Cancel: function() {
                        $( this ).dialog( "close" );
                $( "#resume-begin" ).show( "slow", function() {
                        });  
                }  
            } 
        });  
    }); 
</script>

I want to save user input from the UI dialog to a database via PHP. Although the success message pops up after clicking Submit, the data doesn't get stored in the database.

In my PHP script, I fetch the submitted data like this:

//Sanitize the POST values
$resumeProjectname = $_POST['resume-create-it'];

I'm not sure if I'm handling and passing the data correctly through the "string" variable in jQuery or retrieving it properly in the PHP file.

Your assistance on this matter would be greatly valued. Feel free to ask any questions!

Thank you.

Answer №1

While reviewing the code, I noticed two mistakes:

    ('#resume-begin').hide();//$ missing

and also this line:

var string = $('#resume-create-it').serialize();

should actually be:

var string = $('#project-form').serialize();

Because serialize should be applied to a Form. https://api.jquery.com/serialize/

Answer №2

Follow these steps to send your data:

data: {
    resume_name: string
},
dataType: "json"

In PHP, retrieve the data using:

$resume_name = $_POST['resume_name'];

A quick note, avoid naming variables as string since it is a common keyword in many programming languages. Also, use different variable names like response instead of data to prevent confusion.

Important point: Although JSON is not mandatory, setting the dataType helps jQuery format the response correctly. Using JavaScript Object Notation (JSON) is recommended since you are already working with JavaScript.

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

Troubleshooting problems with PHP mailer on Godaddy hosting

I'm having an issue with my contact us page on my website. I've created the PHP mailer code to send emails to users, but whenever I click the submit button, I get the error message (SMTP Error: Could not connect to SMTP host). Can anyone please h ...

Resolve DOMdocument error in Codeigniter

When I try using @$this->dom->loadHTML($page); to suppress an error in CodeIgniter, it doesn't seem to work as expected... I keep getting a series of errors logged: ERROR - 2012-07-17 16:36:27 --> Severity: Warning --> DOMDocument::loadHTML ...

Stop all AJAX calls and timers immediately

I need to terminate an ajax request along with its timer that is being executed within a function: var run_timer; var run; function myrequest() { if(run && run.readystate != 4){ run.abort(); } run = $.ajax({ type:"POST", ...

Inspecting Facebook links

Currently working on a website and interested in incorporating a feature similar to what Facebook has. I'm referring to the link inspector, but I'm not entirely sure if that's its official name. Allow me to provide an example to clarify my r ...

When choosing from the drop-down menu, the selected box displays the ID instead of

Season's Greetings to everyone. Is everyone having a fantastic time? I am confident that my assumption is correct. Can someone assist me with this issue? I am puzzled as to why this code is returning the ID instead of the value when binding data from ...

Should I use the default or a custom salt with the PHP password_hash() function

Seeking advice on the best method for encrypting user passwords, I am considering three options and would appreciate some guidance. 1. Option: Default Salt with password_hash() $passwordInput = $_POST['password']; $passwordHash = password_hash( ...

Execute a timed PHP script within the WordPress platform to store information in a MySQL database

Looking for advice on setting up a daily PHP script to save database data persistently. What's the most straightforward method to accomplish this task? Does Wordpress offer a scheduler event feature that can execute PHP code at specified times? Or ...

PHP functionality for extracting JSON data

I need help extracting only "SUCCESS" from the JSON data on the server using PHP. The desired output is the value of "status": "SUCCESS" which is nested within the data object. { "response":{ "status":true, "statusCode":"0", "stat ...

What are the top methods for interacting between Server APIs and Client-Side JavaScript?

Presently, I am utilizing setTimeout() to pause a for loop on a vast list in order to apply some styling to the page. For example, For example: How I utilize setTimeOut: I use setTimeout() to add images, text and css progress bars (Why doesn't Prog ...

The functionality of jQuery autocomplete is hindered when trying to utilize a remote data source

HTML: <input type="text" id="shop-id"> JS: $(document).ready(function(){ $( "#shop-id" ).autocomplete({ source: "/ticket/get_sids", select: function(event, ui){ //... } }); }); Encountering an unusual i ...

Send data from an AJAX request to a Laravel controller

Here is the code for my ajax request where I am trying to pass values to a controller in Laravel. var deviceid="<?php echo $id; ?>"; var day="<?php echo $day; ?>"; $.ajax({ 'async': false, 'global': false, url ...

What is the process for modifying a Gist on GitHub?

Trying to update my Gist from another website using my gist token has been unsuccessful. Retrieving a gist with GET was successful, but updating it with PATCH is not working. I don't believe authentication is the issue since retrieving the gist displ ...

PHP String Wrapping

I'm currently facing an issue with my code. I have a piece of code that creates an image from an external source of an image and a string. The string is retrieved using json data. The problem arises when I use the string obtained from the json data a ...

When using json_decode, the first character of string numbers will have the zero removed

When passing a phone number (which is a string) with a leading zero to the json_decode function, it ends up removing the first zero character and converting it into a float number. $phoneNumber = '09178882356'; //dynamic value echo json_decode($ ...

Sending data via an AJAX POST request in the request parameter

I have a question regarding the method of making a POST request in my code: $.ajax({ url :"/clientCredentials.json", type: "POST", data: { "clientEmail": email, "clientName":clientName, "orgName":orgName, "l ...

React Server side error: Router.use() expects middleware function instead of a string

Currently, I am in the process of preparing my server to handle ajax calls. As part of my learning journey with React, I have been exploring server-side functionalities. While following various tutorials, I configured the server.js to connect with a postgr ...

Combining the power of jQuery, PHP, JavaScript, and the popular WordPress platform, let's unlock

After going through numerous attempts to find answers for similar issues, I'm unable to get any of the suggested solutions to work. My WordPress site requires a plugin that utilizes jQuery. The main file for my plugin is located at wp-content/plugins ...

Identifying a failed Ajax Request in JavaScript

How can I check if an Ajax request failed to load a file? Here is the code I'm currently using: var pro = undefined; var xmlhttp; if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTT ...

Tips for saving a PHP variable in an HTML attribute

I am working on a page that allows users to select colors from a list using checkboxes. When the user submits their selections, I want all the chosen colors to be displayed with their corresponding color as their font color. Below is the code I have so fa ...

Understanding the `readfile()` function jargon

When a function's result is sent to the output buffer, it means that the result will not be visible until echoed. For functions that output directly, we use ob_start to direct the result to the output buffer before it reaches the browser as plain html ...