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.
Related
I am trying to send information using AJAX from JavaScript in one file to PHP in another file. When I inspect the page on chrome after I have pressed the button, it shows the values under the form data sub section in networks, however, if I var_dump[$_POST] it shows it is empty.
Here is my JavaScript:
function details(id) {
var data = {"id" : id};
jQuery.ajax({
url: "/Example/includes/detail.php",
type: 'POST',
data: data,
success: function(data){
jQuery('body').append(data);
},
error: function(){
alert("Error");
}
});
}
Here is the PHP:
<?php
$id = $_POST['id'];
$id = (int)$id;
?>
Any help would be greatly appreciated. Thanks
I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.
I want passing 2 parameters to PHP page via AJAX and load the response, but this code is not working.
JavaScript:
$(".show_category").click(function(){
var category_id = $(this).attr('data-category');
$.ajax({
url: "conx.php",
method: "POST",
data: {
action: "sort_category",
category_id: category_id
},
success: function(data) {
$("#con").load("conx.php");
}
});
});
PHP:
<?php
echo "1".$_POST["action"]."<br/>";
?>
You issue is here:
success: function(data) {
$("#con").load("conx.php");
}
At this point, you have already posted the data and received the HTML response. There is no need to make another HTTML request by calling .load, and doing so will mean requesting it again without the POST data, so it will not have the intended effect. Just use the HTML you already have in the data argument.
success: function(data) {
$("#con").html(data);
}
On a side note, this PHP code is a reflected XSS vulnerability:
<?php
echo "1".$_POST["action"]."<br/>";
?>
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
I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.