2

I have little problem with JS and AJAX, i dont know this languages. I know php and i have applied for position php developer, now i have some tasks to do and i stucked at one. It is simple task, form, submit, process information, store in DB, and send. Only problem is i have to use AJAX to submit form, i done little research and somehow i made wrote this code but it doesnt work.

<div>
        <form method="POST" action="add.php" id="form">
            <input type="email" name="email" id="email" value="Email">
            <textarea name="content" id ="content">Message</textarea>
            <input type="submit" value="Submit" id="submit"> 
        </form>
        <a href="send.php">Send messages from database</a>
    </div>
    <script>
        $(document).ready(function() {
            // When click on button store values from form fields into variables
            $("form").submit(function(event) {
                event.preventDefault();
                var email = $("#email").val();
                var content = $("#content").val();
                // Check if fields are empty 
                if (email=="" || content="") {
                    alert("Please fill all fields");
                }
                // AJAX code to submit form
                else {
                    $.ajax ({
                        type: "POST",
                        url: ("#form").attr('action');
                        data: { "email": email, "content": content},
                        cache: false,
                        success: function() {
                            alert("Data successfully forwarded to add.php");
                        }
                    });
                }
                return false;
            });
        });
    </script>
</body>

IN form can i use input type button instead of submit (so no need for preventDefault in JS) and in JS i do it $("#submit").click(function.....

I think i have tried all combinations and when form is submited it goes with default, no JS activated...

SOLVED: problem was in IF statment, content="" instead of content=="", OMG how i overlooked that...

7
  • url: ("#form").attr('action'); What is the name of this file? url (default: The current page), Type: String, A string containing the URL to which the request is sent. Commented Oct 31, 2015 at 19:31
  • 1
    Look at your javascript console you should see that you have a syntax error, url: ("#form").attr('action'); its supposed to be a , at the end Commented Oct 31, 2015 at 19:33
  • Beyond the comma issue.. where do you want the data sent? Hint: I'm thinking add.php is a pretty good place... Commented Oct 31, 2015 at 19:35
  • Yes add.php is place, but i didnt wanted it to be hardcoded so i used ("#form").attr('action') to pull URL from form, if you understand me.. Commented Oct 31, 2015 at 19:42
  • 1
    Can you remove the solution out of your question and submit it as a proper answer? (Slightly related to Meta question meta.stackoverflow.com/q/309266/2564301) Commented Nov 1, 2015 at 17:19

3 Answers 3

2

To answer your questions, yes you are right, you can use an input of type button and you don't necessary need to depend on submitting the form. Here is how you'd write it without form submission:

<div>
    <form method="POST" action="add.php" id="form">
        <input type="email" name="email" id="email" value="Email">
        <textarea name="content" id ="content">Message</textarea>
        <input type="button" value="Submit" id="submit" onclick="SendAjax();"> 
    </form>
    <a href="send.php">Send messages from database</a>
</div>
<script>
    // When click on button store values from form fields into variables
    function SendAjax() {
        var email = $("#email").val();
        var content = $("#content").val();
        // Check if fields are empty 
        if (email=="" || content=="") {
            alert("Please fill all fields");
        }
        // AJAX code to submit form
        else {
            $.ajax ({
                type: "POST",
                url: "type your URL here",
                data: { "email": email, "content": content},
                cache: false,
                success: function() {
                    alert("Data successfully forwarded to add.php");
                }
            });
        }
    }
</script>

As you can see, I prefer to specify the URL in AJAX instead of taking it from the form's action which I sometimes have it set to a different URL from the AJAX. However, if you want to take the URL from the form's action, then fix that line in your code to be:

url: $("#form").attr('action'),
Sign up to request clarification or add additional context in comments.

1 Comment

nice explanation! In the ajax submit code, there should be a comma after the "type your URL here" instead of a semi-colon
1

Use the serialize() method (described bellow) instead of manually getting the value of each field of your form in order to build the JSON object.

 $('#form').submit(function() {
        $.ajax({ 
            data: $(this).serialize(), 
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            success: function() {
                alert("Data successfully forwarded to add.php");
            }
        });
        return false; 
    });

1 Comment

The serialize() method isn't to be found.
1

You have a syntax error in your ajax call.

$.ajax ({
    type: "POST",
    url: ("#form").attr('action'); // This is bad JSON
    data: { "email": email, "content": content},
    cache: false,
    success: function() {
        alert("Data successfully forwarded to add.php");
    }
});

Replace that line with:

url: $("#form").attr('action'),

2 Comments

well i fixed all error but main problem remains, cant trigger JS on form submit, it goes default... $(document).ready(function() { $("#form").submit(function(event) { event.preventDefault();
@Constantine1001 any javascript errors in the console?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.