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.

  1. the javascript sends http request
  2. the form submits
  3. the page goes away
  4. a new page loads
  5. 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

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -