I am creating a small college project in PHP where I want to submit a form without refresh. I am using the following code, but it is not working as I expected.

usercss/demo.js

function newleadentryform(){ document.getElementById('RightPaneContainerDiv').innerHTML="<div id='leadgenerationformdiv'>"+ "<form id='form' 'action='#'>"+ "<table width='352' border='0' class='CSSTableGenerator' style='width: 45%;'>"+ "<tr>"+ "<td>&nbsp</td>"+ "<td>&nbsp;</td>"+ "</tr>"+ "<tr>"+ "<td class='leadgenerationformcss'>Lead Owner</td>"+ "<td><input name='leadowner' type='text' class='leadgenerationtextboxcss' id='leadowner' /></td>"+ "</tr>"+ "<tr>"+ "<td>"+ "<input type='button' id='submit' name='submit' value='Update' onclick='leadgenerationformvalidation()'/>"+ "</td>"+ "<td><input type='reset' value='reset'></td>"+ "</tr>"+ "</table>"+ "</form>"+ "</div><!-- leadgenerationformdiv-->"; } 

index.php

<!DOCTYPE html> <html> <head> <title>Examples of using jQuery Alerts</title> <script src="jquery.js" type="text/javascript"></script> <script src="jquery.ui.draggable.js" type="text/javascript"></script> <script src="jquery.alerts.js" type="text/javascript"></script> <link href="jquery.alerts.css" rel="stylesheet" type="text/css" media="screen" /> <!-- Example script --> <script type="text/javascript"> $(document).ready( function() { $("#submit").click( function() { jAlert('Example of a basic alert box in jquery', 'jquery basic alert box'); }); }); </script> <script src="userjs/demo.js"></script> </head> <body> </body> <a href="#" onclick='newleadentryform()'>New Lead</a> </p> <div> </div> </html> 

When I click on "New Lead" -link, a form should open, which contains a text field and an "Update" button, which should then submit the form without refresh.

How can I achieve what I am trying to do here? Thanks in advance.

3

3 Answers

You may better include html from file, not insert it as a string. You will see possible mistakes and it is a lot better editable. Or you may include it on page and hide it via css on the begining, then on clicking the "New lead" link just call $('form').show();. When you click update button, you want probably do an AJAX call, which can be easily done with the jQuery form plugin. Just include it and on the "Update" button click call $('form').ajaxForm({url: 'filethatsavesyourpostdata.php', type: 'post'})

3

You should be using AJAX for such. Also, fetching an HTML form through a function is not necessarily the best way, especially because you have static content in that form. It should be on the loaded page but instead of showing it, it should be hidden from the client until you click the New Lead link on the page.

So, what do you need to do in order to catch a click? You already figured it out by using the deprecated (not officially deprecated, yet) click-function, which is triggered when a click event occurs. However, it is adviced to use the on-function instead, and within that you should define your event and other arguments.

In order to skip the actual click event and disable page refreshing (it actually submits it as a real form on the specified method and action) we must use the preventDefault-function to cancel the default action, which in this case is the default browser behavior: submit a form when a submit button is pressed.

So now what we end up with is the actual sending of the form. In order to send it to the server, we should be using AJAX, like I mentioned in the beginning of the answer.

What AJAX does, is it basically creates an XMLHttpRequest object and sends it to the server to process and create a response to. The server then sends it back to the client, which reads it while the session is active. Websites that use this type of techique (or similar techniques) are known as dynamic webpages, where content may change during a session.

So what we do, is we create and send our request to the server for processing, and it then returns us something, which the client will then process and figure out. In this case I made it rather simple, and I am checking for the existance of the post field, and the length of the post field. If the post field does not exist, it will return bad-post. And if the value is less or more than my specified amount, which in this case is five (5) and twenty (20), it will return bad-length. But if all went well, it will return success, which is the response the client is normally expecting. This is then processed client-side and the browser will output an alert box to the client explaining what we just received.

index.php

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Examples of using jQuery Alerts</title> <link href="jquery.alerts.css" rel="stylesheet" media="screen" /> <style> #lead-container { margin-left: 11px; display: none; height: 90vh; float: left; } #lead-container form { border: 0; width: 45%; } </style> <script src="//"></script> </head> <body> <a href="#">New Lead</a> <div> <form name="lead-creator"> <table> <tr> <td>Lead Owner</td> <td> <input type="text" name="lead-owner" /> </td> </tr> <tr> <td> <input type="submit" name="submit" value="Update" /> </td> <td> <input type="submit" name="reset" value="Reset" /> </td> </tr> </table> </form> </div> <script> var isBeingSent = false; $(document).ready(function(){ // We want to prevent default browser behavior when clicking the input buttons or the "New Lead" link $("#create-new-lead, #submit-button, #reset-button").on("click", function(e){ e.preventDefault(); }); // We want to display the lead-container when we click the "New Lead" link $("#create-new-lead").on("click", function(){ if (!$("#lead-container").is(":visible")) $("#lead-container").show(); }); $("#submit-button").on("click", function(){ // We stop executing the event if the operation is already running if (isBeingSent == true) return false; // We mark the operation running to avoid simultaneous actions isBeingSent = true; // We send a post request to the server $.post( "handler.php", // The file, which we are sending data to { leadowner: $("#lead-owner-field").val() }, // The data, which we are sending function(result){ // The returning function when the operation is complete isBeingSent = false; if (window.console) console.log('Returned: [' + typeof(result) + '] ' + result); if (result == "success") { alert('All went well!'); }else if (result == "bad-length") { alert('Hmm, the value is too small, or too lengthy!'); }else if (result == "bad-post") { alert('Ouch, something went very, very wrong...'); }else{ alert('Wops! Returned: [' + typeof(result) + '] ' + result + '.'); } } ); }); // We reset the input field when we click the "Reset" button $("#reset-button").on("click", function(){ $("#lead-owner-field").val(""); }); }); </script> <script src="jquery.ui.draggable.js"></script> <script src="jquery.alerts.js"></script> </body> </html> 

handler.php

<?php // Did the client send us a valid post request? if (!isset($_POST["leadowner"])) die("bad-post"); // Sanitize and finalize the input value $finalizedValue = preg_replace("/[^\w\s\.\-]/", "", $_POST["leadowner"]); // Compare the length of the input value against our specified values if (strlen($finalizedValue) < 5 || strlen($finalizedValue) > 20) die("bad-length"); // If all went well, just return a success message die("success"); ?> 

I hope this helped you out with your problem.

EDIT: Improved code layout and added comments to explain the functionality.

You can do it like:

<!DOCTYPE html> <html> <head> <title>Examples of using jQuery Alerts</title> <script src="//"></script> <!-- Example script --> <script type="text/javascript"> $(document).ready(function() { $("#submit").click(function() { alert('Example of a basic alert box in jquery', 'jquery basic alert box'); }); $("#testing").click(function() { $("#RightPaneContainerDiv").show(); }); }); </script> <script src="userjs/demo.js"></script> </head> <body> <a href="#" onclick="newleadentryform()">New Lead</a> <p></p> <div> <div id='leadgenerationformdiv'> <form id='form' action='#'> <table width='352' border='0' class='CSSTableGenerator' style='width: 45%;'> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td class='leadgenerationformcss'>Lead Owner</td> <td> <input name='leadowner' type='text' class='leadgenerationtextboxcss' id='leadowner' /> </td> </tr> <tr> <td> <input type='button' id='submit' name='submit' value='Update' onclick='leadgenerationformvalidation()' /> </td> <td> <input type='reset' value='reset'> </td> </tr> </table> </form> </div> </div> </body> </html> 

Check plunker:

0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy