I am new to AJAX/jQuery with PHP.
I am trying to call a PHP script via AJAX using XMLHttpRequest or jQuery. In both cases the call fails because the php file I am calling into contains on the very first row the following check
if (!defined("SOMETHING")) { die("Error. You cannot access this file directly");}
which causes that my call fails, because this variable is not defined in this case as I am calling from the outside. This condition just checks if the caller is the same web application or wheather the call comes from outside (then it will be denied).
Is there a workaround for it without removing this check? Can I somehow set this expected variable using AJAX/jQuery?
Is there a way how to call specific PHP method via AJAX without calling into the whole PHP file?
Thanks in advance
Tomas
Hmm... you can do it, but I am not sure if this is secure or the way you would like it to be.
Your jQuery should post a variable with GET or POST, which you should check on PHP side. If you have received that variable, then define SOMETHING.
Here is your jQuery, using the POST method:
$.post('ajax.php', {SOMETHING: true}, function(ret){
// do whatever you like with the return here
});
Here is your PHP, which will define SOMETHING if it receives a $_POST request with the variable SOMETHING in it.
<?php
if(isset($_POST['SOMETHING'])){
define('SOMETHING', true);
}
if (!defined("SOMETHING")) { die("Error. You cannot access this file directly");}
// do anything you like here
?>
Related
I am working on a project where I used ajax for asynchronous DB access.
I store the value in JavaScript variable as follows..
var content=xmlhttp.responseText;
now what I wanted is to pass this value to the php module on same page..
Please suggest me..its urgent
You'll have to make a separate AJAX request to another script to achieve this. PHP is server-sided and therefore cannot directly interact with the client.
You should handle the data (which you are assigning to content) in PHP because, as the other answers here tell you, PHP is server-side and JavaScript is on the client. If you are getting this data from a page you control, instead of var content = xhr.responseText; just modify the data BEFORE you send it. For example, if you are making an AJAX call to a process.php file on your server to get the data you are otherwise assigning to content in JavaScript, be sure to handle the data in process.php PRIOR to echo()'ing the data (which you are then storing inside content on the client):
In process.php:
// below is the normal server script which you are storing in content on the client
// echo $result;
// instead, we are going to operate on the data first:
return doSomething($result);
Then on the client:
var newContent = xhr.responseText;
And the newContent variable will contain the data you previously wished to modify with PHP. If you DO NOT have control of the server script which you are calling with AJAX, then as mentioned here already, you will need to send a SECOND AJAX call to the server with your PHP, and use $_GET or $_POST to retrieve that content data and then play with it there.
Am unclear about your need to pass value from javascript to php.
But I can give you,
A non-recommended but working approach towards your problem:
You said, you are making an Ajax call at first. While processing the corresponding server side php function, Store the response value (value of xmlhttp.responseText) into a $_SESSION variable. Finally Reload the page (using location.reload()) inside the ajax response handler function.
And a recommended approach towards your problem:
You might have added some if-else control-flow structures in the php code and expecting to execute them after getting the ajax response value (sadly you cannot do that). So if you do have some logic like that, then convert those if-else conditions to corresponding Javascript code. May be a javascript function and call that function by passing the ajax response value to it. This new function will use your ajax response value and make changes in some parts of your webpage by applying necessary logic.
I am using zend framework project which is been created by using zend studio.
Also there is a Jquery project which is created separately.
I have deployed jquery project in tomcat, and on click of one button in jquery, a php method is called by using ajax LOAD method. PHP is returning string value.
However, for some reason data is not coming back to jquery method.
Jquery method:
var res = $('#updatedtime').load("http://test/index/returndate");
PHP method
public function returndateAction(){
$this->_helper->viewRenderer->setNoRender(true);//this will do job
return "hi";
}
Can we use jquery LOAD method be used to get data? Please correct me if am wrong!
Thanks all
Do you mean something like:
PHP
public function returndateAction(){
$this->_helper->viewRenderer->setNoRender(true);//this will do job
echo "hi";
}
jQuery
// data from PHP is displayed in your element having id updatedtime
$('#updatedtime').load("http://test/index/returndate");
OR
$('#updatedtime').load("http://test/index/returndate", function(data){
alert(data); //shows 'hi'
});
Check if the url you are trying to access thru load actually gets called.
The client doesn't know or care what you run server side. You can get anything you want from the server, whether that is something created with PHP, or a static resource.
If you aren't getting data back, use your browser's network tools to verify that the request is being made, and data is being returned. Also, make sure you are actually executing that function server-side. It doesn't appear that you are.
Yes, just add a callback function as the second argument to .load
$('#updatedtime').load("http://test/index/returndate", function (phpString) { ... });
im stucked with following issue. I have an javascript (jquery) function where i need to pass a variable to php ON .success method. See below Please:
http://paste.org/55404
Any idea how to achieve this? Or is it even possible?
Thanks in advance.
jQuery runs in the browser. PHP runs on the server. So you can not mix and match them like that.
Instead, you will have to use AJAX or another mechanism to contact the server and get the information you need.
Depending on your use case, there may be other solutions, such as inserting the values into the page when the server generates it, or putting the values in a cookie.
Referring to your code, The .success method is called, when your ajax request to "index.php" returns a successful response.
Since you need to get the PHP variable in this function, you can attach the value of "genNavSide()" to the response as a parameter. It is the same way you assigned pageName value, and content value to the response data.
For example, instead of :
<?php echo pagesSideBar('data.pageName') ?>
call the function from your index.php, during the ajax call.
$sidebar = pagesSideBar($PageName);
$response->sidebar = $sidebar; // I just mentioned object, you can assign whatever way you are following to create the response
In the .success method :
jQuery('#links').html(data.sidebar);
Ok so trying to get a page together that needs to connect to our SQL database. So on the javascript page I have functions that will autocomplete a textbox with data out of our mysql DB and then I need to send it to other functions and classes so that it will then look in our SQL DB and return some data. The problem I have is trying to get the .GET call to call in the php page, with the function that calls the class in which I need to get into for the SQL call. I have it setup somewhat but trying to figure out how to send the data through with it as well as just get clarification on how to work the .GET function.
Javascript page:
$.get("dsl_validate.php", calldsl(job));
Php Page
function calldsl($job){
var $dsljob = $job
hasfunctioncode($dsljob);
}
The hasfunctioncode function is in my DSL class page that will return the info I need. Any help on if I am in the right direction or not?
It looks like you're trying to physically call the PHP function calldsl() from the JavaScript. This... isn't right. (I'm assuming the $.get() you're using is from jQuery, please correct me if that assumption is incorrect.)
What $.get() does is simply call a resource on the web server. It doesn't have any knowledge of the server-side code (nor should it, for a number of reasons). From the perspective of the server-side code, there's no difference between a page being called via $.get() vs. one that's just loaded in a web browser.
What you essentially need to do is create a PHP page which accepts arguments either as a form post or query string (if you're using $.get() then the query string is the way to go), does its server-side logic, and then simply outputs the results to the "page." In the case of calling the page via AJAX as you are here, it's a good idea to render the page content using JSON notation. (Don't forget to set the content-type header to "application/json" as well.)
Then what you're getting on the client-side from the $.get() call is the response body, which would be that JSON data. It's really just a "page" like any other, the only difference is the content-type telling the browser that it's JSON data and that it doesn't have HTML, just JavaScript objects. The success callback on the $.get() call (the function you pass it, or create in-line) would receive that response data as an argument and can do what you need to with it.
The way I understand jQuery.get(), the second argument is the "callback" (http://api.jquery.com/jQuery.get/). The callback will hand the results from your server therefore should be a function. Currently your code actually executes the function "calldsl" where you should be only passing a reference like so...
Javascript:
$.get("dsl_validate.php", function(response){
alert("yay I haz ajax! "+response)
});
PHP: "dsl_validate.php"
echo "this is some data from the server";
No, your are not in the right direction. The first parameter of the get method have to br the complete URL of the page, not just the script (this works if the script resides on the same directory of the javascript file, though). The .php file shall return somehting "usable" for you javascript (JSON, or HTML, or text, or... whatever). The "calldsl" function will be called AFTER the data has been returned from the call. Something like that:
$.get('dsl_validate.php?value=somevalue', function(data) {
alert("Data returned from dsl_Validate: " + data)
});
i think you are better off passing the function as a param to your php page
$.get("dsl_validate.php?calldsl="+job, function(data) {
$response = $(data);// create a jquery object from the response
});
`
and in your php file
create a switch statement that call the function based on the parameter
Mmm I think you are wrong, the second argument on your get function is the javascript function that will process de data returned by "dsl_validate.php". I mean, if that page returns "foo", job will contain "foo".
But in my experience is better to use the autocomplete plugin from Jquery UI
jquery autocomplete plugin
I have the following jQuery function in my PHP:
echo '
function myFunction() {
return $.ajax({
type: "POST",
url: "mypage.php",
data: "name=John&location=Boston"
});
}
$.when(myFunction()).then(function(data) {
// handle data return
someOtherFunction(data);
// need to set "data" var into PHP SESSION
}, function(error) {
// handle ajax error.
});
';
After my AJAX does the majic it returns a value (data), which I pass into another function. In addition I need to be able to set that value into a PHP session:
$_SESSION['project'][data] = data;
How do I do that? The switching between PHP and JS confuses me for some reason...
That's impossible since the JS is now on the client side. You can't set PHP variables directly.
What you could do is set a cookie in JS using document.cookie, and then on the next page request PHP can get at it via $_COOKIE.
You could also just set the $_SESSION variable inside mypage.php - that may be significantly easier, if they both share the same session.
It's confusing because you're mixing the two, try to keep a distinct separation in your code. Instead of echoing your jQuery script, just close the php tag, that would also make syntax highlighting work.
As for setting session variables, you need to do it on the server side in your mypage.php, before writing the data to the output. That will happen before passing the data to the client side jQuery script for processing.
First of all you must be aware the javascript is a clientside language and PHP is serverside. Everything PHP does, it does when the page loaded and it stops after the page is loaded. Javascript takes over then.
What you could do is create mypage in a way that it also creates $_SESSION['project']['data'] as an associative array that you can use with PHP. What you're not trying to do is setting a javascript array into a PHP variable. Not that this is wrong by default, but since you're trying to SET the data using PHP my guess is you will also GET the data using PHP, thus a javascript array in that session would be useless.
So in mypage.php you've probably have something like:
echo json_encode($result);
Where $result is the array of data returned by the script. You could simply add one line above saying:
$_SESSION['project']['data'] = $result;
and have the data stored in the session to use on other pages.