Passing a simple javascript variable to php file - javascript

I want to pass a simple javascript variable to another php file which is a controller file in laravel.
For example: below is a code from my blade.php file of laravel.
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert('Geolocation is not supported by this browser.');
}
}
function showPosition(position) {
var latitude = position.coords.latitude;
var longitude =position.coords.longitude;
var dataString = 'latitude'+latitude+'longitude'+longitude;
$.ajax({
type: "POST",
url: "PagesController.php",
data: dataString
});
}
getLocation();
</script>
As latitude and longitude are not form values then how should I catch these values in controller file named as PagesController.php of laravel.

You can try this approach
$.ajax({
type: "POST",
url: "PagesController.php",
data: {latitude: latitude, longitude: longitude},
});
and on PagesController.php
$latitude = $_REQUEST['latitude'];
$longitude = $_REQUEST['longitude'];

Form value submissions simply send formatted data via a http request. You can also do this using javascript(jQuery makes it easier).
Set up the php file that will accept the variable on your server. The php file should look something like this:
File: calculations.php (You can name it whatever you want)
<?php
$dataString = $_POST['dataString'];
// your calculations here
echo $result;
?>
Then use jQuery to make an ajax request to your php file and pass the variable to your php file.
$.ajax({url: 'calculations.php', data:{dataString:dataString} type:'POST', success: function(result){
console.log(result); // will output the $result
}});
After the calculations are done the function stored in the success field will be executed, and whatever you echo'ed out in the php file will be stored in the result variable in your javascript.
Further reading: jQuery Ajax

Related

Cannot pass JS variable to PHP using AJAX

I am trying to get current location of user.
I have JS script to get current Latitude and Longitude with AJAX to send js variables to index.php.
$(document).ready(function() {
if ("geolocation" in navigator){
navigator.geolocation.getCurrentPosition(function(position){
var userLat = position.coords.latitude;
var userLong = position.coords.longitude;
console.log(userLong);
console.log(userLat);
$.ajax({
type: 'POST',
url: 'index.php',
data: {
userLat : userLat,
userLong : userLong
},
success: function(data)
{
console.log(data);
}
});
});
}else{
console.log("Browser doesn't support geolocation!");
}});
Then I am trying to do this in my index.php:
echo $_POST['userLat'];
echo $_POST['userLong'];
Nothing shows up. Thanks in advance.
Nothing shows up.
And that's correct you will never get any thing by browsing index.php because there is no POST at this time , AJAX is internal and the only way to show a result from index.php is in the page that you send from it an ajax call.
At this :
success: function(data)
{
console.log(data);
}
you could control where to show your data that comes from index.php by , for example alert(data) or document.getElementById("someelement").innerHTML=data; and so on.
It might help to define and return a dataType for the ajax.
add this to your list of ajax options
dataType: 'json',
Then in index.php encode and echo a json string. Remove the lines
echo $_POST['userLat'];
echo $_POST['userLong'];
replace them with
echo json_encode($_POST);
The console.log(data); in the success function should show an object with two items: 'userlat' and 'userLong' and associated values for each. Or it should if $_POST had those two items.
If you want the browser screen to update you will have to take data and use it to modify the DOM.

How to access a javascript variable inside a php query?

I want to access a javascript variable inside a php query
function myFunction2(){
Total=parseInt(point2)
<?php
$con->query("UPDATE eventlist SET P2 = $this.Total WHERE Eid=$PID");
?>
}
I want the query to set p2=value of total
I understand that php is a serverside script and I cant do this like this. What is an alternative to this.?
EDIT
ok i got this on the JS side
function myFunction2(){
var Total = parseInt(point1)+parseInt(point2);
$.ajax({ url: 'ajax.php',
data: {'total' : Total},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error");
}
and if i put
echo $_POST['total']
in ajax.php i get an alert with the value passed. So i think the value is being passed properly.
But what i need to do is a Mysql Query.
$con->query("UPDATE eventlist SET P2 = $_POST['total']; WHERE Eid=1");
Something like this. How do i do this
Try send javascript value to another php page which contain your query
function myFunction () {
var param = "value";
$.post('query.php', { postvalue: param}, function(data) {
//do what you want with returned data
//postvalue should be the name of post parameter in your query page
})
}
Change your PHP in this way:
$total = $_POST['total'];
$con->query("UPDATE eventlist SET P2 = $total WHERE Eid=1");

Call Php controller function with AJAX Codeigniter

I , im working with Ajax and Codeigniter to call function client-server
the php
public function mainViewClean() {
unset($_SESSION[$this::jsondevices]);
unset($_SESSION[$this::jsontags]);
return "Ready";
}
//route $route['cleantags'] = 'user/mainViewClean';
And ajax:
<script type="text/javascript">
$(document).ready(function(){
$("#btn_recargar").button().click(function(){
//window.location.href = "<?= base_url('home')?>";
$.ajax({
type:'POST',
url:'<?php echo base_url("cleantags"); ?>',
data:{'id':100},
success:function(data){
//window.location.href = "<?= base_url('home')?>";
alert(data);
}
});
});
});
</script>
The function excuse good , but javascript don't show any data , what im doing wrong?
Well, the ajax call reads the response from the server, and that response must be rendered as some type of readable data, such as application/json or text/html.
In order to write that data, you need to echo it from the server with PHP.
The return statement doesn't write data, it simply returns at the server level.
If you want to communicate between PHP functions, you have to use return. But if you want to output some data, you have to use echo
Client side
$.ajax({
url:'<?php echo base_url("cleantags"); ?>',
dataType: 'application/json',
success:function(response)
{
alert(response.foo);
}
})
Server Side
public function mainViewClean()
{
unset($_SESSION[$this::jsondevices]);
unset($_SESSION[$this::jsontags]);
echo json_encode( array("foo"=>"Ready"));
}
Change return into :
echo "Ready";
If you're sending an array, at server side you need to json_encode, example :
// encode array into json string format
echo json_encode( array( 'name' => 'Osman' ) );
And in Js, you have 2 options, the 1st solution is :
success : function ( data ) {
// data now is coming in this form { "name" : "osman" }
// as the string data is coming from server-side
// you must parse it back into Javascript object
var newData = JSON.parse( data );
}
And the 2nd option is, add dataType properties inside ajax properties like following :
$.ajax({
...
dataType : 'json', // with this, no need to write JSON.parse()
...
});
I'm fairly new as I only have been using AJAX , but I think your code has a few syntactical errors.
data: { id:100 } with no quotations around id.
I advise you need to look at more examples of ajax calls to fix these little errors.
You said your JS is working but not showing data?

Javascript Not Calling PHP function in wordpress

I am trying to get the following code to work:
//In Javascript
function updateContentEditable(){
var span = $(this);
var data = new Object();
data.pid = '1';
data.content = 'this is a test';
data.action = 'update_content'; //This should run update_content php function
$.post(ajaxPath, data, onContentSaved); //ajaxPath returns: /wp-admin/admin-ajax.php
}
//In PHP
function update_content(){
echo "<script>alert (\"php was reached\")</script>";
}
NOTE:
//onContentSaved is this:
function onContentSaved(data){
console.log(data);
}
My problem is the the php function is not being run.
What I'm I doing wrong?
Assuming you are using jquery, try this:
function SendRequestCallBack(webMethod, parameters, callBack) {
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
success: function(results) {
$(".ajaxImage").hide();
eval(callBack(results.d));
}
});
}
function formatData(obj){
alert(obj);
}
$(document).ready(function()
{
SendRequestCallBack("http://url-to-php","{'any':'parameters'}",formatData);
});
Then all the PHP needs to do is echo valid JSON. Or if you like you can change the contentType: parameter to text/xml or text/plain etc depending on what you want it to return. Keep in mind that your PHP needs to output the matching content type as well. for example
<?php
header("Content-type: text/json");
echo {"d":[{"firstname":"John","lastname":"Doe"},{"firstname":"Jane","lastname":"Doe"}]}
?>
If you want to pass data in to the PHP function, set it in the parameters, and make sure that your PHP will accommodate it using the $_POST array.

get json string at server side in php-wordpress

hy,i am working on a wordpress plugin in which i require to delete multiple items using checkbox.when i check all rows and delete them i get their row id in the form of json string.
js code:
$('.check_it:checked').each(function (i){
c[i]=$(this).val();
});
var chk = JSON.stringify({ list: c });
debugger
$.ajax({
type:"POST",
data: chk,
url:'/word/wp-content/plugins/craiglist/action.php?action=delete_leads',
dataType: "json",
success:function(response){
alert('fdsfsfdsfd');
},
failure:function (response) {
alert("Please Try Again");
},
error:function (xhr, status, error) {
alert(xhr.response);
}
});
In var chk i got string like
"{"list":["151","152","153","154","155","156","157","158","159","160","161","162","163","164","165","166","167","168","169","170","171","172","173","174","175"]}"
how can i get it at server side in php and send it to database so i can delete the so called rows.
Because you are sending JSON as the post data, you will have to access the raw post data on the PHP side. This can be done like so:
$obj = json_decode($HTTP_RAW_POST_DATA);
foreach($obj->list as $item)
{
// delete from mytable
$wpdb->query(
$wpdb->prepare("DELETE FROM mytable WHERE id = %d", $item)
);
}
If you want the data in a $_POST variable, then you will have to change your ajax request data to something like:
$.ajax({
....
data: { list : JSON.stringify(c) },
....
Now, on the PHP side it is present in $_POST['list']. So you can do:
$obj = json_decode($_POST['list']);
foreach($obj->list as $item)
{
// delete from mytable
$wpdb->query(
$wpdb->prepare("DELETE FROM mytable WHERE id = %d", $item)
);
}
In your server side php since you're not calling the get_header() function, you have to add this piece of code manually require_once('../../../wp-load.php'); and you can now call global $wpdb; safely and all wp functions. Please also take note that you're php file must be inside your theme together with your functions.php and other core files. Do not put it into another directory inside your theme

Categories