Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass javascript variables into PHP use AJAX

I have 1 javascript variable and i want to pass i to my php file. i search about it and i find that to use ajax but i don't really know how use it ! here is my code . where am i do 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.php file :

<?php
  if(isset($_POST['newMessages']))
  {
      $uid = $_POST['newMessages'];
      echo $uid;
  }
?>
like image 771
Ali Motiee Avatar asked Nov 20 '22 17:11

Ali Motiee


1 Answers

Listen onload event of the asynchronously loaded script and execute your function in callback function.[Ref]

Try this:

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!");
      }
    });
  });
})
like image 97
Rayon Avatar answered Nov 23 '22 07:11

Rayon