2

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.

3
  • 2
    alert(output); It's doing what you're telling it to do. Commented Jul 24, 2017 at 17:09
  • 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 Commented Jul 24, 2017 at 17:12
  • do you want to put the response of loadContent.php in the originating page or alert it? Commented Jul 24, 2017 at 17:18

2 Answers 2

2

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
  }
});
Sign up to request clarification or add additional context in comments.

Comments

2

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);
      }
    });

2 Comments

Uuuh... still alerting.
@waterloomatt It must be ambigous, i thought he wanted the php to echo the content of the original page not put it on the page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.