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.
Related
I have a Javascript variable which I am setting a PHP variable to.
function cancel(number) {
var message = "<?= $message[" + number + "]; ?>";
}
$message is an array. "number" is the element of the array I want to set message to. Basically, I want to set a Javascript variable to a PHP variable using a Javascript variable as the element picker. So if "number" was 2, it would select:
$message[2];
However, the above approach doesn't work, and I'm not even sure if this is possible.
It isn't. Use XHR to retrieve the value from the server.
It doesn't seem at all possible; PHP is evaluated server-side, and javascript is evaluated client-side. So PHP would see it as $message["+number+"], and try to find the value at the index of "+number+". You'd probably have to do something like an AJAX request to get the data you're looking for.
What you are doing isn't possible; since php is a server-side language, it's executed first, and the js is executed after; there isn't any way to control which is executed first. You must retrieve the variable using AJAX.
Something like this will work:
<script type="text/javascript">
var messages = <?= json_encode($message) ?>;
function cancel(number) {
var message = messages[number];
}
</script>
Of course this will output the entire array in the JavaScript source. If it is large, then you are better off using AJAX.
Tip: if you "view source" it should be painfully obvious why your method doesn't work.
You simply cannot do this using this methodology. PHP is server-side code, meaning that it runs on the server, while JavaScript is client-side code, meaning it runs on the client, or your browser.
Once the PHP runs, it generates an HTML document and sends that document in the response to the browser. Once that's complete, the only way you can get data back to the server is to send it via a form POST, send it via AJAX, or send it via script tag remoting.
Consider looking at some examples on the Internet of how to POST data back to the server via a form and via AJAX. It's clear you're struggling with some concepts regarding how to properly architect your program, and looking at some examples would be a great way for you to learn and master these techniques.
PHP Submit Form Example
PHP Tutorial
You need to use AJAX call to resolve your issue.
I want the value of JavaScript variable which i could access using PHP.
I am using the code below but it doesn't return value of that variable in PHP.
// set global variable in javascript
profile_viewer_uid = 1;
// php code
$profile_viewer_uid=$_POST['profile_viewer_uid'];
this gives me the following error :-
A PHP Error was encountered
Severity: Notice
Message: Undefined index: profile_viewer_uid
Another php code i used which give empty value
$profile_viewer_uid = "<script language=javascript>document.write(profile_viewer_uid);</script>
When I echo it shows nothing.
Add a cookie with the javascript variable you want to access.
document.cookie="profile_viewer_uid=1";
Then acces it in php via
$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];
You will need to use JS to send the URL back with a variable in it such as:
http://www.site.com/index.php?uid=1
by using something like this in JS:
window.location.href=ā€¯index.php?uid=1";
Then in the PHP code use $_GET:
$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar
Here is the Working example: Get javascript variable value on the same page.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.
Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.
If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.
<script type="text/javascript>
var foo = <?php echo json_encode($somePhpVar); ?>
</script>
If you want to use a js variable in a php script you MUST pass it within a HTTP request.
There are basically two ways:
Submitting or reloading the page (as per Chris answer).
Using AJAX, which is made exactly for communicating between a web page (js) and the server(php) without reloading/changing the page.
A basic example can be:
var profile_viewer_uid = 1;
$.ajax({
url: "serverScript.php",
method: "POST",
data: { "profile_viewer_uid": profile_viewer_uid }
})
And in the serverScript.php file, you can do:
$profile_viewer_uid = $_POST['profile_viewer_uid'];
echo($profile_viewer_uid);
// prints 1
Note: in this example I used jQuery AJAX, which is quicker to implement. You can do it in pure js as well.
PHP runs on the server. It outputs some text. Then it stops running.
The text is sent to the client (a browser). The browser then interprets the text as HTML and JavaScript.
If you want to get data from JavaScript to PHP then you need to make a new HTTP request and run a new (or the same) PHP script.
You can make an HTTP request from JavaScript by using a form or Ajax.
These are two different languages, that run at different time - you cannot interact with them like that.
PHP is executed on the server while the page loads. Once loaded, the JavaScript will execute on the clients machine in the browser.
In your html form make a hidden field
<input type="hidden" id="scanCode" name="SCANCODE"></input>
Then in your javascript update the field value by adding;
document.getElementById("scanCode").setAttribute('value', scanCode);
This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself.
Given that you have added an php command to catch the variable, you will get it.
You need to add this value to the form data that is submitted to the server. You can use
<input type="hidden" value="1" name="profile_viewer_uid" id="profile_viewer_uid">
inside your form tag.
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.
Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.
if ($publish == '') {
Link to publish.html
} else {
Link to edit.html
}
What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.
How can it be donw using javascript, jquery or ajax?? Please assist.
Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. Since you mentioned jquery, you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
$("a.youra").text('edit').attr('href', resp);
});
url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php.
After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.
I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.
Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.
PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.
For example, you could have javascript call a script like:
http://www.myserver.com/ajax_function.php?do=queryTheDatabase
In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.
Let me try, you want to change the link in a page from a pop-up that handles a form processing. Try to give your link a container:
<div id="publish_link">Publish</div>
As for the form submission use Ajax to submit data to the server to do an update and get a response back to change the link to edit or something:
$.post("submit.php", { some_field: "some_value"}, function(response) {
if(response.isPublished)
$('#publish_link', window.opener.document).html('Edit');
});
Basically your publish link is contained in a div with an ID publish_link so you change its content later after data processing without reloading the page. In the pop-up where you would do the form processing it is done using jQuery Ajax POST method to submit the data. Your script then accepts that data, update the database and if successful returns a response. jQuery POST function receives that response and there's a check there if isPublished is true, get the pop-up's opener window (your main window) and update the link to Edit. Just an idea, may not be the best out there.
It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.
Well, i think i understand your quaestion, but you have to get a starting point, try to understand this:
try to understand what are client variables and server variables.
javascript does not comunicate with database.
you can use javascript to retrieve data to a specific "Object variable".
Using ajax methods of jquery you can post that data do other page, that will execute the
proper actions
you can ;)
at first you must create php file to query database and return something like true or flase and then with file url check the function and get answer
function find_published(folder_id) {
var aj_url = "{{server_path}}/ajax/url"
var list;
$.getJSON(aj_url+"?callback=?&",
function(data) {
//here is your data... true false ... do every thing you want
}
);
};
this app for node.js does mysql queries https://github.com/felixge/node-mysql
You need to use AJAX for this, like .post() or .get() or JSON.