5

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;
  }
?>
Ali Motiee
  • 51
  • 4
  • how can i know it's fired or not ? – Ali Motiee Jan 16 '16 at 01:48
  • 2
    Any specific reason to load `jQuery` asynchronously..Always keep your console open while development.. – Rayon Jan 16 '16 at 01:49
  • Use console.log() or alert to see what is in newMessages and message1, don't see newMessages defined... – Andrew Jan 16 '16 at 01:50
  • From what you said, the JS part of code you showed is included in a `my.js` file. But 1) where is located the `` element? 2) there must be other JS code before `var message1 =...`: can you show it? – cFreed Jan 16 '16 at 01:51
  • POST http://localhost/a.php 200 OK jquery.min.js (line 4) – Ali Motiee Jan 16 '16 at 01:54

2 Answers2

1

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!");
      }
    });
  });
})
Community
  • 1
  • 1
Rayon
  • 36,219
  • 4
  • 49
  • 76
-1

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

Max Y.
  • 19
  • 2