javascript - Retrieving php variables from ajax call but not working

960

when I use this code nothing and call the ajax nothing happens and I was looking at some online forums saying I need to use json encode to pass variables over ajax but it just echos it at the top of the webpage.

AjaxTesting

    <html>
    <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
    $("#test").click(function(){
        $.ajax({
            event.preventDefault(),
            url:'ajaxUser.php',
            type:'POST',
            dataType: 'json',
            success:function(data){
                alert(data.id);
            }
        )};
    });
    </script>
    </head>
  <body>
    <form method="post">
      <input name="userName">
      <input name="submit" type="button" value="Submit" id="test">
    </form>
  </body>
</html>

ajaxUser

    <?php
    echo json_encode(array('id' => 123, 'messageid' => "test"));
    ?>
266

Answer

Solution:

You don't haveevent parameter called in click function. Don't callpreventDefault() within ajax function ,also you need to code your js withindocument.ready() if you want to write in header element !!

   <html>
    <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>       
    </head>
  <body>
    <form method="post">
      <input name="userName">
      <input name="submit" type="button" value="Submit" id="test">
    </form>
    <script>
    $("#test").click(function(event){
        event.preventDefault();
        $.ajax({
            url:'ajaxUser.php',
            type:'POST',
            dataType: 'json',
            success:function(data){
                alert(data.id);
            }
        });
    });
    </script>
  </body>
</html>

Should work

147

Answer

Solution:

The php code needs to be in a different file namedAjaxTesting.php and you never call the functionpost() in the javascript. So we can call it inside a form submit event handler

Try adding:

$(function(){
   $('form').submit(function(event){
       event.preventDefault()
       post();
   })
});

Also note that the html page needs to be running on the same server and not from local file for ajax to work

People are also looking for solutions to the problem: php - Get level-specific element counts from a multidimensional array

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.