Submitting Form using jquery AJAX

后端 未结 2 1265
感情败类
感情败类 2021-01-27 14:37

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 i

相关标签:
2条回答
  • 2021-01-27 15:11

    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.

    0 讨论(0)
  • 2021-01-27 15:29

    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",
      .....
     })
    
    0 讨论(0)
提交回复
热议问题