hide jquery elements in an ajax function
Asked Answered
F

2

1

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.;
}
Flyblow answered 6/3, 2018 at 3:37 Comment(14)
What CSS/styles? I don't see any in your code.Taraxacum
where is your css?Bothwell
@Rens; sorry, Essentially I want to only show part of the html (form info) once the information goes through to the server and is returned. So if error then I get an error message at the bottom of the page, if success, I want everything to hide but the(result) to display. I tried using $('h1 , h2, #p1, input').hide();" but that hides everything even if it's the error. I only want it hide when it is sucess in ajax. Not sure If I can use conditionals with ajax options??Flyblow
Can you maybe change the way you ask this question it's kind of strange question: "I want only the result to remain but the only parts of the form to remain"Taraxacum
Sorry about that. I want to use the hide method to hide everything but the results returned from the form. If there is an error then nothing should “hide”.Flyblow
Ok, but you are not validating any of the fields, so how you would know if there was an error or not? It's missing the form.php script to see how you return validation/error in resultTaraxacum
@Rens, I re-typed my question. Does it help?Flyblow
Ok, see my answer below, hope it helps, it's untested and hope it fits your current code. Note that it might be nicer to make a seperate ajax.php file to doe your validations, or maybe validate-form.php file. Just to keep things organized a little bit (always good to do). Don't forget to update in that case your url: 'form.php', to url: 'validate-form.php',Taraxacum
@Rens, sorry to keep bothering you but I updated my code and included the PHP I am trying to "recognize" text from. For some reason my indexOf is not picking up the strings from the php to return either the success or error message.Flyblow
You must replace myData.indexOf with result.indexOf because myData will only contain the form data submitted by the user, not the result that ajax call gives you back, in your example the result parameter is parsed and you can use that to call indexOf on :)Taraxacum
@Rens, I just tried changing to result.indexOf and I get the same result. I get "success" even though it should say "error". I left the "name" field blank on my form and my alert still said sucess? It seems as if the indexOf is not recognizing the text("String") from the php file. The alert is just running out of pure functionality. Any idea?Flyblow
Please debug what the output of result is by doing a simple console.log(result) then analyse it in browser console. And then see what's happening. That's what I would do in such situationsTaraxacum
@Rens: It is successfully retrieving the error message from the php file but not the success message from the php file. This confuses me because the alert displays "success" even when the form is left blank which should technically display "error" when result.indexOf is returned.Flyblow
Ok, i think you misunderstand the callback methods of the ajax function. The part success: function (result) {....} is is always executed upon a successful 200 OK request send back by the server (which is your ajax call). The error: function... part is only fired when the server did not send back a succesfull response e.g: error 50x. There is another callback called complete which is always fired no matter what :) Hope you understand :) Reference here (which you should definitely read for better understanding): api.jquery.com/jquery.ajaxTaraxacum
M
0

Try this

   $('#display').text(result);

I Hope it Helps

I think it's better to addclass. example in your css

.test{ background-color:#000000;}

on success

  $('#display').addClass("test");

or you can add directly

$('#display').css('background-color','block');

I thought your problem is in your css.

you forgot to add in your ajax.

 type: "post"
Melantha answered 6/3, 2018 at 3:42 Comment(5)
is there a way to incorporate it into the success option of the ajax? If it us successful then it hides everything but the results and the original css to go with it?Flyblow
This basically strips all HTML, has not much to do with CSS?Taraxacum
what do you mean? it will hides everything and the result will remain?Melantha
I want to use the hide method to hide everything but the result upon successFlyblow
I revised my question, maybe this helps?Flyblow
T
0

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);
   }
},
Taraxacum answered 7/3, 2018 at 15:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.