简体   繁体   English

jQuery Ajax发布到php无法打印响应

[英]jQuery Ajax post to php not printing response

I am using the new way to post data to a php page through ajax without a page refresh but the response is not printing to the console. 我正在使用通过ajax将数据发布到php页面的新方法,而不刷新页面,但响应未打印到控制台。

Note: I am not yet collecting form data to send until I can actually get the ajax to work. 注意:在真正使Ajax工作之前,我尚未收集要发送的表单数据。

HTML: HTML:

<form id="myForm" action="process.php" method="post">
      <input type="text" placeholder="Email" id="email" name="email">
      <span class="error">Email not entered</span><br />
      <input type="password" placeholder="Password" id="pword" name="pword">
      <span class="error">Password not entered</span><br />
      <input type="text" placeholder="First Name" id="fname" name="fname">
      <span class="error">First Name not entered</span><br />
      <input type="text" placeholder="Last Name" id="lname" name="lname">
      <span class="error">Last Name not entered</span><br />
      <input type="submit" value="Submit">
</form>

jQuery: jQuery的:

$('#myForm').on('submit', function(e){e.preventDefault()});

var request = $.ajax({
    url         : 'process.php',
    method      : 'POST',
    data        : {name: 'Robert'},
    dataType    : 'html'
});

request.done(function(response){
    console.log(response);
});

request.fail(function(){
    console.log('fail');
});

PHP: PHP:

<?php
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
?>

Your on submit function is not doing anything. 您的“提交”功能没有执行任何操作。 You need to have the ajax call inside of it. 您需要在其中包含ajax调用。

Try: 尝试:

jQuery(document).ready(function ($) {

    $('#myForm').on('submit', function(e){

        e.preventDefault();

        $.ajax({
            url         : 'process.php',
            method      : 'POST',
            data        : {name: 'Robert'},
            dataType    : 'html'
        })
        .done(function(response){
            console.log(response);
        })
        .fail(function(){
            console.log('fail');
        });
    });

});

Also I do not know where you are loading the JS. 另外我也不知道你在哪里加载JS。 But you might want to wrap it in a document ready function to make sure your form exist when it is called. 但是您可能希望将其包装在文档就绪函数中,以确保您的表单在调用时存在。

Lastly there is a very nice plugin for forms that will make this easier for you. 最后,还有一个非常不错的表单插件,可以使您轻松完成此工作。 JQuery.Form. JQuery.Form。

http://malsup.com/jquery/form/ http://malsup.com/jquery/form/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM