0

I have a PHP Ajax form that I'm trying to submit a Zendesk API call. Whenever I use the ajax part, in order to keep the user on the same page, it doesn't work. When I remove the <script> part, it works fine, but obviously redirects to contact.php from contact.html so I'm thinking the problem is in the Ajax part, not in the PHP part.

Here is my HTML form:

<html>
        <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        </head>
        <body>
        <div class="box_form">

        <form id="zFormer" method="POST" action="contact.php" name="former">
        <p>
        Your Name:<input type="text" value="James Duh" name="z_name">
        </p>
        <p>
        Your Email Address: <input type="text" value="[email protected]" name="z_requester">
        </p>
        <p>
        Subject: <input type="text" value="My Subject Here" name="z_subject">
        </p>
        <p>
        Description: <textarea name="z_description">My Description Here</textarea>
        </p>
        <p>
        <input type="submit" value="submit" id="submitter" name="submit">
        </p>
        </form>
        </div>

        <div class="success-message-subscribe"></div>
        <div class="error-message-subscribe"></div>


<script>
jQuery(document).ready(function() {

$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();

    $('.box_form form').submit(function() {
        var postdata = $('.box_form form').serialize();
        $.ajax({
            type: 'POST',
            url: 'contact.php',
            data: postdata,
            dataType: 'json',
            success: function(json) {
                if(json.valid == 1) {
                    $('.box_form').hide();

                    $('.error-message-subscribe').hide();
                    $('.success-message-subscribe').hide();
                    $('.subscribe form').hide();
                    $('.success-message-subscribe').html(json.message);
                    $('.success-message-subscribe').fadeIn();
                }
            }
        });
        return false;
    });

});
</script>

        </body>
        </html>

And the PHP Part:

You can probably ignore most of this since it works when I don't use the Ajax. Only the last few lines gives the response $array['valid'] = 1; which should then be catched by if(json.valid == 1) above.

<?php
        ( REMOVED API CALL CODE FROM ABOVE HERE )

        if (isset($_POST['submit'])) { 

        foreach($_POST as $key => $value){
            if(preg_match('/^z_/i',$key)){
                $arr[strip_tags($key)] = strip_tags($value);
            }
        }
        $create = json_encode(array('ticket' => array(

        'subject' => $arr['z_subject'], 
        'comment' => array( "body"=> $arr['z_description']), 
        'requester' => array('name' => $arr['z_name'], 
        'email' => $arr['z_requester'])

        )));

        $return = curlWrap("/tickets.json", $create, "POST");


        $array = array();
        $array['valid'] = 1;
        $array['message'] = 'Thank you!';
        echo json_encode($array);


  ?>

Any ideas why this isn't working?

3
  • You might be more likely to get an answer if you strip out any irrelevant code. Commented Mar 8, 2015 at 19:05
  • 1
    Will do, you're right :) Commented Mar 8, 2015 at 19:06
  • use Firebug or developer tools to see how ajax call goes, or add an error callback in your ajax call to trace it. Commented Mar 8, 2015 at 19:33

2 Answers 2

1

I expect your use of contact.php as a relative URL isn't resolving properly. Check your JavaScript console and you should see an error that shows the post failing. Change contact.php to www.your_domain.com/contact.php and it should work fine

Sign up to request clarification or add additional context in comments.

7 Comments

Just got my hopes up and changes it to the full URL but it's not working either. This is so weird, I can't find out what's wrong! When I remove the script part, it works perfectly.
And what does the console say? If you use Firefox install firebug add on and it will report the error
In headers, it shows contact.php with "200OK 430ms". In Post it shows the parameters as I input them in the form. And Response and HTML is empty.
Hmm that is strange. Is contact.php at the same domain?
Yep. Same domain. Even the same folder.
|
1

Replace jQuery(document).ready(function() { by

$(document).ready(function() {

Secondly from Jquery documentation:

Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

Therefore submit button won't serialize through jQuery.serialize() function.

A solution below:

<script>
$(document).ready(function() {

$('.success-message-subscribe').hide();
$('.error-message-subscribe').hide();

    $('#submitter').click(function(e) {
        e.preventDefault();
        $myform = $(this).parent('form');
        $btnid = $(this).attr('name');
        $btnval = $(this).attr('value');
        var postdata = $myform.serialize();
        $.ajax({
            type: 'POST',
            url: 'contact.php',
            data: { "btnid" : $btnid, "btnval": $btnval, "form-data": $form.serialize() },
            dataType: 'json',
            success: function(json) {
                if(json.valid == 1) {
                    $('.box_form').hide();

                    $('.error-message-subscribe').hide();
                    $('.success-message-subscribe').hide();
                    $('.subscribe form').hide();
                    $('.success-message-subscribe').html(json.message);
                    $('.success-message-subscribe').fadeIn();
                }
            }
        });
        return false;
    });

});
</script>

3 Comments

Did that but still nothing happens :(
You should change your PHP code to if (isset($_POST['btnid'])) { Or simply use your old code and remove the if (isset($_POST['submit'])) {
Yep. I did that and now it's working. Thanks so much! :)

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.