Ajax post doesn't work when passing variable to PHP - javascript

While reading other similar questions I've learned that to send a javascript value to PHP variable I need to use AJAX. That's what I've done so far:
function onCursorChanged(e, data) {
$.post('familytree.php', {id: data.context.id});
<?php
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
else {
$id = $individualid;
}
?>
}
The problem is that when I check if id is posted it always goes to else statement (id is always equal to individualid). However, when I change my code to this:
function onCursorChanged(e, data) {
$.post('familytree.php', {id: data.context.id,
success: function (msg){
alert('success') },
error: function (err){
alert(err.responseText)}
});
<?php
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
else {
$id = $individualid;
}
?>
}
EDIT: the code above is mixed incorrectly because of a lot of experimenting I've been doing. The original code:
<script type="text/javascript">
function onCursorChanged(e, data) {
$.post('familytree.php', {id: data.context.id});
}
</script>
<?php
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
else {
$id = $individualid;
}
$this->displayLeafEditForm ($_SESSION['username'], $id, $this->getParents($id));
Thanks to all the answers I realised that id is not set that's why I can't get the value in php. But I don'y understand why because data.context.id is the id of the item clicked and set after each click.
I get the message that says 'success'. Any idea why can't I get my variable posted?

The big problem here is that you mixing PHP and JavaScript incorrectly. You are expecting $_POST['id'] to be set in the JavaScript before it goes to the client. But by the time the JavaScript reaches the client, the PHP processing is already complete.
This means that when the $.post() happens, the server has already decided whether if (isset($_POST['id'])) is true. The server sends the output (the JavaScript) on to the client, and then no more PHP processing will happen.
Also, you are passing id, success, and error as data, which is almost certainly not what you want. You want this:
$.post('familytree.php',
{id: data.context.id},
success: function (msg){
alert('success')
},
error: function (err){
alert(err.responseText)
}
);

The AJAX success function cares whether the asynchronous call occurred without error. The fact that you even reached if (isset(...)) (and didn't set any error code eg. with header(...)) means that the AJAX call succeeded.
If isset is returning false, you need to look closer at the information that your AJAX call is actually sending to the PHP. Try putting in print_r($_POST) to see what post values you're actually getting.

Related

Send JS variable to PHP on another page without form

I have an html page with a search field that can have a name typed in which returns a table of Names and IDs (from Steam, specifically). The leftmost column, the names, are hyperlinks that I want to, when clicked, take the user to said player's profile (profile.php) and I want to send the "name" and "steamid" to that profile.php when the name link is clicked, so essentially sending two JS variables from one page to the PHP backend of another page.
I'm new to ajax and it seems that that is the only way to use it, so after researching for a while this is what I've come to:
$(document).ready(function() {
$('#playerList td').click(function(e) {
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function() {
console.log('success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});
Everything up to the ajax definition works as I want, and I want to send the "name" and "steamid" vars to profile.php, but I don't think I'm understanding how ajax works. My understanding is that ajax can "post" information (usually a json object from what I've seen) to a url, but can also return information from a page? That's where I'm a bit confused and am wondering if I'm just using it wrong.
As a quick note: playerList is my table's id.
When I click the hyperlink, it takes me to profile.php, which is what I want, but php's $_POST[] array seems to be empty/null as I get the "undefined array key" error when trying to access both 'playersSteamID' and 'playersName'. var_dump() returns NULL as well, so I'm wondering if there's a problem with the way the data{} field is being sent in the ajax. I'm still very new to this so any help would be much appreciated.
Update: How I'm accessing the variables in profile.php
<?php
echo var_dump($_POST['playersName']);
echo var_dump($_POST['playersSteamID']);
if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}
?>
The rest of profile.php is taking those variables and running several sql queries and building a table which work given proper variables, but since the $_POST[] is empty I can't continue past the above point as the first two lines return null and the conditionals are never true since isset() is false.
The ajax is used to, post or get parameters/info from/to URL without redirecting/refreshing/navigating to a particular page.
Please note down without redirecting/refreshing/navigating
In your case you want to send 2 parameters to profile.php and you also want to navigate to it, yes..? but for that you are using Ajax, which is not a right choice.
Solutions:-
-> Use normal form submission kinda thing, and post the parameters to profile.php, in this case you will get redirect to profile.php and can expect proper functionality.
You can use a normal form with a submit button {pretty normal}, or use a custom function to submit form with some further work if need to be done {form validation}.
you function would look like this...
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
//Do some other stuffs
document.forms['someform'].submit();//submitting the form here
}
});
});
The rest in profile.php remains same.
-> If you really wanna use ajax do following.
Ajax are meant for dynamic web designing, pretty useful to grab data from server without refreshing the page.
You should change the way your response is in profile.php file.
for eg:-
<?php
if(isset($_POST['playersSteamID'])){
$name = $_POST['playersName'];
$id = $_POST['playersSteamID'];
//Do your stuff here db query whatever
//Here echo out the needed html/json response.
echo "<h3>".$name."</h3>";
echo "<h4>".$playersSteamID."</h4>";
}
?>
The response {from: echo} will be available in data of function(data) in ajax success, you can use this data in whatever you want and however you want.
for eg:-
success: function(data){
console.log(data);//for debugging
$('#mydiv').html(data);//appending the response.
}
-> Use php sessions and store steamID in sesssion variable, very useful if you have some login functionality in your website.
$_SESSION['steamID'] = //the steamID here;
This variable can be used anywhere in site use by calling session_start() in the page, you want to use sessions.
for eg:-
click here to view your profile
profile.php
<?php
session_start();
$id = $_SESSION['steamID'];
//echo var_dump($_POST['playersName']);
//echo var_dump($_POST['playersSteamID']);
/*if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}*/
echo $id;
//Do your work here......
?>
For any queries comment down.
A hyperlink may be causing the page navigation, which you dont want.
Page navigation will make a get request but your endpoint is expecting a post request.
You can stop the navigation by setting the href to # or by removing the <a> altogether.
You could also try calling the preventDefault on the event object.
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function(data) {
console.log('success', data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});

Not clear on syntax of ajax post

I am new to php and javascript. I am trying to post some variables to another php file using ajax. From my main php file, I have a javascript setInterval calling a function to send data every 500ms. The function called is:
function UpdateDB(xval, yval) {
TimeCount++;
// console.log(xval, yval, TimeCount);
$.ajax({
type: "POST",
url: "ud.php",
data: { x: xval.toString(), y: yval.toString(), t: TimeCount.toString() }
});
return TimeCount;
}
This function runs fine as I get the console log data (if I uncomment). I can also see in developer tools (chrome) in the network, the file ud.php appears to be run, but I do not believe this is the case. ud.php is a simple file that updates data in a table:
//<script type="text/javascript">console.log("ud");</script>
<?php
if (!isset($_SESSION['id'])) {
exit();
}
//require "includes/dbh.inc.php";
$sql = "UPDATE units SET JoyX='$x', SET JoyY='$y', SET JoyTimeStamp='$t', WHERE SN='$serial'";
//$sql = "UPDATE units SET JoyTimeStamp='$t' WHERE SeralNumber='$serial'";
mysqli_query($conn, $sql);
mysqli_close($conn);
exit();
?>
I wrote the commented out line at the top to see if the file was run, but when uncommented it does not log to the console.
I suspect my ajax query is incorrectly formatted, but again I am new to this and have searched for the last few days to find an answer without success.
Thanks for any help.
The PHP file is successfully being invoked, you just have an invalid expectation of the result. Check the network tab in your browser's debugging tools. Are there any error codes in the request/response? Does the response contain the information you expect? If so then it's working.
The question is... What are you doing with that response?
The AJAX operation by itself doesn't do anything with the response. But it gives you an opportunity to do something with it. For example, in the jQuery .ajax() call you're using, there's a success callback which gets invoked on a successful result. So you can do something like this:
$.ajax({
type: "POST",
url: "ud.php",
data: { x: xval.toString(), y: yval.toString(), t: TimeCount.toString() },
success: function () {
console.log("ud");
}
});
So instead of trying to return new JavaScript from the server, you write the JavaScript here that you want to invoke when the operation successfully completes. (Alternatively you can use an error callback for a failed response.)
If you want to send data back from the server, anything you echo to the response would be available as the first argument to the success function. For example, if you do this on the server:
echo "ud";
Then in the success callback you can show that text:
success: function (result) {
console.log(result);
}

Uncaught TypeError Message using Javascript variable as argument for PHP function that initiates mySQL query

I spent most of my day yesterday trying to solve this puzzle so today I've decided to reach out for some help. Before I begin, let me state that I am very aware that JavaScript is client-side and PHP is server-side and I use Ajax successfully for various other things. In this case, I can't find any S/O references that are similar to what I'm trying to accomplish. I would've thought this was very basic but I'm missing something here and could use some direction. Thank you.
In essence, I have a Javascript function that produces a JavaScript variable and then calls a PHP function that initiates a mySQL query (all on the same page). If I "hard-code" the argument in my PHP function call (e.g., sc_bdls = <?php echo Candidates::getBDLs(1000033); ?>;), the function runs perfectly and I receive the expected outcome (an array).
However, if I try and use a JavaScript variable in place of the argument, I receive a "Uncaught TypeError: Cannot read property 'id' of undefined" error. I have tried several iterations without success and I suspect I am missing something basic. Here is my code:
function tab_pos3(row){
var sc_id = row.toString();
var sc_bdls = [];
$.ajax({
type: "POST",
url: '/phpscripts/pass.php',
data: {row : row},
success:(function(data){
console.log("success");
alert(data);
})
});
sc_bdls = <?php echo Candidates::getBDLs($uid); ?>;
}
Here is the code from the pass.php file:
if(isset($_POST['row']))
{
$uid = $_POST['row'];
echo $uid;
}
Please notice that the console.log("success") and the alert(data) both show that the Ajax POST is working. Any thoughts on what might be going wrong? Thank you.
1st EDIT (comment from Swati)
I tried moving the PHP function call as suggested and then used $UID, $data, data, among others, and I still get the exact same error. Here is the edited code:
$.ajax({
type: "POST",
url: '/phpscripts/pass.php', //
data: {row : row},
success:(function(data){
console.log("success");
alert(data);
<?php $row = $_POST['row'];?>; // I tried this based on something I read.
sc_bdls = <?php echo Candidates::getBDLs(data); ?>;
})
The fact that the error doesn't change is gnawing at me. Could the argument be passed but in a format that is not being read right? Is the "TypeError" referring to data type?
Try moving the
sc_bdls = <?php echo Candidates::getBDLs($uid); ?>; to pass.php and read the returned data in ajax success function.
Please note php is executed before the browser sees it. And JS code is called client side.
This is how your function will look like
$.ajax({
type: "POST",
url: '/phpscripts/pass.php', //
data: {row : row},
success:(function(response){
console.log("success");
sc_bdls=response; // Just to show that response has the value you need.
alert(sc_bdls);
})
The pass.php will look like this
// I prefer using !empty here (unless you are expecting 0 as a valid input.
// This ensure $uid isset and is not empty.
// Also if $uid is supposed to be numeric you may want to add a validation here.
if(isset($_POST['row']))
{
$uid = $_POST['row'];
$response_array = Candidates::getBDLs($uid); //Your question says you are expecting an array
echo json_encode($response_array);
}

Setting session properly in zend controller action on AJAX call

I have an ajax call like following:
$.post("/user/signindo",{'username':username,"password":password},function(data){
//doing something with the response
// Now I need to access the session variable
<?=echo("$_Session['id']")?>
}
and the action in the controller looks like this
public function signindo()
{
$_Session['id'] = 1; // this value is assigned dynamically when the user logs in
// example of setting session to 1
}
The weird thing is that, once the user signs in, the value is assigned with the correct id... Next time I login with the different user, the ID remains the same from the previous user... Next time when I login with the 3rd user, I get the ID of the 2nd user... If you guys understand me what I'm trying to say? What am I doing wrong here?? How to fix this ?
Try this
public function signindo()
{
$namespace = new Zend_Session_Namespace();
$namespace->id = 1;
echo $namespace->id;
exit;
}
Client side:
$.post("/user/signindo",{'username':username,"password":password},function(data){
//data will be your session id
}
Read the below link for more details about Zend session
http://framework.zend.com/manual/1.12/en/zend.session.basic_usage.html
I will go with EagleEye
You will get session value in data, but you can use $.post jquery call..
<script>
$.post("/user/signindo",{username:username,password:password},function(data){
//case1 - output
//console.log(data);//1
//case2 - output
console.log(data);//{id:1,name:joe}
console.log(data.id);//1
console.log(data.name);//joe
}
</script>
In signin I dont know how session works in zend but in corePHP it goes as shown below..
<?php
public function signindo()
{
//case 1
//session_start();
//$_SESSION['id'] = 1; //Not in small $_Session
//echo $_SESSION['id'];
//case 2
$test_array = array('id'=>1,'name'=>'joe');
echo json_encode($test_array);
exit;
}
Maybe it's due the fact that $.post is asynchronous, and the javascript function is called before the session is set, hence the old id.
When you use $.ajax it should work.
$.ajax({
url: '/user/signindo',
data: {'username':username,"password":password},
async: false,
success: function(data) {
// maybe do something with data
}
});
You could also return the id in the PHP function and and access it through the data variable.

PHP/HTML/JavaScript: <script> not working when called asynchronously using echo

The innerHTML attribute of a div on my webpage is updated asynchronously (XMLHttpRequest) by getting PHP from the server: but it doesn't seem to call javascript.
This works absolutely fine:
<div id="mydiv"><script>alert('hello');</script></div>
And this works absolutely fine (updating inner HTML of that same div):
echo "<p>Hello</p>";
But this does not work:
echo "<script>alert('hello');</script>";
And I have no idea why! I have tried this in multiple documents, and my searching online seems to suggest it should work.
This is only a problem that occurs when the content is asynchronous. The following works perfectly:
<html>
<body>
<?php
echo "<script>alert('hello');</script>";
?>
</body>
</html>
I can easily design around this, but is it impossible to execute javascript code in this way? As far as I can see, this page suggests work-arounds but doesn't say explicitly that it's impossible: executing javascript in PHP through echo, via ajax.
Thank you!
What you are doing is echoing the script tags into the body of the html, but nothing is asking them the javascript to run. Either way, this is the wrong way to go about this.
You should just execute whatever javascript you want from the success function of your ajax request.
Usually I would pass a JSON object back from my PHP to the success handler, which would JSON.parse it and then do what you wanted with the return data, but you could also use Javascripts eval() although, this is discouraged in most cases due to security reasons.
Not using eval();
Javascript;
$.ajax({
url: "path/to/php.php",
type:'POST',
data: {
data: 'someString'
},
success: function(json){
var obj = JSON.parse(json);
if(obj) {
// run some javascript
}
},
});
PHP file (path/to/php.php);
<?php
// create return object to pass back to client javascript
$return = new stdClass();
// if you have incoming data from the ajax request to the server
$dataFromAjaxRequest = $_POST['data'];
// do somehting with this data;
if($dataFromAjaxRequest == "someString") {
$return->success = true;
} else {
$return->success = false;
}
// clean the buffer
ob_clean();
// encode your return obj to JSON and echo it and die
die(json_encode($return));
?>
Using eval to execute pure php generated Javascript;
Javascript;
$.ajax({
url: "path/to/php.php",
type:'POST',
data: {
data: 'someString'
},
success: function(javascript){
eval(javascript);
},
});
PHP file (path/to/php.php);
<?php
// if you have incoming data from the ajax request to the server
$dataFromAjaxRequest = $_POST['data'];
// do somehting with this data;
if($dataFromAjaxRequest == "someString") {
$return = "alert('success!');";
} else {
$return = "alert('failure!');";
}
// clean the buffer
ob_clean();
// encode your return obj to JSON and echo it and die
die($return);
?>
Hope this will work
<html>
<body>
<script>eval(<?php echo 'alert('hello')';?>);
</script>
</body>
</html>
For better cross-browser compatibility and less verbosity I'd suggest jQuery.
$.get('http://example.com', function(responseText) {
alert(responseText);
});

Categories

Resources