javascript - GET result placed into <div> using AJAX and jQuery -
simple using ajax , jquery. trying place resulting html div below form. div not populating, doing wrong?
<head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready( function myfunction() { var name = document.forms["form"]["name"].value; $.get( "fetch-photographer.php?name="+name,( function( data ) { $( "#responsearea" ).html( data ); }) ); } ); </script> </head> <body> <form name="form" method="post" onsubmit="myfunction()"> <input type="text" name="name" value="enter search"> <input type="submit" value="submit"> </form> <div id="responsearea"></div> </body>
you have 2 main problems:
you have defined myfunction
in scope of function. isn't global, can't access onsubmit
function.
make myfunction
global:
$(document).ready( // remove line function myfunction() { // ... } ); // remove line
you running js when submit form.
- the javascript sends http request
- the form submits
- the page goes away
- a new page loads
- there no js handle http response
add return false
end of onsubmit
function.
<form name="form" method="post" onsubmit="myfunction(); return false;">
better yet, use modern way bind event handlers:
<form id="form" method="post"> $("#form").on("submit", myfunction); function myfunction(event) { event.preventdefault(); // rest of function }
note failing escape special characters user might type in. don't create query strings hand if using jquery, take advantage of built-in functions that: pass data object via second argument $.get
.
$.get( "fetch-photographer.php", { name: document.forms["form"]["name"].value }, function (data) { $("#responsearea").html(data); } );
Comments
Post a Comment