Ajax posting NAN value - javascript

I'm posting a variable via ajax however when I use it in PHP, I get NAN why is that? it's supposed to be a number
//in js
var variableToSend = 1;
$.post('ajax.php', {variable: variableToSend});
//in php
<?php echo $_POST['variable']?>;

This code won't work,
Because AJAX is something that works in the background, So there is no way the "echo " in PHP will display the data, Because the data returns back to the success:function and then that can be consoled or printed on the HTML
Here is an example code of how it works:
var variableToSend = 1;
$.ajax({
url:"ajax.php",
method:"POST",
data: {
variable:variableToSend
},
success:function(data){
console.log(data);
}
})
Hope you understood how AJAX works

Related

$_POST empty in post Ajax Request

I tried to check the solution in the other similar post on the forum, but I did not resolve my problem yet.
So, I have this Ajax Request in my .js page
JS Code
$(document).ready(function(){
$(document).on('click', '.mySubmitTextButton', function() {
var dataToSend = {};
dataToSend.text = $("#comment").val();
console.log(dataToSend);
$.ajax({
type: "POST",
url: "../submitPages/submitText.php",
data: dataToSend,
dataType: "json",
success: function(result){
console.log(result);
var mediaToClone = $(".rowToCopy").clone();
$(".userId", mediaToClone).html(result.user);
$(".textTweet", mediaToClone).html(result.text);
$(".userAvatar", mediaToClone).attr("src",result.avatar);
mediaToClone.removeClass("rowToCopy hidden");
mediaToClone.appendTo($(".tweetBox"));
},
error: function(result){
console.log(result);
}
});
});
});
PHP Code
if (!isset($_SESSION)) { session_start(); }
include ("../db/db.php");
var_dump($_POST);
if(submitText($_POST["text"], $_SESSION["name"])){ //which is the call to the query function
$propic = getUserPic($_SESSION["name"]);
$result = array(
"text" => $_POST["text"],
"user" => $_SESSION["username"],
"avatar"=>$propic
);
echo json_encode($result);
}
FROM THE BROWSER
Form Data
text: test //This is the Params Tab
//In the response tab
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=1)</i>
'text' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'ccccccccc'</font> <i>(length=9)</i>
</pre>{"text":"ccccccccc","user":"blackout_chisel","avatar":"..\/..\/img\/useravatar\/0826fc411cd2dc627ddd0b0cac0f7fb7.jpg"}
The datas seem to be correctly passed from the js to php (in the browser console I see the parameters correctly passed), but with var_dump($_POST) in the php file, I get an empty array, so I can't use $_POST["text"] in the query case the index is undefined.
Any ideas?
Ok guys, thanks all, I had a misunderstood on it. It works perfectly. I was trying to see the result var_dump($_POST), when the ajax call was already done. That's why it was obviously empty.

Not receiving data from ajax to php

I want to send data from javascript to another php page where I want to display it. I found that I need to use Ajax to pass the data to php so I tried myself.
My file where is the javascript:
$('#button').on('click', function () {
$.jstree.reference('#albero').select_all();
var selectedElmsIds = [];
var selectedElmsIds = $('#albero').jstree("get_selected", true);
var i = 0;
$.each(selectedElmsIds, function() {
var nomenodo = $('#albero').jstree('get_selected', true)[i].text;
//var idnodo = selectedElmsIds.push(this.id);
var livellonodo = $('#albero').jstree('get_selected', true)[i].parents.length;
//console.log("ID nodo: " + selectedElmsIds.push(this.id) + " Nome nodo: " + $('#albero').jstree('get_selected', true)[i].text);
//console.log("Livello: " + $('#albero').jstree('get_selected', true)[i].parents.length);
i++;
$.ajax({
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo
},
success: function(data)
{
$("#content").html(data);
}
});
});
});
I want to send the data to another php page which consists of:
<?php echo $_POST["namenodo"]; ?>
But when I try to go to the page there's no data displayed.
This is a very basic mistake I think every beginner (including me) does while posting a data using ajax to another php page.
Your ajax code is actually posting the data to lamiadownline.php (if you are using the variables correctly) but you can't get that data by simply using echo.
Ajax post method post data to your php page (lamiadownline.php) but when you want to echo the same data on the receiver page (lamiadownline.php), you are actually reloading the lamiadownline.php page again which makes the $_POST["namenodo"] value null.
Hope this will help.
First of all you won't be able to see what you have post by browsing to that page.
Secondly, is this
<?php echo $_POST["namenodo"]; ?>
in the current page?
Otherwise, specify the url
$.ajax({
url: "lamiadownline.php",
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo},
success: function(data) {
$("#content").html(data);
}
});
//try this
$.ajax({
type: "POST",
url:"Your_php_page.php"
data: { namenodo: nomenodo levelnodo: livellonodo},
success: function(data)
{
$("#content").html(data);
}
});

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.

Error by passing variable from JS to PHP

I know this question was already answered one million times but I'm becoming desperate with this code.
I have two files php files and I want to send a variable from a part written in JS to the other PHP file. So here's the code:
carga_datos.php
<script>
function MyAlert() {
var radio1 = $("input[name='inputTipoActividad']:checked").val();
$.ajax({
url : 'post.php',
type : "POST",
data: {'radio1' : radio1},
dataType:'json',
success : function(data) {
alert(data);
},
});
}
</script>
I'm calling to MyAlert() in a radio button form
post.php
<?php
$radio1 = $_POST['radio1'];
echo $radio1;
?>
And I call post.php into carga_datos.php like this:
And this is the error I'm retrieving:
Notice: > Undefined index: radio1 in C:\xampp\htdocs\gis\post.php on line 2
Edit:
It seems you have used dataType "json" so it will expect a "json", if none is returned you will get undefined or an empty response.
If you remove dataType: "json" you should be able to retrieve the data just fine.
function MyAlert() {
var radio1 = $("input[name='inputTipoActividad']:checked").val();
$.ajax({
url : 'post.php',
method : "POST",
data: {"radio1" : radio1},
success : function(data) {
console.log(data);
}
});
}
If you want to check with "dataType: 'json'" still in your code, you need to return your PHP code like the following:
<?php echo json_encode($_POST); ?>
This will then either return your $_POST data or just an empty [] array.
// Old Answer for just true/false values
If you just want to see if the checkbox was checked or not to retrieve a boolean, please try the following:
var radio1 = $("input[name='inputTipoActividad']").prop("checked");
This will return TRUE or FALSE. If not wrong, if you use
$("input[name='inputTipoActividad']:checked").val()
it'll return "on" or nothing (might be wrong here though).
Tested it with the ".prop("checked")" and it worked for me.

AJAX call returns undefined in Header / form-data

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.

Categories