How to call a variable in post function - javascript

I call a variable (t_d_url) in a post function. It doesn't show the variable data. It shows only variable name.
I tried this way to call it:
$.post(t_d_url.'/ascott/includes/booking/booking-summary.php', {}, function(data) {
$(".booking-summary").html(data);
});
Here is the variable:
var t_d_url = '<?php echo get_template_directory_uri(); ?>';
Here is the output:
So I want to show this variable data in this function.

You can not use . to merge 2 strings. That only works in PHP. In Javascript you should use +..
$.post(t_d_url+'/ascott/includes/booking/booking-summary.php', {}, function(data) {
$(".booking-summary").html(data);
})

You are using incorrect concatination operator. . doesn't work with Javascript try using + as
let url = "<?php echo get_template_directory_uri(); ?>/ascott/includes/booking/booking-summary.php";
$.post(url, {}, function(data){ $(".booking-summary").html(data);});
In worst case, this will call /ascott/includes/booking/booking-summary.php on current domain

You can use anyone of the following two method. Using + in JavaScript, because JS Doesn't merge strings using dot(.):
$.post(t_d_url+'/ascott/includes/booking/booking-summary.php', {}, function(data) {
$(".booking-summary").html(data);
})
Using PHP tag
$.post('<?php echo get_template_directory_uri(); ?>'+'/ascott/includes/booking/booking-summary.php', {}, function(data) {
$(".booking-summary").html(data);
})

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.

Update data through Ajax

I have the below code on href click I'm calling a javascript code in which an ajax is being called which returns the value of array $ss in json format . Now I want to know how can I update the value of $ss via ajax.
<div class="white" id="white" style="display:none">
<?php
foreach ($ss as $key => $value){
?>
<a href='javascript:void(0);' onclick='callAjax('<?php echo $key; ?>')'>
<?php
echo $value;
?>
</a>
<?php
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var res;
function on(id){
//alert('hi '+id);
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: ({a: id }),
success: function(data){
res = data;
//alert(res);
document.write(res);
}
});
}
</script>
And ajax.php files return array values for $ss.
I understood how to update data of normal div through ajax but encountering problem to pass the data returned by ajax call to update array value.
1- Lets be clear javascript will not replace the content of a php variable. 2- Even if so you will not be able to regenerate the html you need this way.3- after you receive your variable you need to update the html instead.
PS: Surely you can update the variable on the server side when you receive that ajax call,that also needs some requirements(the variable is global and accessible inside the php file...),but from what I have understood you want to change it with javascript which is not possible.
Your ajax must like this...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var res;
function on(id){
//alert('hi '+id);
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: {a: id },
success: function(data){
res = data;
//alert(res);
document.write(res);
}
});
}
</script>
I think you can't.
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it.
$ss = 'ss value';
if exists($_POST['ss']) {
$ss = $_POST['ss'];
}

Javascript Variable to Php json decoded

Actually i've used this script to get the profile picture of instagram user
<script src="http://codeorigin.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
var user_id = <? echo $page_id; ?>;
var url = "https://api.instagram.com/v1/users/"+user_id+"?client_id=775829274b6f48c1ac2bf218dda60e16&callback=?";
$.getJSON(url, function(data) {
$("body").append("<img src='"+data.data.profile_picture+"' />");
}
);
</script>
The Output of this script is 100% what i need.
All i need now is to take the image link to a PHP variable which is (+data.data.profile_picture+)
if tried to reload the same page with + ?link="+data.data.profile_picture+"
so i can grab it with $_GET['link']
Like this:
window.location.href = location.href + '?link="+data.data.profile_picture+";
but it doesn't .. What should i do to pass this javascript variable to a PHP variable.
Try This
window.location.href = location.href + '?link='+data.data.profile_picture;
You need to send your data to the PHP, and the simplest way would be using jQuery.ajax().
var picture = data.data.profile_picture;
$("body").append("<img src='"+picture+"' />");
$.ajax({
url: "http://example.com/webservices/getProfilePicture.php",
type: "POST",
data: {
'profile_picture': picture
},
success: function () {
console.log('Success!');
// Place eventual post-treatment here
},
error: function () {
console.log('Error..');
// Place eventual error-handling / debugging here
}
}
);
});
Then in PHP you can access it with this:
<?php $profile_picture = $_REQUEST['profile_picture']; ?>

Getting PHP variable to jquery script file by AJAX call

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);
}
});

Jquery ajax : dynamic success function

Hi i'm making a reusable javascript/ajax function used for validating input textboxes, checkboxes..etc. But I'm trying to create some sort of a generic validator using ajax. and so far i've managed to make my url and data dynamic by having this:
<?php
//contains php variables passed during after rendering the view
$url = //...some url;
$data = // array()... some array containing parameters;
$success = // should contain a string defining a function;
?>
So i get the needed php variables and pass them onto javascript, to use it into ajax like this :
<script>
$(document).ready(function(){
var submitUrl = '<?php echo Yii::app()->createAbsoluteUrl($url); ?>';
var params = <?php echo json_encode($data); ?>;
$.ajax({
url : submitUrl,
type : 'POST',
async : false,
data : params,
success : ??? // i don't know how to define this function dynamically based on php values
});
});
</script>
I don't know how to define success function dynamically. I tried defining :
var successFunction = <?php echo json_encode("function(response){ return 'sample response' ; }");?>;
but no luck. How do i put a success function dynamically from a string defining custom success function? Many thanks!
---------------------------------added-------------------------------------------
Practically i'm using X-edtiable extension.
$('.editable').editable({
type : editableType,
savenochange : true,
pk : 1,
emptytext: 'Click to edit',
params : function(){
return jsParameters;
},
url : submitUrl,
validate : validateFunction,
});
we use validate as :
validate : function(value){
//do some validation rules like if value < someValue or is a negative, or character
}
The problem is I've made the submitUrl dynamic, and editableType dynamic so far. but failed on the validate part. since I have a dynamic editable type. values could either be date, text, numbers, etc. And these have different validation rules, some may require another ajax call if i need to counter check something in the database. I was trying to make a validate function dynamic by basing it to some php variable passed onto the view after render, to see what validation rule is appropriate. Is this possible or am i making sci fi? Many Thanks!
There's no JSON encoding for functions. Use it for the data within the function body:
var successFunction = function(response) {
<?php switch($editableType) {
case 'date':
echo 'return response.test(dateRegexp);';
break;
case 'number':
echo 'return response.test(numberRegexp);'
break;
...
} ?>
};
you can use dataType: 'script;
<script>
$(document).ready(function(){
var submitUrl = '<?php echo Yii::app()->createAbsoluteUrl($url); ?>';
var params = <?php echo json_encode($data); ?>;
$.ajax({
url : submitUrl,
type : 'POST',
async : false,
data : params,
dataType: 'script'
});
});
</script>
https://api.jquery.com/jQuery.ajax/

Categories

Resources