0

I believe there are numerous posts for this question and I have followed all before posting this question here and I am getting

405 (Method Not Allowed) Error

I am wondering what I am actually missing. But really, how to Insert Form Data into PHP file using AngularJs or jQuery AJAX

My scenario is : I have website in GitHub and I the same project within Github I have a .PHP file into which I am inserting Form Submit Data.

angular.module('homeModule').controller('contactController', function ($scope, $routeParams, $location, $http, contactService) {

    $scope.submitForm = function (contact) {
        if ($scope.ContactForm.$valid) {

            contactService.postNewContactHttp(contact)
                .then(function (data) {
                alert("Success");
            }).finally(function (response) {
                alert("finally");
            });
        }
    };
});



angular.module('homeModule').factory('contactService', ["$http", "$q", "$resource", function ($http, $q, $resource) {

    var postNewContactHttp = function (data) {
										
        var deferred = $q.defer();
        $http({
            //url: "./scripts/MyScripts/data.php",
			url: "https://**.github.io/***/data.php",  // Actual PHP Path
            method: 'POST',
            data: JSON.stringify(data),
            headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            }
        })
            .success(function (result) {
                deferred.resolve(result);
            })
            .error(function (result, status) {
                deferred.reject(status);
            });
        return deferred.promise;
    };


    return {
        postNewContactHttp : postNewContactHttp
    };
}]);
 <form name="ContactForm" id="ContactForm" method="post" role="form" novalidate ng-submit="submitForm(contact)"> 
.........
</form>

 <?php



<!--Below code is in separate PHP File-->
	$postdata = file_get_contents("php://input");
	$htmlContent = json_decode($postdata);

?>

I have also tried by adding following headers in PHP file but it does not worked as well.

header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");

And I always get :- 405 (Method Not Allowed) Error.

Any suggestions will be helpful.

Thanks

1
  • I would also like to tell you all that I tried using only 2 lines in PHP as:- $postdata = file_get_contents("php://input"); $htmlContent = json_decode($postdata); Even these 2 lines did not worked as well Commented Oct 8, 2016 at 6:10

3 Answers 3

0

seems you are trying to same header multiple times so once you have sent allow methods and allow headers, just skip them sending in options method check. also try to give empty string as output instead of exit

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { 
         die("");
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for response, I tried simply using 2 lines in PHP file as :- $postdata = file_get_contents("php://input"); $htmlContent = json_decode($postdata); Event these 2 did not worked as well
can you post your console output so i can get more information.
Hi Sam,I have updated my question with full relevant code. please review it and let me know... Now I am trying with almost bank PHP file , however I had also tried by adding following headers in PHP but it does not worked as well. header("Access-Control-Allow-Methods: POST, GET, OPTIONS"); header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: Content-Type");
0

Try to add it in your .htaccess file,

RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

Added a rewrite to respond with a 200 SUCCESS on every OPTIONS request.

Good luck

1 Comment

Thanks for the help, but I am running my code in Github and it does not have any .htaccess file. Can you let me know where I can use this code otherwise.
-2

It seems you are sending a request via a Secure Network (HTTPS). If you are sending the request to (and from) the same Server, it would be better to use a relative URL and most importantly explicitly use JSONP. The Code below would use JQuery and JSONP to demonstrate an alternative.

PHP:

<?php
    header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: Content-Type");
    header('Access-Control-Max-Age: 86400');


    $postData       = isset($_REQUEST)  ? $_REQUEST                 : null; 
    $jsonEncoded    = ($postData)       ? json_encode($postData)    : null;
    $response       = array();
    $callback       = null;

    if ($jsonEncoded) {
        $htmlContent    = json_decode($jsonEncoded);
        $fName          = htmlspecialchars(trim($htmlContent->fName));
        $lName          = htmlspecialchars(trim($htmlContent->lName));
        $email          = htmlspecialchars(trim($htmlContent->email));
        $phone          = htmlspecialchars(trim($htmlContent->phone));
        $callback       = htmlspecialchars(trim($htmlContent->callback));

        if ($fName != "") {
            $response['message']    = "Server returns: " . $fName;
        }else {
            $response['message']    = "Empty username parameter!";
        }
    }else {
        $response['message']        = "Not called properly with username parameter!";
    }

    if($callback) {
        die($callback . "(" . json_encode($response) . ")");
    }else{
        die(json_encode($response));
    }

JAVASCRIPT: JQUERY

 <script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>
 <script type="text/javascript">
    (function($){
        $(document).ready(function(evt){
            $("#jpForm").on("submit", function(evt){
                evt.preventDefault();
                var formElem    = $(this);

                $.ajax({
                    url         : "https://**.github.io/***/data.php",
                    dataType    : "jsonp",
                    crossDomain : true,
                    type        : "POST",
                    data        : formElem.serialize(),
                    success: function (data, textStatus, jqXHR){
                        if(data){
                            console.log(data.message);
                        }
                    },

                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log('The following error occurred: ' + textStatus, errorThrown);
                    },

                    complete: function (jqXHR, textStatus) {
                    }
                });
            });
        });
    })(jQuery);
</script>

Comments

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.