Displaying HTML with extracted message form URL

I have a link that redirects to this page

Is there a way for me to extract the message "Message Sent Successfully" from the URL and display it in the form below?

<form action="send_form_email.php" name="contactForm" method="post">
    //I want to display the message here
    <h4>E-mail</h4>
    <div class="border-stripes">
        <input type="email" class="textfield" name="email" placeholder="Your e-mail address" />
    </div>
    <h4>Message</h4>
    <div class="border-stripes">
        <textarea class="textarea" name="message" rows="3" placeholder="Your message"></textarea>
    </div>
    <br />
    <br />
    <input id="submit" name="submit" type="submit" value="Submit">
</form>

Answer №1

The following code will display the GET variable:

<?php echo urldecode($_GET['msg']); ?>

Answer №2

To achieve this in JavaScript, you can utilize query string parsing as shown below:

var queryString = (function() {
    function decodeString(string) {
        return decodeURIComponent(string.replace(/\+/g, " "));
    }
    var result = {};
    if (location.search) {
        location.search.substring(1).split('&').forEach(function(pair) {
            pair = pair.split('=');
            result[decodeString(pair[0])] = decodeString(pair[1]);
        });
    }
    return result;
})();

$('form[name=contactForm]').prepend('<p>' + queryString['msg'] + '</p>');

Answer №3

Javascript Function to Retrieve URL Parameters:

Below is a function that allows you to retrieve any parameter from a URL:

function getParamValue(parameterName) {
    parameterName = parameterName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexString = "[\\?&]" + parameterName + "=([^&#]*)";
    var regex = new RegExp(regexString);
    var results = regex.exec(location.href);
    if (results == null)
        return "";
    else
        return decodeURI(results[1]);
}

alert(getParamValue('param'));

Check out the solution here: http://jsfiddle.net/tb8cetLy/1/

Answer №4

To accomplish this task using PHP (keep in mind that there is no security check for XSS vulnerabilities)

<form action="send_form_email.php" name = "contactForm" method="post">
                    <?php echo urldecode($_GET['msg']); ?>
                    <h4>E-mail</h4>
                    <div class="border-stripes"><input type="email" class="textfield" name="email" placeholder="Your e-mail address" /></div>
                    <h4>Message</h4>
                    <div class="border-stripes"><textarea class="textarea" name="message" rows="3" placeholder="Your message"></textarea></div><br /><br />
                    <input id="submit" name="submit" type="submit" value="Submit">
</form>

Alternatively, you can achieve this with JavaScript

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var msg = getParameterByName('msg');
$( "form" ).prepend( "<p>"+msg+"</p>" );

The getParameterByName function has been sourced from this site

Answer №5

If you have a file called send_form_email.php, you might be handling form data like this:

// processing form data
// redirecting to index.html with $_GET['msg'] variable

To create cleaner URLs, you can use the following function and add it to your common file:

session_start();

function flash_set($key,$value)
{
    $_SESSION['flash'][$key] = $value;
}

function flash_get($key)
{
    if(isset($_SESSION['flash'][$key]))
    {
        $message = $_SESSION['flash'][$key];
        unset($_SESSION['flash'][$key]);
        return $message;
    }
    return '';
}

Modify the send_form_email.php to redirect without any $_GET parameters. After processing the form, add this snippet:

// processing form data
flash_set('form','Message Sent Successfully');
// perform redirect

Now, integrate this into your form as follows:

<form action="send_form_email.php" name="contactForm" method="post">
<?php echo flash_get('form')?> // Display message here
<h4>E-mail</h4>

The flash message will only display once after redirection. If the user refreshes the page, it will disappear!

Answer №6

To decode a URL parameter in HTML/PHP, you can use the code urldecode($_GET['msg'])

If you prefer to do it with JavaScript, you can use the following function:

function getQuerystring(key, default_) {
    if (default_==null) default_=""; 
    key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if(qs == null)
        return default_;
    else
        return qs[1];
}

This function allows you to retrieve the 'msg' parameter using var msg = getQuerystring("msg");, and you can combine it with escape functions (http://www.w3schools.com/jsref/jsref_unescape.asp).

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

How to transform multi-dimensional arrays to JSON format using JavaScript (and maybe jQuery)

Currently facing a Javascript dilemma where data storage is essential in the following format: MainArray(Array(JavaScript Object, JavaScript Object, etc etc..), Array(JavaScript Object, JavaScript Object, etc etc..), etc etc..) The main array consists of ...

Confusion surrounding the concept of returning an arrow function from a Vuex storage getter

I delved into a Vuex course and the journey was smooth sailing until they introduced an arrow function in a getter, then utilized it in a computed property and action. Behold the code: item structure: const _products = [ { id: 1, title: "iPad 4 Mini", ...

Guide on displaying the name attribute of a button along with its price in a separate div when clicked

Upon clicking the Koala button, I want to display a message showing the id name of the button and the corresponding price for Koalas. Here is the HTML code snippet: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <link h ...

The Upstash Redis scan operation

Attempting to utilize the @upstash/redis node client library for Node.js (available at https://www.npmjs.com/package/@upstash/redis), I am facing challenges in executing the scan command, which should be supported based on the documentation. Specifically, ...

When scrolling, use the .scrollTop() function which includes a conditional statement that

As a newcomer to jQuery, I've been making progress but have hit a roadblock with this code: $(window).scroll(function(){ var $header = $('#header'); var $st = $(this).scrollTop(); console.log($st); if ($st < 250) { ...

Error encountered while attempting to start session

I created a function to monitor user session time in my code. function sessionTracker(){ ini_set('session.cookie_lifetime', 86400); ini_set('session.gc_maxlifetime', 86400); $sid = session_id(); if ($sid != '' ...

Best practice for incorporating Bootstrap into Webpack

Greetings everyone, I've been experimenting with Bootstrap for Webpack, but I've hit a roadblock. After reading numerous blog articles, I found that they either rely on the outdated 'bootstrap-webpack' plugin from 7 months ago (which d ...

Adding options to a dropdown menu using jQuery and Ajax technique

After retrieving data from an Ajax call and attempting to append option values to a dropdown generated in jQuery, it doesn't seem to be working as expected. Here is the code snippet: $(document).on('focusout', '.generate', functio ...

What could be causing the video to extend beyond the limits of the container?

When extending the result window, the video ends up overlapping the section below it. I am looking to keep the video within the confines of the section's height, which is set to height:100vh. Is there a way to accomplish this? Check out this jsFiddl ...

Using the CSS property `transform:scale(2,2)` causes an image to suddenly appear in the

Currently utilizing Joomla 3.3, I am seeking to enlarge an image on mouseover. The html code for the image is as follows: <img class="enlarge" style="float: right; margin: 10px; border: 5px solid black;" title="Chapter 1: Physical Differences" src="im ...

Guide on importing an external JavaScript library in Node.js utilizing a TypeScript declaration file

I am working on a Node.js project using Typescript and I am facing an issue with integrating mime.js (https://github.com/broofa/node-mime). Even though I have a declaration file available (https://github.com/borisyankov/DefinitelyTyped/blob/master/mime/mim ...

Secure your Flask forms with CSRF token validation middleware

I'm handling an html form and want to make sure that all submissions originate from my website. I've noticed others using a key for this in Django, and I'm considering implementing something similar. Is there a recommended approach for achie ...

How to retrieve the value from an editable td within a table using Jquery

I am working with a dynamic table that looks like this: <table> <tbody> <tr> <td>1</td> <td contenteditable='true'>Value1</td> </tr> <tr> ...

Executing operations in the background in Laravel 4.2

Dealing with a specific condition that requires me to initiate an iperf server as a daemon on a designated port and send a response to the client if the server is running. My attempt using shell_exec('iperf -s -p {port} -D'); didn't quite ...

The art of transforming properties into boolean values (in-depth)

I need to convert all types to either boolean or object type CastDeep<T, K = boolean> = { [P in keyof T]: K extends K[] ? K[] : T[P] extends ReadonlyArray<K> ? ReadonlyArray<CastDeep<K>> : CastDeep<T[P]> ...

Looking to confirm client-side text in NodeJS?

As I work on constructing a to-do list, one challenge I am encountering is confirming that the correct task has been checked off. While considering using unique IDs for each individual task may seem like a solution, there is still the risk of users manipul ...

Unable to retrieve data from PHP using AJAX request

My project consists of 3 interconnected files: index.php, functions.js, and compute.php In index.php, there is a div that triggers a function in functions.js called compute(), which sends an AJAX request to perform a task in compute.php The code in index ...

Using Typescript: invoking static functions within a constructor

This is an illustration of my class containing the relevant methods. class Example { constructor(info) { // calling validateInfo(info) } static validateInfo(info):void { // validation of info } I aim to invoke validateInfo ...

Empty jQuery $.ajax value after post

I'm encountering an issue where my code's post value appears to be empty. I have attempted to echo the key and value using a foreach loop, but it only shows "0 Array." This is what my code looks like: <script type="text/javascript"> $(doc ...

Tips for successfully installing a package through npm

Looking to set up nest.js Using the guide provided below. https://www.npmjs.com/package/@nestjs/cli Attempted the following command $ npm install -g @nestjs/cli Encountered this error message. bash: /usr/local/bin/npm: No such file or directory Any ...