Session variables is not getting printed - javascript

I have a PHP backend script where I am creating a PHP Session variable:
if(!isset($_SESSION))
session_start();
if(isset($_SESSION['uid']))
unset($_SESSION['uid']);
$_SESSION['uid']=$this->_out;
In my HTML Script I am using the following way to access it:
editor = new $.fn.dataTable.Editor( {
ajax: {url:"euseradd.php",complete : function(){var uid='<?php if(!isset($_SESSION)) session_start();if(isset($_SESSION["uid"])){echo $_SESSION["uid"];unset($_SESSION["uid"]);}?>';alert(uid)}},
......................
} );
But I am not getting the value - my alert prints empty value. However when I try to echo the session variable output in WAMP server Apache logs by below way:
echo 'Value is ' . $_SESSION['uid']
I get an error that 'Notice: Array to string conversion' - my intention is to log the value in some logs to see whats the value backend is also assigning.
EDIT:
I modified the echo statement by below way:
echo 'Hello ' . serialize($this->_out);
And Now I get the data at browser side like:
Hello a:5:{s:2:"id";i:-1;s:11:"fieldErrors";a:0:{}s:5:"error";s:0:"";s:4:"data";a:0:{}s:3:"row";a:11:{s:8:"DT_RowId";s:7:"row_135";s:2:"id";s:3:"135";s:9:"last_name";s:6:"sdfdsf";s:10:"first_name";s:3:"dsf";s:8:"homeaddr";s:21:"sdfdsfsdfdsfdsfdsfdsf";s:5:"email";s:8:"s#jj.com";s:10:"officeaddr";s:24:"wwwwwwwwwwwwwwwwwwwwwwww";s:6:"mobile";s:8:"11111111";s:3:"age";s:2:"11";s:9:"chargeamt";s:2:"11";s:10:"start_date";s:10:"11/11/2011";}}{"row":{"DT_RowId":"row_135","id":"135","last_name":"sdfdsf","first_name":"dsf","homeaddr":"sdfdsfsdfdsfdsfdsfdsf","email":"s#jj.com","officeaddr":"wwwwwwwwwwwwwwwwwwwwwwww","mobile":"11111111","age":"11","chargeamt":"11","start_date":"11\/11\/2011"}}
I am in need to extract the value "id":"135" from it.
Actually I cannot use success function for my operation due to some constraint. And cause I am fixing an issue I am writing the code for the issue that I have
EDIT:
I tried printing the values like below:
echo 'Hello ' . serialize($this->_out['row']['DT_RowId']);
I get the below output at console logs:
Hello s:7:"row_140";{"row":{"DT_RowId":"row_140","id":"140","last_name":"sdfdsf","first_name":"dsf","homeaddr":"sdfdsfsdfdsfdsfdsfdsf","email":"s#jj.com","officeaddr":"wwwwwwwwwwwwwwwwwwwwwwww","mobile":"11111111","age":"11","chargeamt":"11","start_date":"11\/11\/2011"}}
I am not sure what structure of the output is - but how can I extract "id":"140" from above. I just guess that "row_140" is not a constant name but rather row_# record number
EDIT:
Below is the output of echo print_r($this->_out); as requested:
Array
(
[id] => -1
[fieldErrors] => Array
(
)
[error] =>
[data] => Array
(
)
[row] => Array
(
[DT_RowId] => row_157
[id] => 157
[last_name] => sdfdsf
[first_name] => dsf
[homeaddr] => sdfdsfsdfdsfdsfdsfdsf
[email] => s#jj.com
[officeaddr] => wwwwwwwwwwwwwwwwwwwwwwww
[mobile] => 11111111
[age] => 11
[chargeamt] => 11
[start_date] => 11/11/2011
)
)
1{"row":{"DT_RowId":"row_157","id":"157","last_name":"sdfdsf","first_name":"dsf","homeaddr":"sdfdsfsdfdsfdsfdsfdsf","email":"s#jj.com","officeaddr":"wwwwwwwwwwwwwwwwwwwwwwww","mobile":"11111111","age":"11","chargeamt":"11","start_date":"11\/11\/2011"}}

Am not really sure whether I understood your issue. But session_start() is supposed to be called at the very beginning of the page in your php script. That is, before printing anything. Because the session headers should be sent to the browser.
When you preform the ajax, don't mix up with the PHP. Send the user details to the PHP script via ajax. Then make the php script return the user id back as the response and then you can use it in your javascript. The page that you get on your browser is actually as an output of the PHP script. I mean, all PHP code in your PHP script would be executed and the output is what you are getting on your browser. So, when your page is executed(accessed from browser), that var uid = ''; in your javascript will already be having a result of the PHP script. It won't get updated after that AJAX call!
And for the array error, I believe you are assigning an array to the $_SESSION['uid']. I think it would be better if you just store the value(ie. the user id) as int or string there in that session instead of array!

You cannot access php variables from jquery like that
There is a much simpler solution to your problem just echo $_SESSION['uid'] to your jquery callback function and access it using jquery some what like this
useradd.php
if(!isset($_SESSION))
session_start();
if(isset($_SESSION['uid']))
echo $_SESSION['uid'];
unset($_SESSION['uid']);
Jquery
$.ajax({
url : "euseradd.php",
cache: false,
success: function(responseText){
alert(responseText); //this should contain your session uid
}
}); //end of ajax call
return false;

Related

Trying to pass my WordPress database result to JavaScript and then back through PHP

At start of page load I get all my products (posts) with a database query and print the first results on the page like this:
$posts_from_query = $wpdb->get_results($SQL, ARRAY_A);
$output = $CORE->create_output($posts_from_query, 1);
<div id="currentPageSearchResults"><?php echo $output ; ?></div>
Then I send it to a JS init function when the page is fully loaded:
initSearchJavascript(<?php echo json_encode($posts_from_query);?>);
And here is a simplified version of the JS file:
var postsFromCurrentQuery;
function initSearchJavascript(postsFromQueryInit){
postsFromCurrentQuery = postsFromQueryInit;
}
When alerting postsFromCurrentQuery I get [object Object],[object Object],... 258 times since I have 258 products, all good so far.
Now when I click on page 2 (I show 50 products per page) I call a JS function that through an AJAX call sends postsFromCurrentQuery back to PHP to create the output for page 2:
jQuery.ajax({
type: "POST",
url: ajax_site_url,
dataType: 'json',
data: {
action: "change_search_page",
clickedPage: currentPage,
postsFromCurrentQuery: postsFromCurrentQuery,
},
});
And on the PHP side I unpack it like this:
case "change_search_page": {
// Unpack variables
$postsFromCurrentQuery = $_POST['postsFromCurrentQuery'];
$clickedPage = $_POST['clickedPage'];
// Retrieve output
$output = $CORE->create_output($postsFromCurrentQuery, $clickedPage);
// Send back to JS for printing on page
header('Content-type: application/json; charset=utf-8');
die(json_encode(array(
"status" => "ok",
"output" => $output,
"count" => count($postsFromCurrentQuery),
)));
} break;
Problem
When I print the length of postsFromCurrentQuery before the AJAX call it is 258 as expected. But when I print it after (or in the PHP) it instead says 231. For some reason information is lost when sending from JS to PHP via AJAX.
What I tried
I can see that some information on the last (231th) product is missing and some is not. It shows the correct title, image etc but then fails on location which comes later in the string. This makes me think that there is some limit to how much data can be sent over AJAX? It has been working fine when I had 20 products or so.
I also tried to make it into a string with JSON.stringify before sending it over AJAX and then json_decode on the PHP side. This fails however for some reason. It seems like I have a JSON structure with nested {} which makes it fail, since it works if I remove the attribute with the extra {}.
Questions
Is there a limit to how much data AJAX can handle?
If not, why is my approach failing?

What is wrong with the way I am handling these variables in PHP?

Originally I wanted to use node.js, but after an entire day of frustration, I switched to using jquery and mySQL. The logins seem to be working, but something is wrong in the way it is handling variables. All I want to do is update the database with two things: score and name. Here is the code I modded for my project in PHP:
<?php
$db = "myDatabaseNameIsCorrect";//Your database name
$dbu = "soIsMyUsername";//Your database username
$dbp = "AndMyPassword";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
if(isset($_GET['name']) && isset($_GET['this.score'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$name = strip_tags(mysql_real_escape_string($_GET['name']));
$score = strip_tags(mysql_real_escape_string($_GET['this.score']));
$sql = mysql_query("INSERT INTO `$db`.`scores` (`id`,`name`,`score`) VALUES ('','$name','$score');");
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your score was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your score. Please try again later.';
}
}else{
echo 'Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
And here is the JS! that runs the PHP:
let gameoverScene = new Phaser.Scene('GameOver');
gameoverScene.create = function(){
this.laughSound=this.sound.add('laughSound')
this.gameW = this.sys.game.config.width;
this.gameH = this.sys.game.config.height;
this.goToTitle=function(){
var name = prompt('Enter your name');
jQuery.ajax({
type: "POST",
url: 'savescores.php?name=' +name +'&score=' + this.score,
dataType: 'text',
data: {functionname: 'add', arguments: [name, this.score]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
this.scene.start('Title')
};
I also tried changing the data type and that didn't work, but I'm not ruling it out yet as a problem.
Here are links to the project and the database:
www.igglepud.com/DeerDefender/Testing
www.igglepud.com/DeerDefender/Testing/getscores.php
This is the error I get:
gameover.js:20 Uncaught TypeError: Cannot use 'in' operator to search for 'error' in
Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.
at Object.success (gameover.js:20)
at fire (jquery.js:3268)
at Object.fireWith [as resolveWith] (jquery.js:3398)
at done (jquery.js:9305)
at XMLHttpRequest.<anonymous> (jquery.js:9548)
So, the error you're getting is because, in the JavaScript, obj (or the parameter in obj's position) is a string, not an array.
You can see some examples here of how you can properly check for and catch errors.
Edit:
So, in regards to your question about the score variable.
It's important to note that there are 2 types of variables at play here.
The first one is PHP GET variables. PHP GET variables are set via the following format:
var=value
You can set these variables by calling a PHP script like this:
script.php?var1=value1&var2=value2&var3=value3 // etc...
You can access them like this:
echo $_GET["var1"];
echo $_GET["var2"];
echo $_GET["var3"];
Which produces the result:
value1
value2
value3
The second variable at play is a JavaScript variable. Those can only be accessed in JavaScript. a JavaScript variable means nothing in PHP.
So, let's examine what you're doing from the JavaScript:
url: 'savescores.php?name=' +name +'&score=' + this.score,
For the purpose of explaining let's say name = Chipster, and this.score = 123.
What this code will do is try to open the following file:
savescores.php?name=Chipster&score=123
Remembering that PHP GET variables are set by the format script.php?var1=value1&var2=value2&var3=value3 // etc... we can see that there are 2 GET variables available from the PHP script called name and score. Thus, to access score from PHP you need to do it like this:
echo $_GET["score"];
This will output 123 in our example.
This may not solve your problem, but one issue I see with your code is calling strip_tags (or another function that alters the string) after it has already been quoted for insertion with mysql_real_escape_string may defeat the purpose of mysql_real_escape_string. It should be the very last function called on data before it's inserted.
Also, if score is an integer string, intval serves just as well as mysql_real_escape_string for sanitizing integers for insertion.
EDIT: You're also checking for GET variables in the PHP when the submission method used in the jQuery is POST. Try looking at $_POST instead of $_GET on the PHP side. You don't need to put variables in a query string if you're putting them in the request body via POST either.

post request in javascript with multilevel object

I am going CRAZY posting a json request to a php webservice file when the object I am trying to send is multi-level. ie:
postdata = {
name:"francesco"
, age:58
, address : {
street:"my Street"
, number: 42
, city:"London"
}
}
I have tried every example on the web, but, when I read the $_POST data on the php webservice two things happen:
if I use JSON.stringify I dont get anything on $_POST or $_GET depending what method I use, and I have to read the file_get_contents('php://input') and then json_decode it (whereas calling the webservce from php I get the info tidily in my $_GET or $_POST globals),
If I use other methods I have found, I get the name and age fine, but the address comes through as "[object object]" .
My question is, is it possible, WITHOUT USING jquery, to :
- create an object in javascript (multilevel or however the right term)
- use the "XMLHttpRequest()" object to post it to the php ws?
- read it from php using the $_GET or $_POST globals (depending on method used)?
I have been going crazy for over 96 hours now!!!
Thanks!
Francesco
So many incorrect answers here.
To POST a nested object to your PHP script you can use plain js:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://yourwebsite.com/yourscript.php");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send({"data":postData});
To read the info server-side
$postData = $_POST['data'];
When I looked to see what PHP had actually given me with error_log(print_r($_POST['test'], true)) I got
Array
(
[name] => francesco
[age] => 58
[address] => Array
(
[street] => my Street
[number] => 42
[city] => London
)
)
It's all there.
Question #1
is it possible to create an object in javascript (multilevel or however the right term)
This is how you create an object in javascript:
var o = {
foo: "bar"
};
Question #2
is it possible to use the "XMLHttpRequest()" object to post it to the php ws?
It's not hard to find it on the web: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
The code would be something like:
var oReq = new XMLHttpRequest();
oReq.open("POST", "http://www.example.org/target");
oReq.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
oReq.send(JSON.stringify(postdata));
Question #3
is it possible to read it from php using the $_GET or $_POST globals (depending on method used)?
No, you can't. As the docs say, $_POST is:
An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.
So the $_POST is usable only if you're passing form encoded data. Since you're passing a JSON, you're supposed to parse the request body by yourself.
From what I understand, it is not possible to post data to php from jscipt unless it's a form. but I can do this:
if ($_POST != null)
$req = $_POST;
else {
$json = file_get_contents('php://input');
$req = json_decode($json, true);
}
.. and then just read the $req ..
Is this VERY dirty or commonplace??

Strange behaviour sending data with PHP JSON encode to jQuery getJSON

I am sending data from PHP to jQuery. Everything works fine except I want to sent the total rows from the DB.
I have stripped a lot of other things to put onlu the essential problem.
PHP code:
header('Content-type: text/json');
header('Content-type: application/json');
$rows = array with the data; That is working fine
$total=mysql_num_rows($RSList);
$total_data=array("total"=>$total);
array_push($data,$total_data,$rows);
echo json_encode($data);
jQuery code:
$.getJSON("..url..", function( data ) {
var data_array = eval(data);
$.each(data_array[0], function(i, item ) {
console.log(item)
});
});
The result showing in the browser is:
[{"total":532},[{"product_id":"1",.... }]]
532 is the correct value from the mysql_num_rows()
Console:
An empty string
I tried the following:
If I set the value manually of total in PHP:
$total=100;
The result showing in the browser is:
[{"total":100},[{"product_id":"1",.... }]]
Console of java:
100
If I convert the value in string in PHP:
$total="(".$totalRows_RSList.")";
The result showing in the browser is:
[{"total":"(532)"},[{"product_id":"1",.... }]]
Console:
()
I have also tried intval, number_format and strval with no success.
Very, very strange or ?
Update:
I have modified as suggested the code and still the same problem:
PHP:
echo json_encode(array('total' => $total, 'rows' => $rows));
javscript:
$.getJSON( "..url..", function( data ) {
console.log( data )
$.each( data.rows, function(i, item ) {...}
})
Browser:
{"total":532,"rows":[{"product_id":"567",...}]}
Console:
Object { rows=[99], total=""}
You don't need to pass the total rows, just get the length of the parsed JSON object.
jQuery code:
$.getJSON('...url...', function(data){
console.log(data.length);
}
PHP Code:
header('Content-type: text/json');
header('Content-type: application/json');
$rows = array_with_the_data; //That is working fine
echo json_encode($rows);
Note: This answer explains what is wrong with your code. Learn from it, then look at #ojovirtual's answer which shows what I think is the best way for you to accomplish what you were intending to do in the first place. End Note
Remove the eval statement from your code. jQuery will have already parsed the incoming JSON (if it is valid) and your success function will receive your array as the data param. Just use that data param instead of data_array.
$.getJSON('..url..', function (data) {
// if your PHP is sending proper JSON in the format you describe, `data` is now
// an array containing two items. The first (`data[0]`) is an object which has
// one property, `total`. The second (`data[1]`) is your array of row data, each
// of which is an object.
// your code in modified form, though I don't understand why you would use `each`
$.each(data[0], function (i, item) {
console.log(item);
});
// just use:
console.log(data[0].total);
});
Be sure to read the comments in the above code.

jQuery Fails To Read JSON Response From PHP Script

In my form, I want to do something with two fields:
"website_domain" and "website_ip_address"
I'm trying to use jQuery/JSON to call a PHP script, pass the website_domain to it, and receive JSON including the IP address of that website.
Problem/Symptoms Description:
It's partially working: On blur, it GETs the url of the PHP script. I can see that much in firebug. I get a 200 OK. Output from the PHP script is valid JSON according to JSONLint:
{"field":"website_ip_address","value":"74.125.225.70"}
But in Firebug, I don't have a JSON tab. I only have Params and Headers tabs. Not even a Response tab.
Needless to say, the website_ip_address field is also not being populated with the data I should be getting from the PHP script's JSON output.
My PHP Script:
It may be important to note that for now, this PHP script on a different domain from my application. Maybe my whole problem is cross-domain?
<?php
$domain = $_GET["domain_name"];
$ip = gethostbyname($domain);
// echo $ip;
$json = array(
'field' => 'website_ip_address',
'value' => $ip,
);
header('Content-Type: text/plain');
echo json_encode($json );
?>
My jQuery/JSON script:
Note this is written inside a Ruby On Rails application view.
:javascript
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name=" +$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
I really hope this isn't just a syntax error on my part. I've been writing/rewriting this for 2 days, based on answers I've found on StackOverflow, to no avail. I'm just missing something here.
You are currently attempting to output the JS object (that is formed from the parsed JSON response) to the field. You need to output a value from within it. So not:
$('#website_ip_address').val(data); //data is an object, not a string
but
$('#website_ip_address').val(data.someValue); //output a property of the object
With your code as it is, I would expect the field to be populated with the string representation of an object, which is [object Object]. You don't mention this, so I wonder whether a) your success function is even firing (check this - stick a console.log in it); b) your jQ selector is sound.
The problem can be with different domain. I had it like this before. Try in php to add header("Access-Control-Allow-Origin: *")
Put your jQuery code inside document ready, example: $(function(){ });
:javascript
$(function() {
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name="+$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
});
});
And you have a missing end })

Categories