How can I load my php on my domain using my javascript that was loaded dynamically.
my sample code
sample.html(Client-side)
<div onClick = "getThis()"></div>
my.js(Client-side)
function getThis(){
var url = "http://www.sampledomain.com/test.js"
var script = document.createElement('script');
script.src = url;
document.head.appendChild(script);
}
test.js(Server-side)
$.get("index.php", function(data) {
alert(data);
});
index.php(Server-side)
<?php
$_SESSION['user'] = "rob098";
?>
<script>
var data = '<?php echo json_encode($_SESSION['user']) ?>';
</script>
but it doesn't alert any.
Use ajax and json:
sample.html
<div onClick = "getThis()"></div>
my.js (inside sample.html)
function getThis() {
$.ajax({
url: '/test.php',
dataType: 'json',
success: function(data){
alert(data.user); //should alert rob098
},
});
}
test.php
header('Content-type: application/json');
echo json_encode(array("user" => "rob098"));
you have to append your js file to this
$(document).ready(function(){
$.get("index.php", function(data) {
alert(data);
});
});
so when script file loaded it will execute code inside jQuery ready function
I think you are using jquery $.get() the wrong way. Well I've never seen used that way at least, so you need to change your index.php to this:
<?php
$_SESSION['user'] = "rob098";
echo json_encode($_SESSION['user']);
header('Content-type: application/json');
?>
Let me know if I helped.
Related
I'm looking for some guidance on how if I have an already existing php variable, that is not a web element, just a string, how can I pass that as a variable to ajax?
here is a santized snippet of what I'm doing.
I want to be able to pass $my_php_var to ajax.
<?php
$my_php_var = "foo";
?>
$(document).on('click', '#btn_add', function(){
var my_php_var = $my_php_var;
$.ajax({
url:"directory/script.php"),
method:"POST",
data:{my_php_var:my_php_var},
dataType:"text",
success:function(data);
{
alert(data);
}
})
What you can do is, print it there inside another PHP tag:
<?php
$my_php_var = "foo";
?>
$(document).on('click', '#btn_add', function(){
$.ajax({
url:"directory/script.php"),
method:"POST",
data:{my_php_var:<?=$my_php_var?>},
dataType:"text",
success:function(data);
{
alert(data);
}
})
Where <?=$var?> is short version of <?php echo $var; ?>.
I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard
I am trying to use some data calculated with a php script in javascript, this is my code :
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<button onclick="duplicate()"> button send</button>
<script>
function duplicate()
{
var action = "CreationBoard";
alert(action);
$.ajax({
type : "POST",
url : "file.php",
data : { action : action },
success: function(output) {
alert(output);
}
});
}
</script>
</body>
</html>
So I'm calling file.php to calculate my data :
<?php
if(isset($_POST['action']))
{
$return = some_function($_POST['action']);
}
?>
I need to use $return in javascript, how to do that ?? I've seen many examples, but they only show how to send data with Ajax to php, not from php to ajax.
How should I do that ??
All you need to do
<?php
if(isset($_POST['action']))
{
$return = some_function($_POST['action']);
echo $ return
}
?>
Javascript doesn't know php variable. All it know is the data returned
In your file.php I would do
echo json_encode($return);
And then modify your ajax to expect a json return:
function duplicate()
{
var action = "CreationBoard";
alert(action);
$.ajax({
type : "POST",
url : "file.php",
data : { action : action },
dataType: 'json',
success: function(output) {
alert(output);
}
});
}
the output variable that you have in your alert should look like your array and you can do with that what you want.
I have 2 files "index.php" and "userip.php". I want to pass the variable varip to the file "userip.php" with ajax. If this is successful I want to share POST['name']; in a session. I thought that the session would be set but when I reload the index.php page the echo shows nothing. Can someone help me out?
index.php (jQuery section):
<script type="text/javascript">
$.getJSON("http://ip.jsontest.com/", function(data) {
var varip = "";
$.each(data, function(k, v) {
varip += v;
$.ajax({
type: "POST",
url: "userip.php",
data: "name="+varip,
success: function(data){
alert("ok");
}
});
});
});
</script>
index.php (php section):
<?php
echo $_SESSION['userip'];
?>
userip.php:
session_start();
if(!empty($_POST['name'])){
$variable = $_POST['name'];
$_SESSION['userip'] = $variable;
}
The problem is that you are missing session_start() in your index.php file, so at that point $_SESSION hasn't been loaded.
But it looks like you're getting the user's IP address?
<?php
echo $_SERVER['REMOTE_ADDR'];
change
data: "name="+varip,
to
data: { name: varip },
I need pass jQuery variable to PHP variable, so I made simple code to test and it doesn't work.
It's only a testing files. Finally, I have to do something more advanced but i can't make it works!
I have 3 files
In character.html I have:
SAVE
and in character.js (it's external javascript for character.html)
$(document).ready(function() {
$('.saved').click( function () {
var avatarID = 123;
$ajax({
url :'character-save.php',
data:{"avatarID":avatarID},
type: 'post',
dataType: 'json',
});
});
});
in character-save.php i try this:
<?php
header('Content-type: application/json');
$result = $_POST['avatarID'];
$result = htmlentities($result, UTF-8);
echo json_encode($result);
exit();
?>
And it doesn't print 123
In your php file, you have a mistaks with UTF-8, it should be included with parentheses.
<?php
header('Content-type: application/json');
$result = $_POST['avatarID'];
$result = htmlentities($result, 'UTF-8'); // It should be 'UTF-8'
echo json_encode($result);
exit();
?>
Your syntax is wrong its not $ajax its $.ajax don't forget the . dot.
Also you need some way of checking response so either update your html by adding ajax callback and necessary jquery, use alert or log reponse to console. Something like this should give you a good indication.
$.ajax({
url :'character-save.php',
data:{"avatarID":avatarID},
type: 'post',
dataType: 'json'
}).done(function(response) {
alert(response.data);
});
In your PHP change $result = htmlentities($result, UTF-8); to $result = htmlentities($result); also validate your json by putting result in an array then encode that array as json and echo it like this:
<?php
header('Content-type: application/json');
$result = $_POST['avatarID'];
$result = htmlentities($result);
$return["data"] = $result;
echo json_encode($return);
exit();
?>
In your javascript you have to add e.preventDefault(); to prevent the page redirecting to character-save.php
And inside the click function add e
see the updated javascript section below
$(document).ready(function() {
$('.saved').click( function (e) {
e.preventDefault();
var avatarID = 123;
$.ajax({
url :'character-save.php',
data:{"avatarID":avatarID},
type: 'post',
dataType: 'json',
success: function(msg){
alert(msg);
}
});
});
});
Try this,
$(document).ready(function() {
$('.saved').click( function () {
var avatarID = 123;
$ajax({
type:"POST",
url: 'character-save.php&avatarID='+avatarID ,
success:function(response){
alert(response);
});
});
});
In character-save.php try this:
<?php echo $_GET['avatarID'];
?>