Pass javascript variables in PHP use AJAX

I have 1 javascriptvariable, and I want to transfer me to my file php. I'm looking for this, and I find what to use ajax, but I really don't know how to use it! here is my code. where am i doing wrong? my.js file:

var message1 = message.message;

        var jq = document.createElement('script');
        jq.src = "https://code.jquery.com/jquery-1.10.2.js";
        document.querySelector('head').appendChild(jq);

            $(document).ready(function() {
               $.ajax({
                        type: "POST",
                        url: 'http://localhost/a.php',
                        data: { newMessages : message1 },
                        success: function(data)
                        {
                            alert("success!");
                        }
                    });
         });

my a.phpfile:

<?php
  if(isset($_POST['newMessages']))
  {
      $uid = $_POST['newMessages'];
      echo $uid;
  }
?>
+4
source share
2 answers

Listen to the onloadevent of the asynchronouslyloaded script and execute your function in callback. [ Ref ]

Try the following:

function loadScript(src, callback) {
  var s,
    r,
    t;
  r = false;
  s = document.createElement('script');
  s.type = 'text/javascript';
  s.src = src;
  s.onload = s.onreadystatechange = function() {
    if (!r && (!this.readyState || this.readyState == 'complete')) {
      r = true;
      callback();
    }
  };
  t = document.getElementsByTagName('script')[0];
  t.parentNode.insertBefore(s, t);
}

var message1 = "My message";
loadScript('https://code.jquery.com/jquery-1.10.2.js', function() {

  $(document).ready(function() {
    $.ajax({
      type: "POST",
      url: 'http://localhost/a.php',
      data: {
        newMessages: message1
      },
      success: function(data) {
        alert("success!");
      }
    });
  });
})
+1
source

The php file should return data in json format. You can add a complete, always bug to your Ajax to better catch the result.

-1

Source: https://habr.com/ru/post/1624537/


All Articles