user1228739
user1228739

Reputation: 153

$ajax success response print HTML page

I have this code in my JS function, I need to call a PHP file "valiadte-attrib-form.php" this PHP script returns a variable. This is my HTML page:

 <form method="post" id="form1" name="form1" action="<?php echo $editFormAction; ?>">

<script>
   $(function() {   
     $('#form1').submit(function() {
        return validateForm();
     });
   });
</script>

This is my JS code:

 function validateForm() {
    var form = $("#form1");
    $.ajax({
        context: form,
        type: 'GET',
        url: 'validate-attrib-form.php',
        data: params,
        success: function(response){  
            alert(response);
            result=response;  
            return result;
        }.bind(form)
    });

This is my PHP code:

    <?php  
     echo "false";

But my problem is when a I see alert(response); I see full HTML codelike this:

<!doctype html>
<html lang="es">
<head>  
   <meta charset="iso-8859-1"/> 
   <meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1"/>
.....
.....

What's wrong in my code? I need that alert(response) shows false not HTML code. Thanks for your help!

Upvotes: 2

Views: 5374

Answers (1)

Jason
Jason

Reputation: 32490

You're getting a server error like a 400 or 500-series error ... Sometimes, depending on how the server is configured, this may look like a re-direct, at which point you may see a full HTML page without any error codes, like the main page of the site if the redirects are being done to suppress errors to end-users.

I'm also a little confused at the structure of your $.ajax call. You may want to change it to the following:

function validateForm() {
    var form = $("#form1");
    $.ajax({
        /* context: form, //not sure you need that */
        type: 'GET',
        url: 'validate-attrib-form.php',
        data: form.serializeArray(), /* turn the form data into an array */
        dataType: "text",
        success: function(response){  
            alert(response);
            /* do other stuff... */
        }
    });
}

$("#form1").on("submit", function(ev) {
    ev.preventDefault();
    validateForm();
};

You don't need to specify a form action attribute if you are attempting to make an AJAX call to an endpoint.

Upvotes: 1

Related Questions