How to access php session data inside template files jquery code - php

I have ajax that calls a php file called "fetch_quarter_limit.php" from template file.
$.ajax({
type: 'POST',
url: 'fetch_quarter_limit.php',
data: {
leavefrom: from,
leaveto: to,
empid: emp
},
success: function(data) {
var quarter_limit = data['myVar'];
alert(quarter_limit);
}
});
In my .php file i have tried to return the session data as an array.
Fetched the required data, stored in session and formed an array.
$_SESSION['quarter_limit_mend'] = $quarterLimit;
$returnVal = array('myVar' => $_SESSION['quarter_limit_mend']);
echo $returnVal;
As shown in above ajax code part, i tried to fetch it, but all i am getting is "undefined" when i output the variable using alert.
Please help.
Ajax code updated, p2 :
Adding dataType is making code not to work.
$.ajax({
type: 'POST',
url: 'fetch_quarter_limit.php',
dataType: 'json',
data: {
leavefrom: from,
leaveto: to,
empid: emp
},
success: function(data) {
alert(data);
}
});
As #Tim mentioned i have added custom json encode function to my .php file.
It returns as expected {"myVar": 2}
echo array_to_json($returnVal);
This is returned from php file.
But not able to access in ajax code.

You're using echo on an array, which is not possible. As described in the PHP manual
echo outputs one or more strings.
Usually you'd use json_encode() on your array and then output it to the screen. But as you've commented you are using php < 5. First of all, if possible, you should consider to upgrade to PHP > 7, as this not only improves performance, it also improves security.
If you can't upgrade to a PHP version above PHP 5, then you can use workarounds. On this question there is already an answer for the workaround, and the workaround can be found on the PHP manual itself.
You should be able to use the returned JSON data.

Reply for after your edit
So you have your data as JSON now, but JS will still see it as a string. In your success function you still have to parse it.
success: function(data) {
jsonData = JSON.parse(data);
alert(jsonData.myVar);
}
I do have to add too that it is very insecure to continue using php < 7.3 (as of today, 24-02-2021)

Related

ajax always going to error

Im trying to learn to use ajax at the moment, but unfortunately I cannot get it to success.
$('.engineering-services').live('click', function() {
$.ajax({
url: 'index.php?route=information/information/homepage_info',
type: 'post',
data: {info_description : 'test'},
dataType: 'json',
success: function(json){
alert('pass');
},
error: function(json) {
alert('fail');
}
});
});
Here is the php function...
public function homepage_info() {
$json = array();
if (isset($this->request->post['info_description'])) {
echo $this->request->post['info_description'];
echo '<br /> test2';
}
$this->response->setOutput(json_encode($json));
}
However this always makes a fail alert instead of a pass one.
Am I missing something obvious here?
EDIT: Its finding the function ok, as in the console it is giving the correct response,
i.e.
test
test2
Thank you
If your dataType is set to json, anything returned that is not JSON will cause the ajax call to error out. Try sending some json back to the script... {"test":"abc"} or similar. I see a couple of calls to echo in your code, for example.
Not just this, but any PHP error/warning/notice printed to the browser will break calls.
Hint: you can generate valid JSON from PHP variables using json_encode().
You cannot combine an existing query string with data. Something like this should work (or at least be syntactically valid):
$.ajax({
url: 'index.php',
type: 'post',
data: {information:'information/information/homepage_info',info_description:'test'},
dataType: 'json',
success:function(json){
alert('pass');
},
error:function(json) {
alert('fail');
}
});
Also as was mentioned, anything that is not json will potentially cause an error, so you not echo those html components ... if anything, you print them.
Also, as a side note your dataType should be done server side with a header('Content-type: application/json'); declaration in index.php rather than in your jQuery script. Its guaranteed to be recognized as json that way, and also less Javascript code.

javascript unexpected token < , is there any way I can escape the errors(or atleast skip those useless characters)

In php, I have an array like this :
$arr['a'] = "some big data so may contain some chars that bring us headache"
$arr['b'] = "some big data same as above"
$data = json_encode($arr)
echo $data
My javascript code containing a jquery ajax call, $.ajax . It calls the file containing the above php code so, on success, the json_encoded(by php) is returned to my javascript variable . In my javascript file, I am doing like this :
jsdata = JSON.parse(data); //Getting error here
$.ajax({
type: "post",
data: jsdata,
url: "url",
crossDomain: true,
dataType: 'jsonp'
}).done(function(d) {
print("success");
});
From the above code, in the line jsdata = JSON.parse(data), I am getting errors something like
Error : UNEXPECTED TOKEN <
As the data contains lot of different content, its normal to get those errors . They need to be escaped properly . Can anyone tell me how to do that correctly . Whatever the data may be , I shouldnot get error regarding the data .
Thanks
Well, a couple of things you should probably know jsdata = JSON.parse(data); tries to parse whatever json string you assigned to data, and return it as a JS object. I think you want to do the opposite: jsdata = JSON.stringify(data);
Besides, since you are using jQuery, you could just leave that line out: jQuery will convert the data to the appropriate format before sending the request anyway, no need to bother with parsing or stringify-ing it yourself.
Yeah you forgot the ; at the end of two lines, so PHP is outputing an error, which is no JSON-compliant.
Always do this :
Catch errors and output them in a way that is understable by your application (a 5xx status can be enough)
Next time you have this, use Chrome Developper tool or Firebug to see what your app really returns
Also, you're outputing json, not jsonp which is different and what your app expects
$.ajax({
type: "post",
data: jsdata,
url: "url",
crossDomain: true,
dataType: 'jsonp',
success: function(d) {
print("success");
}
})
try it this way
This is much more simple than it might seem.
Call urlencode($arr['a']) and urlencode($arr['b']) (for each data value in $arr) before encoding the JSON and echoing $data to the JavaScript. This will URL-Encode the data in the array so that it will cause you no problems.
When you are done parsing the JSON, you will have to call the JavaScript function unescape(string) on each of the large data values. This will return them to the way they originally were. It's a sort of superhero-team-up of PHP and JavaScript!

Refer jQuery .ajax Post to function

Is it possible to refer an AJAX POST to a specific function within a PHP file?
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: "some data...",
success: function(){
alert('Success!');
}
});
Or is there a way to have functions.php receive data and know what to do with it? If not, are there any other suggestions for getting data over to mySQL (using PHP/jQuery)? Thanks!
The data sent to the php file using POST can be accessed in php using:
$datasent = $_POST['name'];
Given that you sent data as:
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: {name:"Jesse"}, //data goes here
success: function(){
alert('Success!');
}
});
Not directly. You'd need to post certain data, and have PHP check the POST variables to choose the correct function.
Perhaps have a look at some tutorials (unfotunately the jQuery links for php tutorials are broken).
Is it possible to refer an AJAX POST to a specific function within a PHP file?
No. jQuery doesn't know what PHP is, even less what a PHP function is. jQuery talks to server side urls. Whether those urls are static html files, PHP scripts, Java servlets, Python I don't know what, CGI scripts, is not really important.
So you could use the data setting to pass parameters to this server side url which based on the values of those parameters could invoke one or another function.
If you want to call a specific function, change ur jquery:
$.ajax({
type: "POST",
url: "functions.php", //somehow specify function?
data: {function:"doSomething",name:"Jesse"}, //data goes here
success: function(){
alert('Success!');
}
});
In your php add:
call_user_func($_POST['function']); // This will call what ever function name is passed as parameter
function doSomething(){
echo $_POST['name'];
}

jquery message system without php how to?

i took some interest in this script http://www.9lessons.info/2009/06/comment-system-with-jquery-ajax-and-php.html
and i see that the ajax calls commentajax.php.
what i want to do is to ignore that php, because i want to post to a json file and then get the response from the same file.
my server will use POST or PUT to put the data in the database, so there is no need for me to use php, just the syntax is killing me :)
i want to use :
$.ajax({
type: "POST",
url: "http://www.xxx.com/json",
data: dataString,
cache: false,
success: function(html){
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
document.getElementById('comment').value='';
$("#name").focus();
$("#flash").hide();
}
});
but then how would the commentajax.php look like?
maybe replace the php with :
$.getJSON('http://www.xxx.com/json' , function(data) { ... });
any idea helps
Thanks.
edit1: i have the server-side script in place
If you have the server side scripting set up already, then what is the question again?
If you're asking how to handle the ajax call, then it's mostly a matter of looping through the JSON that you get back, and applying those values to the site in some manner. Pseudo code:
$.getJSON('http://www.xxx.com/json' , function(data) {
for(i=0; i<data.comment.length; i++) {
$(".commentTitle").html(data.comment[i].title);
$(".commentBody").html(data.comment[i].text);
}
});
If I am reading this correctly:
because i want to post to a json file and then get the response from the same file.
You are going to need some server side scripting in order to 'post' to the json file. How are you getting the data into the file.
You can 'read' the data file from the server, that's not a problem, it is a matter of getting the data into the file that you need the server side scripting for.

PHP and Jquery's json

My html file:
<script>
$(document).ready(function() {
$.ajax({
type: "POST",
url: "search.php",
data: "id=1",
datatype: "json",
success: function(msg){
$('.result1').html(msg["name"]);
}
});
})
</script>
<span class="result1"></span>
My php file:
<?
$a["name"] = 'john';
echo json_encode($a);
?>
Why the name John doesn't appear in class result1? Why? Please help me, I am going insane.
edit: Is it possible to make bounty right now?
The dataType parameter has a capital T. It works if you correct this.
Currently it is (by default) trying to guess the response format based on the mime-type, so probably defaulting to html - debugging in firebug you can see that the msg argument of the success callback is a string containing the JSON.
Not to distract you from solving this problem. But you may want to look into the .getJSON() function http://api.jquery.com/jQuery.getJSON/. It's a little cleaner if you're just getting some data.
Also, take a look at the JSON format, I think data: "id=1" should be data: "{id:1}"
And on the response side, keep in mind it's expecting multiple records so try: msg[0].name;, check out the each() function to process multiple records.
I think you should use:
$('.result1').html(msg.name);

Categories