iwato Posted February 8, 2018 Share Posted February 8, 2018 (edited) BACKGROUND: Using AJAX I have successfully filled a <div> element with HTML that contains a <form> element whose action attribute points to a $_SERVER_REQUEST superglobal in the same filled <div> element. I have also set the target attribute of the <form> element to _self. Unfortunately, when the <input type='submit'> form control is clicked the entire page is replaced. I want only that the contents of the <div> element is replaced. DILEMMA: I want to suppress this replacement behavior, but still process the form data with the PHP contained within the <div> element. Although I have managed to suppress the replacement, I do not know how to process the form data within the <div> element. The CODE: .click(function() { $("#main").html(''); $.ajax({ url: './_utilities/php/newsletter_filler.php', method: 'GET', data: {name : 'personal', length : 200}, dataType: 'JSON', statusCode: { 404: function() { alert( "Page not found" ); }}, success: function(jsonData) { console.log(jsonData); $.getScript('./_utilities/javascript/wordcount.js', function(data) { $.each(jsonData, function(subfield, obj) { setWordConstraint(obj.id, obj.length); }); }); } }); $("<link/>", { rel: "stylesheet", type: "text/css", href: "./_utilities/css/newsletter_filler.css" }).appendTo("head"); $.get('./newsletter_filler.html', function(data) { $('#main').html(data); }).done(function(){ var tongue = ''; $('#tongue').change(function() { if ($('#tongue').val() == 'other_tongue') { $('#other').show(); } }); $("#sevengates").submit(function(e){ return false; }); }); The jQuery object $("#sevengates") refers to the id of the <form> element. $("#sevengates").submit(function(e){ return false; }); QUESTION: How can I have my cake and eat it too? Or, how do I set the $_POST superglobal without leaving the filled <div>? Roddy Edited February 8, 2018 by iwato Link to comment Share on other sites More sharing options...
dsonesuk Posted February 8, 2018 Share Posted February 8, 2018 Any element created by JavaScript after the initial loading of page, where JavaScript code on that page refers to id, class etc of new html won't work unless it is re-initialized to relate to the new html OR you use jQuery .on() function that refers to the parent element that existed on page load and the original/new html code that was inserted into it. Link to comment Share on other sites More sharing options...
iwato Posted February 8, 2018 Author Share Posted February 8, 2018 Quote Any element created by JavaScript after the initial loading of page, where JavaScript code on that page refers to id, class etc of new html won't work unless it is re-initialized to relate to the new html OR you use jQuery .on() function that refers to the parent element that existed on page load and the original/new html code that was inserted into it. So, if I have understood you correctly, I cannot expect the following code snippet to append to <div id='main> a message that contains the value of a JSON string returned from .newsletter_filler_form.php by AJAX. Is this correct? $("#sevengates").submit(function(e){ $.ajax({ type: "POST", url: "./newsletter_filler_form.php", data: dataString, dataType: 'JSON', success: function(jsonData) { $('#main').html("<div id='message'></div>"); $('#message').html("<h2>Welcome " + jsonData.name + ", your contact form has been submitted!</h2>") .append("<p>We will be in touch soon.</p>") .hide() .fadeIn(1500, function() { $('#message').append("<img id='checkmark' src='images/check.png' />"); }); } }); return false; }); Roddy Link to comment Share on other sites More sharing options...
dsonesuk Posted February 8, 2018 Share Posted February 8, 2018 The new created div with id="message", and after that the code that adds the header text will work fine, because it is newly referring to this specific element once it is created, but take the image with id="checkmark" IF ANY js code from the actual page, that was targeting this img with this id on loading, would not work because it did not exist when the page was loaded. Unless jquery '.on() was used or the js code targeting this img was added after the img was appended, like how the header and text was added after #message element was added. 1 Link to comment Share on other sites More sharing options...
iwato Posted February 8, 2018 Author Share Posted February 8, 2018 OK, so why does the message containing the jsonData string fail. Am I not rendering the string properly? <?php If (!($_POST['name'] && $_POST['email'] && $_POST['mobile'])) { $name = $_POST['name']; echo json_encode($name); } ?> Roddy Link to comment Share on other sites More sharing options...
justsomeguy Posted February 8, 2018 Share Posted February 8, 2018 If name is just a string, and that's all you need to return, there's no reason to use JSON. You use JSON if you need to transfer a complex data structure like an array or object. Link to comment Share on other sites More sharing options...
iwato Posted February 8, 2018 Author Share Posted February 8, 2018 This is just experimentation. What I will be returning is more complex. Roddy Link to comment Share on other sites More sharing options...
dsonesuk Posted February 8, 2018 Share Posted February 8, 2018 If (!($_POST['name'] && $_POST['email'] && $_POST['mobile'])) { Why do you think that would work? to show or echo out echo json_encode($name); think about it Link to comment Share on other sites More sharing options...
dsonesuk Posted February 8, 2018 Share Posted February 8, 2018 test with $_POST['name'] = "steve Majors"; $_POST['email'] = "steve@Majors.com"; $_POST['mobile'] = "077123456789"; above it Link to comment Share on other sites More sharing options...
iwato Posted February 8, 2018 Author Share Posted February 8, 2018 (edited) Why do you think that would work? to show or echo out I tried to edit the error in the previous entry, but apparently it did not go through. I have now tried the following with both GET and POST variables and have added the contentType property to the AJAX request object and header() function to the PHP file. Although the PHP file generates the proper response, it is not received by AJAX. The JAVASCRIPT $.ajax({ type: "GET", url: "./formPageAlt.php", data: dataString, dataType: 'JSON', contentType: 'application/json', success: function(jsonData) { console.log(jsonData); // alert(jsonData); $('#contact_form').html("<div id='message'></div>"); $('#message').html("<h2>Welcome" + jsonData + "Your contact form has been submitted!</h2>") .append("<p>We will be in touch soon.</p>") .hide() .fadeIn(1500, function() { $('#message').append("<img id='checkmark' src='images/check.png' />"); }); } }); The PHP <?php /* If ($_POST['name'] && $_POST['email'] && $_POST['mobile']) { $name = $_POST['name']; header('content-type','application/json'); echo json_encode($name); // echo $name; } */ If ($_GET['name'] && $_GET['email'] && $_GET['mobile']) { $name = $_GET['name']; header('content-type','application/json'); echo json_encode($name); // echo $name; } ?> I feel like what I am doing is forbidden. Is it true? Roddy Edited February 8, 2018 by iwato Link to comment Share on other sites More sharing options...
justsomeguy Posted February 8, 2018 Share Posted February 8, 2018 This is just experimentation. What I will be returning is more complex. Be that as it may, that's why your example code fails. An arbitrary string of text is not JSON data. JSON is for complex data structures, it's right in the name (JavaScript Object Notation). If you want to use an example, at least use data that is going to work. While your code above shows a get request, you should be aware that if you send an ajax post request with the content type application/json, PHP will not populate the $_POST array. PHP uses the default content type for a form to decide whether to check for and populate post data, so if you're sending a post request do not set the content type. Although the PHP file generates the proper response, it is not received by AJAX. That's correct, because you're having PHP tell the browser that the content type is JSON data, but then you're not outputting JSON. That would cause the failure callback to fire in Javascript if you defined one, receiving an incorrect response for the data type is considered a failure. The moral of the story is that you need to test with appropriate data if you expect your tests to be useful. Link to comment Share on other sites More sharing options...
iwato Posted February 8, 2018 Author Share Posted February 8, 2018 OK. Then for the continued purpose of experimentation what would the setting be for receiving echoed text from the PHP file. I set dataType to 'TEXT' in the javascript file and echoed the variable $name in the PHP file as output. Still the AJAX response was not received. The console.log() function showed nothing and the name was missing from error message. In effect, var dataString = JSON.stringify(name,email,mobile); $.ajax({ type: "POST", url: "./formPageAlt.php", data: dataString, dataType: 'TEXT', success: function(text_data) { $('#contact_form').html("<div id='message'></div>"); $('#message').html("<h2>Congratulations, <span style='font-family: Bradley Hand, cursive';font-size:1.2em;'>" + text_data + "</span>!</h2>") .append("<p> Your contact form has been submitted securely to the Grammar Captive database using TSL/SSL protocol! It will stored on the Lunarpages webserver in Orange, California USA.</p><p>If you have any doubt about the safety of your information, please look under the headings Other/Internet Security and Other/Legal Privacy in the navigation bar on your left, or email the Grammar Captive webmaster at <a href='mailto:admin@grammarcaptive.com?subject=Grammar%20Captive%20Webmaster%20-%20Question%20About%20Internet%20Security' title='The Grammar Captive webmaster' target='_blank'>admin@grammarcaptive.com</a></p>") .hide() .fadeIn(1500, function() { // $('#message').append("<img id='checkmark' src='images/check.png' />"); $('#message').append("<img id='checkmark' src='images/check.png' />"); }); } }); and <?php /* If ($_POST['name'] && $_POST['email'] && $_POST['mobile']) { $name = $_POST['name']; header('content-type','application/json'); echo json_encode($name); // echo $name; } */ If ($_POST['name'] && $_POST['email'] && $_POST['mobile']) { $name = $_POST['name']; // header('content-type','application/text'); // echo json_encode($name); echo $name; } ?> Roddy Link to comment Share on other sites More sharing options...
dsonesuk Posted February 8, 2018 Share Posted February 8, 2018 You are looking for something like this I thinks <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0" /> <title>Document Title</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> <style type="text/css"> </style> </head> <body> <form id="sevengates"> <input type="text" name="name" value="Steve Majors"> <input type="email" name="email" value="Steve@Majors.com"> <input type="text" name="mobile" value="077123456789"> <input type="submit" name="submitthis"> </form> <script> $("#sevengates").submit(function(e) { e.preventDefault(); $.ajax({ type: "POST", url: "newsletter_filler_form.php", data: {name: $(this).find("input[name='name']").val(), email: $(this).find("input[name='email']").val(), mobile: $(this).find("input[name='mobile']").val(), dataType: 'json'}, success: function(jsonData) { alert(jsonData) } }); }); </script> </body> </html> and finally <?php $phpObj = (object) []; If (isset($_POST['name'], $_POST['email'], $_POST['mobile'])) { $phpObj->name = $_POST['name']; $phpObj->email = $_POST['email']; $phpObj->mobile = $_POST['mobile']; echo json_encode($phpObj); } If you are going to encode it you require name and value, to send multiple value, you require array with named indexes and values associated to them, or object array where you can define the object and apply data to it. 1 Link to comment Share on other sites More sharing options...
Ingolme Posted February 8, 2018 Share Posted February 8, 2018 Have you checked to see what the contents of the dataString variable look like? var dataString = JSON.stringify(name,email,mobile); I don't think it translates into the POST variables you're expecting. 1 Link to comment Share on other sites More sharing options...
justsomeguy Posted February 8, 2018 Share Posted February 8, 2018 Then for the continued purpose of experimentation what would the setting be for receiving echoed text from the PHP file. The default. Don't set the data type, don't set the content type. It will send the request to PHP using the appropriate content type, and PHP will send the response with a content-type of text/html as the default. That should be fine. You can even use those settings with JSON data. If you're trying to send a bunch of post data, don't use JSON to convert that to non-post data, just set the data object/string like you would for any other post request. Post data is not submitted using JSON, so if you try to force that then PHP isn't going to know what to do with it. Just submit it as regular form data. 1 Link to comment Share on other sites More sharing options...
iwato Posted February 9, 2018 Author Share Posted February 9, 2018 Sometimes simple is better. It worked! Hooray, hooray, hooray. An entire morning of experimentation resolved. Thank you! Roddy Link to comment Share on other sites More sharing options...
iwato Posted February 9, 2018 Author Share Posted February 9, 2018 (edited) $.ajax({ type: "POST", url: "./formPageAlt.php", data: dataString, success: function(text_data) { $('#contact_form').html("<div id='message'></div>"); $('#message').html("<h2>Congratulations, <span style='font-family: Bradley Hand, cursive';font-size:1.2em;'>" + text_data + "</span>!</h2>") .append("<p> Your contact form has been submitted securely to the Grammar Captive database using TSL/SSL protocol! It will stored on the Lunarpages webserver in Orange, California USA.</p><p>If you have any doubt about the safety of your information, please look under the headings Other/Internet Security and Other/Legal Privacy in the navigation bar on your left, or email the Grammar Captive webmaster at <a href='mailto:admin@grammarcaptive.com?subject=Grammar%20Captive%20Webmaster%20-%20Question%20About%20Internet%20Security' title='The Grammar Captive webmaster' target='_blank'>admin@grammarcaptive.com</a></p>") .hide() .fadeIn(1500, function() { $('#message').append("<img id='checkmark' src='images/check.png' />"); }); } }); var dataString = 'name='+ name + '&email=' + email + '&mobile=' + mobile; Edited February 9, 2018 by iwato Link to comment Share on other sites More sharing options...
iwato Posted February 10, 2018 Author Share Posted February 10, 2018 If you would like to experience what you have enable Just click on the word Subscribe under the heading Info/Newsletter in the navigation bar on the Grammar Captive main page, fill out the form, and submit your information. Then, watch what happens, Roddy Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now