Selecting an element from the jquery POST data

347
November 21, 2016, at 7:15 PM

I have been trying to fetch the result of a php page after sending a post request to the page itself. I want to fetch the data after the post request succeeded and get the content of the div element with id result. Here is the code:

<!DOCTYPE html>
<html>
<head>
    <title>My Form</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("#myForm").submit(function() {
        $.post("test.php",
        {
            name: "valid"
        },
        function(data, status) {
        });
        return false;
    });
});
</script>
</head>
<body>
<form method="POST" id="myForm">
    <input type="text" name="name" />
    <input type="submit" name="submit" value="Submit" />
</form>
<div id="result">
<?php
    if(isset($_POST['name'])) {
        if($_POST['name'] == 'valid') {
            echo 'You are a valid user!';
        }
    }
?>
</div>
</body>
</html>

When I submit the button regardless of what is written in the textbox I should get the Your a valid user message from the test.php I want to get this message in the result page and display it in the current page without reloading the page. Since the result page content is saved in data variable I don't know how to select an element which is contained in a variable instead of the current page itself. We can do $("div#result").text() for the current page. But how should I do it for the html content stored in a variable?

Answer 1

Just give your data variable as second parameter to jQuery like this:

$('#result', data).text()

Not tested but should work.

Update:

I don't know why but this will only work when your element you want to find is wrapped with another element within your body tag. See this fiddle: http://jsfiddle.net/xf32L5uj/

READ ALSO
Need to clearInterval in iframe from parent and it&#39;s not working

Need to clearInterval in iframe from parent and it's not working

I'm using setInterval inside an iframe, and I need to be able to stop it from the parent window, and it doesn't seem to be working. I'm assigning a global variable ('modelViewRefresh') to the setInterval event to be accessed from the parent.

273
DataTables.net custom font-size after sorting

DataTables.net custom font-size after sorting

I'm using DataTables. net to insert a Table in my website.

528
how to open sub menu in click on menu Item instead of hover

how to open sub menu in click on menu Item instead of hover

I want to open this sub menu in button click not on hover.

264
SignalR - multiple hubs - start connections individually

SignalR - multiple hubs - start connections individually

I have a SignalR application which has multiple hubs (the hubs are part of different projects inside the same solution). .

650