2

I am trying to submit my form using jQuery ajax, but my data isn't posting to PHP it returns empty array nothing in $_POST array.

This is my code - here is my form:

<form action = "/webdevelopmentpakistan/send_mail.php" method = "post" class = "myForm"   >
                <div class="row">
                    <div class="col-md-3 col-sm-12">
                        <div class="form-group">
                            <input class="form-control" id="fname" type="text" required name= "full_name" placeholder="Full Name" 
                             />
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-12">
                        <div class="form-group"> 
                            <input class="form-control" type="tel" required name = "phone" placeholder="+92" id="phone" onkeypress="return isNumberKey(event)" />
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-12">
                        <div class="form-group">
                            <input class="form-control" type="email" required name = "email" id="email" placeholder="Email"/>
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-12">
                        <div class="form-group">
                            <input class="btn popup" type="submit"    name = "submit" value="CONTACT OUR CONSULTANT"/>
                        </div>
                    </div>
                </div>
</form>

its an ajax part:

  $('form').on('submit', function (e) {
    e.preventDefault();

    var url = $(this).attr("action");
    var form_data = $(this).serialize();


    $.ajax({
            type: 'POST',
            url: url,
            data: $('.myForm').serialize() ,
            dataType : 'JSON',
            //contentType: "application/x-www-form-urlencoded",
            success: function (data) { // here I'm adding data as a parameter which stores the response

                    console.log(data); // instead of alert I'm changing this to console.log which logs all the response in console.
            },
             error:function(xhr, textStatus, thrownError, data)
             {
                 console.log("Error: " + thrownError);
                 console.log("Error: " + textStatus);


             }
                   });



    // var popup = document.getElementById("myPopup");
    // popup.classList.toggle("show");
    console.log(form_data);

});

PHP CODE using at other page:

if(isset($_POST)) {
        echo json_encode($_POST);
    }

and this is my serialize array which I am getting on submission of form but it isn't getting passed to php

full_name=talha&phone=012345678&email=admin%40gmail.com
Talha Arif
  • 25
  • 1
  • 1
  • 5

2 Answers2

3

welcome to stackoverflow, here are the changes, hope it will works

$.ajax({
    type: 'POST',
    url: url,
    data: $('.myForm').serialize() ,
    dataType : 'json', // changing data type to json
    success: function (data) { // here I'm adding data as a parameter which stores the response
        console.log(data); // instead of alert I'm changing this to console.log which logs all the response in console.
    }
});

in php

if(isset($_POST)) {
    echo json_encode($_POST);
}

this should print array of post parameters in your console, however you will get an array in php.

Prateik Darji
  • 2,297
  • 1
  • 13
  • 29
  • actually i am posting data to the same page in which the form is and after posting data i am showing a popup modal in which i am using recaptcha nd also i am storing posted data in variables so i can post them again after verifying recaptcha – Talha Arif Jan 31 '20 at 05:21
  • success: function (data) { console.log(data); } success function is not working json gves error reponse .. – Talha Arif Jan 31 '20 at 05:40
  • and what is the error in console can you please check? – Prateik Darji Jan 31 '20 at 05:41
  • Error: SyntaxError: Unexpected token a in JSON at position 2 this is the error i am getting – Talha Arif Jan 31 '20 at 05:44
  • okay as per your description, the php code for ajax call is also on the same page right? – Prateik Darji Jan 31 '20 at 05:46
  • okay can you please move your php code to separate page, where only the response should be return because when you r calling the api also html content might be returned so it gives you error, just change the php page and form action too. – Prateik Darji Jan 31 '20 at 05:55
  • ok now it isn't giving me error but the array still empty no data getting post {full_name: "", phone: "", email: ""} full_name: "" phone: "" email: "" __proto__: Object – Talha Arif Jan 31 '20 at 06:06
  • serialized array is generating but not getting post further here is my serialized array full_name=talha&phone=03204789963&email=admin%40gmail.com do i have to covert it to some other format ?? – Talha Arif Jan 31 '20 at 06:16
  • no its just fine, you can try after removing `dataType`, and, I am really having trouble to debug your code can you please update your latest code to your question so it will be more clear – Prateik Darji Jan 31 '20 at 06:17
  • 1
    i have solved it .. thanks alot for your time and help i just change serialized array into JSON object using JSON.stringify($(this).serialize()) and this done the job , thanks again for helping through this . – Talha Arif Jan 31 '20 at 06:27
  • 1 last thing how can i used this JSON object to store data in variable ? – Talha Arif Jan 31 '20 at 06:36
  • you will get the object array on php so it will working same as before like $_POST['first_name']. – Prateik Darji Jan 31 '20 at 06:38
0

The form action needs to be either absolute url i.e. https://somewebsite.com or a relative url on you site so ideally it should be /some-url.php. Read about form action here

So your form opening tag should be,

<form action = "/web-development-in-pakistan.php" method = "post" class = "myForm"  target="_self">

So in your javascript code when you do

var url = $(this).attr("action");

I also believe that in your ajax call, the type needs to be method, so,

$.ajax({
  method: "POST",
  .....
 })
alithedeveloper
  • 687
  • 5
  • 17