Pass JavaScript variable to php script - php

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 },

Related

Execute php using jquery post

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

How can I take jquery id in session

This is my jQuery code for taking id value when I click itemslist
$(document).ready(function() {
$('.itemslist ul li').click(function()
{ $id = $(this).attr("class");
});
});
But session is not taking that id value
session_start();
$_SESSION['catname'] = $id;
$id= $_SESSION['catname'];
session_destroy();
Can any one please say the answer about this?
You can't assign values to PHP variables from withing Javascript/Jquery. You should make an AJAX call to a PHP file that handles the creation/destroying of the SESSION.
See this answer.
for that you need to call the Ajax to store the session value, given example code here
$(document).ready(function() {
$('.itemslist ul li').click(function() {
var id = $(this).attr("class");
$.ajax({
type : "POST",
url : youphppage.php,
data :"id="+id ,
success: function (msg) {
alert(msg); // you will get stored session value here
}
});
});
});
In your php page while ajax call,
session_start();
$_SESSION['catname'] = $_POST['id'];;
echo $id= $_SESSION['catname'];
you can use ajax for send your id to server page and store your id in session.
$(document).ready(function() {
$('.itemslist ul li').click(function()
{ id = $(this).attr("class");
$.ajax({
type : "POST",
url : Postpage.php,
data :"id="+id ,
success: function (json) {
alert(json);
}
});
});
Server side
session_start();
$id=$_REQUEST['id'];
$_SESSION['catname'] = $id;
$id= $_SESSION['catname'];
session_destroy();
Use jquery ajax to send the data in a php file in post method and retrieve the value on that page
$(document).ready(function() {
$('.itemslist ul li').click(function()
{ var a = $(this).attr("class");
var dataString = 'a=' + a;
$.ajax(function(){
type : "POST",
url : "session.php",
data : dataString,
cache: false,
success: function(data){
alert('session sent!');
}
});
});
});
and the session.php:
session_start();
$a= issest($_POST['a']):$_POST['a']:"";
$_SESSION['catname'] = $a;
session_destroy();

My ajax/jquery script to send $_GET to php isn't working? (Wordpress)

This is the code that I'm using to send a variable (via GET) to another php file:
(basically, I click on a button, and then js gets the id and sends the id via ajax to the php file.
$(document).ready(function() {
$(".doClick").click(function() {
var category=$(this).attr('id');
$.ajax({
url:'aFile.php',
type:'GET',
data: $category,
success: function(data){
alert("It worked?"); // this is the response
}
});
alert($(this).attr("id"));
});
});
This is the code in my aFile.php:
The php file gets the info via $_GET[] and then assigns it to a variable and uses that variable in a function call.
<head>
<script type="text/javascript">
$(document).ready(function() {
function JS() {
//code
});
</script>
</head>
<body onload="JS()">
<?php
$category = $_GET['category'];
if (function_exists('inventory_insert')) {
echo inventory_insert('{category_name = '.$category.'}');
} else echo('warning');
?>
It's supposed to give me a response back on my main page, but nothing seems to be happening. I don't even get the alert I posted after the ajax script.
your variable is category but you're sending data: $category
You must send key/value pair to server
to receive $_GET['category'] your data sent in ajax needs to be either:
data: 'category='+category
Or
data: {category: category}
You have assigned id into category in jquery. so correct in data params.
data: {category : category},
Send it in this way to server or php file.
$(document).ready(function() {
$(".doClick").click(function() {
var category=$(this).attr('id');
$.ajax({
url:'aFile.php',
type:'GET',
data: {category : category},
success: function(data){
alert("It worked?"); // this is the response
}
});
alert($(this).attr("id"));
});
});

Load php dynamically from a dynamic javascript

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.

How to send a variable in an AJAX site?

I created an Ajax navigation system but I've an issue when I want to send a variable.
I've an index.php like this
<script src="navigation.js" type="text/javascript"></script>
<div id="pageContent"></div>
page1
profile
This is navigation.js
$(document).ready(function(){
checkURL();
$('a').click(function (e){
checkURL(this.hash);
});
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#','');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
}
}
});
}
And this is the load_page.php page:
<?php
if(!$_POST['page']) die("0");
$page = $_POST['page'];
include('pages/'.$page.'.php');
?>
This is the issue: when I load profile.php page I want to see values by GET... example:
<?php
$nome_utente = $_GET['user'];
if(!$_GET['user']) {
print 'Attention! You have to insert a username';
}
else
{
print $nome_utente;
}
?>
To do this I tried to change the link in index.php
profile
But this doesn't work because load_page.php doesn't find the "profile?user=test.php" page.
What do I have to do to send a GET variable at profile.php, from a link in index.php?
I've to edit JS or PHP code?
Mixing get/post variables is considered poor practice, but is easily done:
function loadPage(url) {
url=url.replace('#','');
$.ajax({
type: "POST",
url: "load_page.php?user=whatever_you_want_here",
^^^^^^^^^^^^^^^^^^^^^^^^^^^^---your 'get' query
The other optiont would be to add the 'user' parameter to your ajax data line:
data: { page: url, user: whatever_you_want_here }
The first one would make 'user' available in $_GET, the second one would make it available in $_POST.

Categories