how to pass js variable to php via ajax - javascript

Hello I am new to js and I stuck on the problem about passing variables to php via ajax.
<script>
$date = "123";
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: ({'date': date}),
success: function(data){
console.log("successfully");
}
});
</script>
And below is my code in record.php file.
<?php
session_start();
if(!empty($_POST['date'])){
//$hello = 'hh';
$_SESSION['date'] = $_POST['date'];
echo($_SESSION['date']);
}else{
echo "its empty(var)";
}
?>
Page always print out "its empty(var)" and I checked console, it shows "successfully"... I already stayed on this problem for several hours and looked for a lot of similar post, but I still can't find where is the problem. Can anyone have a look at it? I also already loaded the jQuery library.

you ar mixing js variable with php variable, js variables are declared with var and php variables are declared with $fieldname
<script>
var date = "123";
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: {'date': date},
success: function(data){
console.log("successfully");
}
});
</script>

if you want a PHP variable insite javascript you should define php variable first then asign it into js.
<?php $date = "123"; ?>';
<script>
var date=<?php echo $date; ?>';
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: ({'date': date}),
success: function(data){
console.log("successfully");
}
});
</script>
Hope it wil helps you.

You cant mix server (php) and client (js)
you might to this
<?php $var = 0?>
then in html you create
<input id="something" type="hidden" value="<?php echo $var?>">
then you get that value via
document.getElementById("something").value;

You are declaring $date and pass in your ajax as date.
Try this:
<script>
var date = "123";
$.ajax({
url: './record.php',
type: "POST",
dataType:'text',
data: {'date': date},
success: function(data){
console.log("successfully");
}
});
</script>

Related

Why php file is not executed after upgrade to php 7?

I am reviewing a web page that uses javascript, php, ajax and that with php5 worked correctly, but having updated to php7 no longer works.
I comment the details below:
In the screen I am reviewing, MyWebPage/Folder1/protected/views/applications/file1.php is executed which assigns to the variable $load this value:
$load='protected/views/aplicaciones/cargas/file2.php';
At the end of this php there is a block of code where it call several javascript libraries and then assign value to various dynamic variables, using this code:
<script type="text/javascript">
var startTime = "<?php echo $INIT; ?>";
var endTime= "<?php echo $END; ?>";
var period="<?php echo $PERIODUSED; ?>";
var db="<?php echo $DATABASE; ?>";
var loadpage="<?php echo $loadpage; ?>";
</script>
So this php calls the file3.js javascript using this code:
<script type="text/javascript" src="protected/views/aplicaciones/aplicacionesjs/file3.js"></script>
This javascript theoretically calls file2.php, using this code:
function requestData()
{
waitingDialog({});
$.ajax({
data: "startTime="+startTime+"&endTime="+endTime+"&period="+period+"&db="+db+"",
type: "POST",
url: loadpage,
datatype: "json",
success: function(data)
{
closeWaitingDialog();
var json= eval(data);
// Process and paint json
// ...
},
error: function()
{
closeWaitingDialog({});
},
cache: false
});
With Firebug I see that loadpage = protectec/views/aplicciones/cargas/file2.php
that looks to be right.
However, the problem is that after the line
var json= eval(data);
the value of json is undefined and instead of this it should contain a series of data that should be displayed on the page.
From the tests I have done with Firebug it seems to me that the problem could be that protectec/views/applications/loads/file2.php is not being executed.
Any comment or suggestion is appreciated.

load a file using variable from client side

I need to load a file inside a container, but using an argument - to get some data from database firstly:
$('#story').load('test.php');
test.php
$st = $db->query("select * from users where id = " . $id);
... processing variables... load the finished content
Here I need $id from client side. Is it possible?
yes ..you could pass with url query
$('#story').load('test.php?id=1');
test.php
$id = isset($_REQUEST['id'])?$_REQUEST['id']):'';
$st = $db->query("select * from users where id = " . $id);
You can use ajax request and on success you load your file something like:
$.ajax({
type: 'POST',
url: "test.php", //make sure you put the right path there
data: {id: id},
dataType: "json",
success: function (resultData) {
$('#story').load('test.php');
}
})
Just make sure that your php function returns/echos the id you want.
That way you make a call to your php file and when it's successful you will load your file and you can put extra logic there if you want to return more data to use it of course.
resultData holds the output of your php function so it's up to you what info you want to be there.
You could use Ajax to post the ID to your php code.
$.ajax({
type: "POST",
url: "test.php",
data: { 'id': foo },
cache: false,
success: function(){
alert("Order Submitted");
}
});
php:
<?php
$id = $_POST['id'];

send Php variables to javascript using AJAX [duplicate]

This question already has answers here:
Using AJAX to pass variable to PHP and retrieve those using AJAX again
(5 answers)
Closed 4 years ago.
I have two PHP variables that I want to pass to javascript using AJAX.
test.php
$Longitude = json_encode($Long);
$Latitude = json_encode($Lat);
Index.js
$.ajax({
type: 'POST',
dataType: "json",
url:'test.php',
data:
success: function(data)
{
console.log("testing");
}
});
I am new to programming. Please guide how to refer these variable names in the ajax call.
Pass in array and encode it.
test.php
$data = ['Longitude ' =>$Long, 'Latitude ' => $Lat ];
echo json_encode($data);
index.js
$.ajax({
type: 'POST',
dataType: "json",
url:'test.php',
data:
success: function(data)
{
try {
data = JSON.parse(data);
}catch(e) {}
console.log(data);
}
});
Set your php variable into two hidden text box. Like below.
<input type="hidden" name="Longitude" id="Longitude" />
<input type="hidden" name="Latitude" id="Latitude" />
now get that both the field name into javascript. Like below.
var lats = $("#Longitude").val();
var longs = $("#Longitude").val();
Now pass above data into your ajax call. Like below.
$.ajax({
type: 'POST',
dataType: "json",
url:'test.php',
data:{ lats:lats,longs:longs},
success: function(data)
{
console.log("testing");
}
});
You are going to need to echo the variables you want to access in order for javascript to be able to read them.
try something like this in test.php:
$data = ['lat' => $lat, 'lon' => $lon];
echo json_encode($data);
then in index.js in the success function:
console.log(data);

Not sending data into controller with onclick function

I use this button in jason.
<button id="bid" type="button" class="button" onclick="connect()">Save</button>
It show altert when I use alert after document.getElementById. But it not works in ajax function. Here is my connect function
function connect()
{
var BID = document.getElementById('BID').value;
var REF = document.getElementById('ref_po').value;
var POU = document.getElementById('po_units').value;
//**alert(BID + REF + POU);**
var url ='<?php echo base_url()."index.php/main/transacIn/" ?>';
$.ajax({
type: "POST",
url: url,
data: 'BID='+BID +'&REF='+REF +'&POU='+POU,
success: function(data) {
//$("#bid").hide();
alert(BID);
}
});
}
alert(BID + REF + POU); this alert works but not works alert in success. And it don't sent any data into controller. Help me about it. Thanks in advance.
try this
function connect()
{
var BID = document.getElementById('BID').value;
var REF = document.getElementById('ref_po').value;
var POU = document.getElementById('po_units').value;
var site_url = document.getElementById('site_url').value;
var url = site_url+'main/transacIn';
$.ajax({
type: "POST",
url: url,
data: {
BID : BID ,
REF: REF,
POU:POU
},
success: function(data) {
//$("#bid").hide();
alert(BID);
},
error: function(err) {
console.log(err);
}
});
}
you should a hidden field in your corresponding page <input id="site_url" type="hidden" value="<?php echo site_url(); ?>"/>
You cannot inject the php syntax into javascript file. Either you define the script in codeigniter template file as
<script type="text/javascript">
// Your javascript function
</script>
...or you can define a javascript variable in the template file which actually get the path to your controller:
var url = <?php echo base_url()."index.php/main/transacIn/" ?>';
Then on your javascript file on ajax post you are pointing to the variable defined in the template file:
$.ajax({
type: "POST",
url: url,
data: 'BID='+BID +'&REF='+REF +'&POU='+POU,
success: function(data) {
//$("#bid").hide();
alert(BID);
}
});
Hope you got the idea.
Anyway you need to be careful defining global variables. It's a good practice to guard the variables by using namespaces.
Try this solution. It will work:
$.post(url , {BID: BID, REF: REF, POU:POU },
function(data){
alert(BID);
});

How to retrieve and store data with Ajax

I want to return multiple data (variables) from PHP instead of just 1 piece of returned html code.
Right now I got this:
$.ajax({
url: "test.php",
cache: false
})
.done(function(html) {
$('video').attr('src', html);
});
But I want to be able to do someting similar to this:
$.ajax({
url: "test.php",
cache: false
})
.done(function(data) {
$('video').attr('src', data.videoUrl);
$('video').attr('poster', data.posterUrl);
});
In my test.php I have this:
$posterUrl = "thumbnail.png";
$videoUrl = "video.mp4";
echo $posterUrl;
echo $videoUrl;
How can I accomplish something like that?
The easiest way? JSON.
JavaScript:
$.ajax({
url: "test.php",
dataType: "JSONP"
}).done(function(json) {
$("video").attr("src", json.videoURL).attr("poster", json.posterURL);
});
PHP:
$output = array();
$output["posterURL"] = "poster.png";
$output["videoURL"] = "video.mp4";
echo json_encode($output);
You may need to json_encode the response like this.
$response = array("videoUrl"=>"video.mp4","posterUrl"=>"video.mp4");
echo json_encode($response);
You can return a JSON instead of a string.
More info here: http://api.jquery.com/jQuery.getJSON/

Categories

Resources