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);
Related
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 2 years ago.
I have a variable that holds the value of a checked checkbox. I need to pass it to a PHP file as a PHP variable so that I can run a query with it. I was told I could achieve this with AJAX but I have no knowledge on it and very little time. I would really really appreciate some help!
<script>
function checked(){
var chkbxElements = document.getElementsByClassName("checkboxes");
for (element of chkbxElements){
if (element.checked)
return element.value ;
}
return null;
}
var element = checked(); //pass it to a php file
I tried the code below but it doesn't work.
$.ajax({
method: "POST",
url:"file.php",
data: {id: element},
success: function(data){}
})
</script>
<?php
$id = $_POST['id'];
?>
Since you are confident that you got the right element (the string data of the value attribute) only the AJAX part needs to be demonstrated here:
// jQuery:
$.ajax({
method: "POST",
dataType: "JSON",
url:"https://jsonplaceholder.typicode.com/posts",
data: {uploadData: "my jQuery payload"},
success: function(data){
console.log(data);
}
})
// Vanilla:
fetch("https://jsonplaceholder.typicode.com/posts",
{method: 'POST',
body: JSON.stringify({
uploadData: 'my Vanilla-JS payload'}),
headers: {'Content-type': 'application/json; charset=UTF-8'
}})
.then(r=>r.json())
.then(j=>console.log(j))
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
Obviously, I had to use some other backend server to send the data to but it should work with your own backend just es well.
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>
I am successfully inserting data into my database in codeigniter via a an ajax post from javascript:
//JAVASCRIPT:
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
$('body').append(data); //MH - want to avoid this
}
});
//PHP:
public function respond(){
$this->load->model('scenarios_model');
$responseID = $this->scenarios_model->insert_response();
//redirect('/pages/view/name/$responseID') //MH - not working, so I have to do this
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
echo "<script>window.location = '$redirectURL'</script>";
}
But the problem is that I can't get codeigniter's redirect function to work, nor can I get PHP's header location method to work, as mentioned here:
Redirect to specified URL on PHP script completion?
either - I'm guessing this is because the headers are already sent? So as you can see, in order to get this to work, I have to echo out a script tag and dynamically insert it into the DOM, which seems janky. How do I do this properly?
Maybe you can 'return' the url in respond function and use it in js
PHP :
public function respond(){
// code
$redirectURL = base_url() . 'pages/view/name/' . $responseID;
return json_encode(['url' => $redirectURL]);
}
JS :
$.ajax({
type: "POST",
url: submissionURL,
data: submissionString,
dataType: 'JSON',
failure: function(errMsg) {
console.error("error:",errMsg);
},
success: function(data){
window.location = data.url
}
});
you have to concatenate the variable. That's all.
redirect('controller_name/function_name/parameter/'.$redirectURL);
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);
});
So basically i have two files. 1 is my php file and it creates tables with some variables when it's called, and second file is jquery script file that makes that call. My script file:
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
$('#results').html(data);
}
});
and it works fine by printing my results.
My php file is echoing data that should be printed in my results div.
Question is how to get some PHP data variables and be able to use them in my jquery file without actually echoing them ??
Like i said in my comment to your question, a way to do that is by echoing the variables on a script tag, so you can access in javascript.
<script>
var PHPVariables;
PHPVariables.VariableName1 = '<?=$phpVariableName1?>';
PHPVariables.VariableName2 = '<?=$phpVariableName2?>';
PHPVariables.VariableName3 = '<?=$phpVariableName2?>';
</script>
And you could use those values accessing PHPVariables.VariableName1 on the javascript.
You can do this by echoing all the data you want like so peiceofdata§anotherpeice§onemorepeice§anotherpeice then you can use php's explode function and use § for the "exploding char" this will make an array of all the above data like this somedata[0] = peiceofdata somedata[1] = anotherpeice and so on.
the explode function is used like this
explode('§', $somestringofinfoyouwanttoturnintoanarray);
you can then echo the relevent data like so
echo data[0];
which in this case wiill echo the text peiceofdata.
write this type of code in ajax file
var data =array('name'=>'steve', date=>'18-3-2014');
echo jsonencode(data);
//ajax call in this manner
$.ajax({
type: 'POST',
data: pass data array,
url: ajaxfile url,
success: function(data) {
var data = $.parseJSON(data);
$('#name').html(data.name);
$('#date').html(data.date);
}
});
Use json format, and in this json add your data variables :
PHP :
$arr = array('var1' => $var1, 'var2' => $var2, 'var3' => $var3);
echo json_encode($arr);
Javascript :
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
data = JSON && JSON.parse(data) || $.parseJSON(data);
$('#results1').html(data.var1);
$('#results2').html(data.var2);
}
});