AM-
AM-

Reputation: 881

How to fix AJAX $.post issue?

I have the strangest AJAX bug (or severe case of inexperience) ever. After a $_POST request, only the contents of div#content should be updated and nothing else, however, my entire page layout seems to break.

My layout is simple:

<header>..</header><nav>..</nav>

div#left-sidebar - div#content - div#right-sidebar

<footer>..</footer>

The Javascript used is the following:

$("#terms").submit(function(event) {
    if ($("#content #inp_iRead").is(":checked")) {
        event.preventDefault();
        $("#content img[alt=loading]").show();
        $("#content #terms").hide();
        $.post("reg", {
            ajax_reg: true,
            iRead: 1
        },
        function(data) {
            $("#content").html(data).find("#content");
        }, 
    "html");
        }
    });

#terms being the form ID and #inp_iRead being a checkbox. What I want is to update my div#content with the div#content returned (in this case it contains only the string foo :)).

Below are my expectations (as it appears with JavaScript turned off): Expectations

And received result: Results

My experience with AJAX is very limited, however, following all the tutorials and what I know so far this code should work.

My attempt to fix this was using filter() instead of find(), which returned the same results. In my opinion, a possible workaround could be getting the script to return a JSON object and updating div#content with it, however, I am more interested in fixing the code that should work instead of changing the method used.

Any suggestions are highly appreciated.

EDIT: the reason for if ($("#content #inp_iRead").is(":checked")) is that otherwise my other live form validation script does not work.

Upvotes: 1

Views: 68

Answers (1)

Blender
Blender

Reputation: 298046

I'd use the load() method instead. It's a lot simpler:

$('#content').load('reg #content > *', {
    ajax_reg: true,
    iRead: 1
});

reg #content > * tells .load() to load reg and replace your element's contents with #content > *.

When you pass data to the load function, it turns the GET into a POST.

Upvotes: 2

Related Questions