隐藏ajax函数中的jquery元素 [英] hide jquery elements in an ajax function

查看:77
本文介绍了隐藏ajax函数中的jquery元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery和$ .ajax()方法提交表单。将信息提交给服务器时,我只希望保留结果并隐藏页面的其余部分。我可以在ajax方法中添加一个条件,指出如果(成功)然后在隐藏h1,h2和p元素时显示结果(只留下返回的文本;否则如果(错误)则只显示错误消息在页面底部的div占位符中没有.hide() - 任何元素,所以在ajax方法成功之后,我希望所有元素都隐藏,除了div占位符中返回的文本之外,如果发生错误表格留空),然后在div占位符中显示错误信息,同时保留所有元素。

更新:



当我在我的例子中使用警报时,他们总是以成功的形式出现,ajax / jquery不能识别我的if语句,有什么想法可能会发生在这里吗?

HTML:

 < form id =formaction =form.php> 
< label for =name>名称:< / label>
< input type =textid =namename =name>

<标签for =phone>电话:< / label>
< input type =textid =phonename =phone>
< / form>

< input type =submitid =clickMevalue =Sendclass =clear>

< p id =display> < / p为H.

jQuery / Ajax

点击(功能(事件)){
event.preventDefault();
($); $(文档).ready(函数(){
$(#clickMe var myData = $('#form')。serialize();

$ .ajax({
url:'form.php',
data:myData,
成功:function(result){
$('#display')。html(result);

if(myData.indexOf(Thank)){
alert(success)
}
},
错误:function(xhr,status,error){
$('#display')。html(Error: + xhr.status ++ xhr.statusText);

if(myData.indexOf(Something went wrong)){

alert(error);
}
}
});
});
});

PHP

  if(!empty($ _ GET ['name'])

echoThank you for your messsage;


else {
echo出错了;
}


解决方案

既然你没有显示任何验证的PHP代码,我不知道你的代码是怎么样的,但你必须做这样的事情:



放在 form.php 文件的顶部:

  if( isset($ _ POST ['name'])){

//根据验证返回true / false

//默认设置成功消息
$ success = true;
$ message ='我的成功消息';

//现在执行您的条件检查并基于该更改为false

//例如:当名称验证失败时:
if($ _ POST ['name'] ==''){
$ success = false;
$ message ='M y错误消息:(名称是必填字段)';
}

//将数组转换为json,所以我们可以在ajax上很好地读出它返回
echo json_encode($ result);

//停止我们代码的其余部分
exit;
}

然后将您的ajax成功更改为:

请注意:


从jQuery 3.0开始, $。parseJSON 已弃用。要解析JSON字符串,请使用本地 JSON.parse 方法。




  success:function(result){
//将json字符串读入适当的对象,对于jQuery 3.0+使用本地方法而不是
var $ data = jQuery.parseJSON );

//检查是否存在验证问题
if($ data.success == true){
//将成功消息写入DOM元素
$( '#display')HTML($ data.message)。
} else {
//将错误信息写入DOM元素
$('#display')。html($ data.message);
}
},


I am trying to submit a form using jquery and the $.ajax () method. When submitting the information to the server I want only the result to remain and the rest of the page to be hidden. Am I able to add a conditional in the ajax method that states " if(success) then display the result while hiding the h1, h2, and p elements (leaving only the returned text; else if (error) then just display the error message inside my div place holder at the bottom of the page without .hide()-ing any element. So upon success of the ajax method, I want all elements to hide except for the text returned in the div placeholder. If an error occurs (the form is left blank) then display the error message in the div place holder while leaving all elements in place.

UPDATE:

When I use the alerts in my example, they always come out as success. The ajax/jquery is not recognizing my if statements. Any idea what may be going on here?

HTML:

 <form id="form" action="form.php">
     <label for="name">Name: </label>
     <input type="text" id="name" name="name">

     <label for="phone">Phone: </label>
     <input type="text" id="phone" name="phone">
</form>

<input type="submit" id="clickMe" value="Send" class="clear">

<p id="display"> </p>

jQuery/Ajax

$(document).ready(function() {
    $("#clickMe").click(function(event){
        event.preventDefault();
        var myData = $('#form').serialize();    

        $.ajax({
            url: 'form.php',  
            data: myData,    
            success: function (result) {
                $('#display').html(result);

             if(myData.indexOf("Thank")){
                        alert("success")
                    } 
            },
            error: function (xhr, status, error) {
                $('#display').html("Error: " + xhr.status + " " + xhr.statusText);

             if(myData.indexOf("Something went wrong")){

                        alert("error");
                    }
            }
        });
    }); 
});

PHP

 if(!empty($_GET['name'])

  echo "Thank you for your messsage ";


else {
    echo "Something went wrong.;
}

解决方案

Since you have not shown any PHP code that does validation I do not know how your code looks but you will have to do something like this:

The following should be put at top of your form.php file:

if(isset($_POST['name'])){

    // return either true/false depending on validation

    // By default set the success message
    $success = true;
    $message = 'My success message';

    // now do your conditional checks and based on that change to false

    // Example: when validation fails on name:
    if($_POST['name']==''){
        $success = false;
        $message = 'My error message: (Name is a required field)';
    }   

    // convert array to json, so we can read it out nicely on ajax return
    echo json_encode($result);

    // stop rest of our code
    exit;
}

Then change your ajax success to:

Plese note:

As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.

success: function (result) {
   // Read the json string to proper object, for jQuery 3.0+ use native method instead
   var $data = jQuery.parseJSON(result);

   // Check if there where no validation problems
   if($data.success==true){
       // Write success message to DOM element
       $('#display').html($data.message);
   }else{
       // Write error message to DOM element
       $('#display').html($data.message);
   }
},

这篇关于隐藏ajax函数中的jquery元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆