简体   繁体   中英

PHP script called from javascript(ajax/jquery) echos as an alert dialog rather than original page

I need to be able to pass data from a java-script script to php and send new data from the php script back to java-script. However, when I send the data to php and echo it in the new php script, the echoed content is sent through an alert.

A simplified (& incorrect) version of what I'm trying to do is as follows

index.php

<!DOCTYPE html>
<html>
<head>


   <script src="jquery.js"></script>
   <script src="script.js"> </script>
</head>
<body> </body>
</html>

script.js

$.ajax({ url: 'loadContent.php',
  data: {action: 'HEYO'},
  type: 'post',
  success: function(output) {
    alert(output);
  }
});

loadContent.php

<?php
  if(isset($_POST['action']) && !empty($_POST['action'])) {
      $action = $_POST['action'];
      echo $action;
  }
 ?>

What this code currently does is display an alert with whatever text is sent through script.js to loadContent.php. What I would like it to do is echo the content to the original page.

If you just want the output of loadContent.php to be put into the page you could use something like

$.ajax({ url: 'loadContent.php',
      data: {action: 'HEYO'},
      type: 'post',
      success: function(output) {
        $('body').html(output);
      }
    });

You need to paste this content inside any div or other html element on your html page. alert() is doing the exact job for which it meant for

So code need to be:-

HTML code:-

<!DOCTYPE html>
<html>
<head>
   <script src="jquery.js"></script>
   <script src="script.js"> </script>
</head>
<body> 
  <div id="result"></div><!-- created a div to represent the output of ajax code-->
</body>
</html>

jQuery code:-

$.ajax({ url: 'loadContent.php',
  data: {action: $('html').html()},
  type: 'post',
  success: function(output) {
    $('#result').html(output); // paste the output to the div
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM