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;
}
?>
Listen
onload
event of theasynchronously
loaded script and execute your function incallback
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!");
}
});
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With