Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
iwato

Replacing the Default Action of a Submit-Type Form Control

Recommended Posts

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 by iwato

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

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.

  • Like 1

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

This is just experimentation.  What I will be returning is more complex.

Roddy

Share this post


Link to post
Share on other sites
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

 

Share this post


Link to post
Share on other sites

test with

$_POST['name'] = "steve Majors";
$_POST['email'] = "steve@Majors.com";
$_POST['mobile'] = "077123456789";

above it

Share this post


Link to post
Share on other sites
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 by iwato

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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.

  • Like 1

Share this post


Link to post
Share on other sites

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.

  • Like 1

Share this post


Link to post
Share on other sites

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.

  • Thanks 1

Share this post


Link to post
Share on other sites

Sometimes simple is better.

It worked!

Hooray, hooray, hooray.

An entire morning of experimentation resolved.

Thank you!

Roddy

Share this post


Link to post
Share on other sites
$.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 by iwato

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now

×