Error by passing variable from JS to PHP - javascript

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.

Related

Ajax calling PHP and getting Return value

Not used Javascript -> Ajax -> PHP -> Javascript before and I am struggling to pick-up the return value. Ajax is calling the PHP, but all I am getting back is the HTML for the web page. Can anyone see what I am doing wrong?
Javascript: -
onChange: function(value, text, $selectedItem) {
jQuery.ajax({ url : 'index.php', type : 'post', data : { action: 'getTest', param : text },
success: function(result){
console.log('Sucess',result);
},
failure: function(result){ console.log('Failed'); }
});
}
PHP: -
$_action = isset($_Post['action']) ? $_Post['action'] : '0';
if ($_action == 'getTest') {
$test = $_Post['param'];
echo $test;
exit;
}
As I said, RESULT just seems to contain the page's HTML and not the expected string value.
Thanks
Your post variable is with small caps letters. However the Variable should be full caps ($_POST). So your php is not going into the if statement.
https://www.php.net/manual/en/reserved.variables.post.php
To debug these kind of issues start logging variables like $_action and check if their value is what you expect it to be. Then check if the if statement actually fires, etc. until you find the error.

$_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.

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

using returned json values in calls not working

Trying to use the values I return from my php yet there are not working properly.
<script type="text/javascript">
$(function () {
$('#delete').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
if (response.success == 'success') {
// fade out the deleted comp
$("#c"+response.computer_id+"").fadeOut("slow");
// remove from the drop down
$("#comp_selection option[value='#c"+response.computer_id+"']").remove();
} else {
alert('Some error occurred.');
}
});
});
});
</script>
I am returning from the php file :
echo json_encode($ajax_result);
which is returning :
{"computer_id":1,"success":"success"}
EDIT: I found a small error in code outside of this where I was returning a different value than expected. All is well and the above was indeed correct to start with.
You should debug using firebug or whatever developer tools you have in your browser - firebug in Firefox is very good for this as you can see the JSON data passed back from the AJAX call.
That said, your issue is that the data is probably under response.d - so look at response.d.success and response.d.computer_id
Maybe the content you are receiving from your PHP server is sent as simple text, and must be sent with the headers set for JSON content:
header('Content-Type: application/json');

Cant concatinate a javascript variable inside an ajax which is inside another ajax

I'm not sure how to ask this question but I'll just describe my problem:
I have this variable:
var htmlvalues = '';
then I have an ajax code:
#for loop here
$.ajax({
url : 'dasdasdas',
...
....
....
success : function (data) {
#now this is my problem here:
$.ajax({
url : 'dasdsa',
........
.............
success : function (data again) {
htmlvalues += 'some html values to concatinate';
}
});
});
#end of for loop here
So after that loop ends I want to display that html values:
$(".tech-file-upload-dialog").html( htmlvalues );
In a dialog box like above. But it will just display an empty dialog box, I suspect It cant get those values inside the deeper part of ajax. I can see through console.log that my data are being concatinated successfully, it just can't reach the dialog box part.
Use async:false, so your code might look like.
var htmlvalues = '';
#for loop here
$.ajax({
async: "false",
url : 'dasdasdas',
...
....
....
success : function (data) {
#now this is my problem here:
$.ajax({
async: "false",
url : 'dasdsa',
........
.............
success : function (data again) {
htmlvalues += 'some html values to concatinate';
}
});
});
#end of for loop here
$(".tech-file-upload-dialog").html( htmlvalues );
Define your function as
...
success: function(data) {
//do something
}
This way the function will get the response from the server parsed according to dataType you define in the call so you will have access to the data you need.

Categories