jQuery.ajax post is being sent but $_POST is empty - javascript

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

Related

AJAX Post error like no $_POST variable

I'm developing a part of a website that upload the content of a textarea and of an input text to a remote database, but I have a problem in the AJAX request...
my JavaScript:
function pubblica(pubblicato){
htmlpuro = document.getElementById("htmlpuro").value;
oggetto = document.getElementById("oggetto").value;
$.ajax({
type: "POST",
url: "salva_doc_ajax.php",
data: "oggetto="+oggetto+"&html="+htmlpuro+"&pubblicato=0",
dataType: "html",
//Inizio visualizzazione errori
success: function(msg)
{
alert(msg);
},
error: function()
{
alert("Chiamata fallita, si prega di riprovare...");
}
});
}
my salva_doc_ajax.php:
<?php
if(isset($_POST['name']) && isset($_POST['html']) && isset($_POST['pubblicato'])){
$oggetto = $_POST['oggetto'];
$html = $_POST['html'];
$pubblicato = $_POST['pubblicato'];
$oggetto = addslashes(htmlentities($oggetto));
$html = addslashes(htmlentities($html));
echo "Oggetto: $oggetto";
echo "<br>HTML: $html";
echo "<br>Pubblicato: $pubblicato";
}else{
echo "Errore";
}
?>
I've tested that in 'htmlpure' and in 'oggetto' there is data...
everytime I run this js function I get "Errore" from the php page, like if I don't send $_POST variables...
I believe that in an ajax POST, your data should be an object. You are sending a query string for a GET request.
Also, as #Kaddath said, there is no name in your post.
See what you're getting by adding this line to the very top of salva_doc_ajax.php and comparing it to what you think you're getting:
die(print_r($_POST));

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.

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

I can't passing variable to PHP from JavaScript and jQuery load the response

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/>";
?>

Why Does My AJAX Response Contain HTML Source?

hope you're all doing well. Here's the deal. I make an AJAX call to PHP and PHP decodes the JSON string then echoes a property from the json object but in the AJAX response alert, I get the correct value from the json property AND the source of the current page, for example:
jsonProperty<!DOCTYPE HTML>
<html>
<head>... [the rest of the page's source]
Here is my code:
PHP
<?php
private function validate_review(){
$json = json_decode($_POST['data']);
echo $json->review;
}
?>
AJAX:
<script>
var reviewData = {
title : $('#fieldtitle').val(),
raiting : starRaiting,
review : $('#fieldreview').val()
}
$.ajax({
type: 'post',
url: 'http://localhost/codeigniter/new-review',
data: {data: JSON.stringify(reviewData)},
success: function(result){
alert(result);
}
});
</script>
Why would the response also include the source of the page, this is completely counter-intuitive and strange. Help?
Request:
specify your request dataType
$.ajax({
type: 'post',
url: 'http://localhost/codeigniter/new-review',
data: {data: JSON.stringify(reviewData)},
dataType: 'jsonp', //tell the server that you expect json
success: function(result){
alert(result);
}
});
Response:
<?php
//DO NOT echo any output before header
header('Content-Type: application/json'); //said this response content is json
?>
and die instead of echo json content
I think your code still includes the template.
private function validate_review(){
$json = json_decode($_POST['data']);
die($json->review);
}
This should work.

Categories