Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Aug 2012
    Posts
    37
    Thanks
    5
    Thanked 0 Times in 0 Posts

    parse html from jquery ajax return

    Hello coders,

    I have an jquery form validator, client-side but also an php serverside validator.

    After the form is validated client-side, it would send an ajax to my submit.php page.

    If the form isn't validated server-side it would return a div with class 'error'.

    Here's the code:
    Ajax:
    Code:
    var datastring = 'username='+ username + '&password=' + password 
    + '&repeatpassword=' + repeatpassword + '&email=' + email + '&formtype=' + formtype;
    
    $.ajax({
    	type: "POST",
    	url: "submit.php",
    	data: datastring,
    	success: function(data) { 
    		if($(data).find(".error").length > 0){
    			alert("Error! The following errror occurs:");
    			$(data).find(".error").each(function(){
    				$('.error_form').text($(this).text());
    			});
    		}else{
    			$("form.formulier").hide();
    			alert("succesvol signup");
    			//game.start(5,5);
    		}
    		alert(data);
    	}
    });
    PHP return
    Code:
    <div class='error'>Username does not match our conditions</div>
    I want to put the text of class error, in an div with class called 'error_form'

    Response:
    alertbox with text: "succesvol signup"
    alertbox with text: "<div class='error'>Username does not match our conditions</div>"
    and div 'error_form' contained nothing

    help!

  • #2
    Senior Coder
    Join Date
    Apr 2011
    Location
    London, England
    Posts
    2,120
    Thanks
    15
    Thanked 354 Times in 353 Posts
    The response is returned as a string, rather than an HTML element. Try

    Code:
    var returnAsHTML = $(data);
    // then..
    if (returnAsHTML).find(...) // etc..
    // do you need to use find..?
    if ($(".error", returnAsHTML).length) {
    Do you need to use each()? I suspect you just need to use first() to retrieve the first (and only) error message.

    But if you return just a string rather than '<div>...etc.' then you can just use the string as is rather than extracting it.

    I would consider returning either 'true' or 'Some error message' and check against the text 'true'.
    "I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
    Validate your HTML and CSS


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •