Mahdi_Nine
Mahdi_Nine

Reputation: 14751

ajax with jquery not working

I want when i click on button the text input data post or get to same page that input is in it. i have this code:

$(document).ready(function () {
         $("#btn_ok").click(function(){
              $.ajax({
                          type: "GET",
                          url: "test.php",
                          data: { name :$("#name").val() ,                }
                        }).done(function( msg ) {
                            alert("Ok");

                });


         });


     });
<?php
    if(isset($_GET["name"]))
    {
        echo "OK";

    }
    else
        echo "NO";

?>
<input type="text" id="name" />
<input type="button" id="btn_ok" />

Ok alert is shown but on the page echo NO instead of OK.

Upvotes: -1

Views: 68

Answers (2)

Parixit
Parixit

Reputation: 3855

You are doing AJAX call to same page, which means you get the content of the same page as a response and it will be in your msg string or when you use success function then also you get it.

And in that response you will get OK displayed.

AJAX is actually give you response what that page suppose to send content to browser. So if you are planning to display OK in page then you have to load this page with a query string parameter.

To display OK on page you should type following in your browser's addressbar. http://YOUR_PAGE_URL?name=anything

Please click here to see more details about AJAX.

Upvotes: 1

MD SHAHIDUL ISLAM
MD SHAHIDUL ISLAM

Reputation: 14523

1.You should not call same page because ajax call will not execute (refresh) same page you have to call another page in which you have the php code

page1.php

$(document).ready(function () {
     $("#btn_ok").click(function(){
          $.ajax({
              type: "GET",
              url: "page2.php",
              data: { name :$("#name").val() ,                }
          }).done(function( msg ) {
                //alert("Ok")
                alert(msg); //You have need a change here to see 
                            //response from page2.php
          });


     });
 });

     <input type="text" id="name" />
     <input type="button" id="btn_ok" />

page2.php

<?php
    if(isset($_GET["name"]))
    {
        echo "OK";
    }
    else
        echo "NO";
?>

2.You did not show your msg in ajax done function

Use:

 alert(msg);

Instead of

  alert("Ok");

Upvotes: 2

Related Questions