Janaka Dombawela
Janaka Dombawela

Reputation: 1357

jquery is resetting my div content

I'm trying to change the content of div using jquery. but the content flashes and resets the div. i cannot use return false; because there is another button for post text field value. i want to keep the changes of div. here is my code:

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="jquery.js"></script>

</head>
<body>

    <div>
        <form id="form" method="POST">
            <input type="text" name="gname" id="gname"/></br>
            <button id="btn">Set</button>
            <button id="nbtn">View</button>
        </form>
    </div>
    <div id="outp">

    </div>
</body>
<script>
    $("#btn").click(function(event) {
        $.post("send.php", {
            named: $("#gname").val()}, function(data) {
            alert(data);
        });
    });

</script>

<script>
    $("#nbtn").click(function(e) {

        $("#outp").html("<?php include './view.php'; ?>");

    });
</script>

Upvotes: 0

Views: 77

Answers (3)

GuybrushThreepwood
GuybrushThreepwood

Reputation: 153

You can try with ajax and catch success and error:

$("#btn").click(function() {
    var named: $("#gname").val();
    $.ajax({
        url: 'send.php',
        type: 'POST',
        data: {param1: 'value1'},
    })
    .done(function(data) {
        console.log("Post success"+data);
    })
    .fail(function() {
        console.log("Post error"+data);
    });     
});

Upvotes: -1

Eternal1
Eternal1

Reputation: 5625

Any buttons inside a form are considered submit buttons.

So you need to add event.preventDefault() to your .click code.

Also, why are your scripts outside body section?

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075855

It's not jQuery; it's that your form is being posted. So your change is made, but then the form is posted and the page is refreshed from the server.

The default type of button elements is "submit". To make one or both of those buttons just a button, use type="button".

Alternately, if you want to allow the form to be used when JavaScript is disabled (e.g., allow it to be posted normally), leave the buttons as submit buttons but prevent form submission using JavaScript. E.g.:

$("#form").submit(false); // Prevents the form being submitted in the normal way.

Upvotes: 2

Related Questions