How to call function from jquery to php? - php

PHP:
$product_code = $_GET['product_code'];
$countryCode = getCountryCode();
<script src="js/register_script.js" type="text/javascript"></script>
Jquery:
function getCountryCode() {
countryCode = qrcode_getinfo(qrCode1,"mfg_c_a_code",0)
return countryCode;
}
I want to get my country code from the jquery to perform some validation task, however, i wasn't able to retrieve the country code. Any idea what should i do for it to work? please note that the library is already been called. (I had read up on examples but dont really understand how it works..)

It is not possible to directly call PHP function from JavaScript and vice versa. Part of the reason for this is that as #Pekka indicated JS runs clientside (in your browser) while PHP runs server-side (on your server).
It is however possible to use AJAX for your purposes:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function getCountryCode()
{
countryCode = qrcode_getinfo(qrCode1,"mfg_c_a_code",0)
return countryCode;
}
function doAjax(){
var countryCode = getCountryCode();
$.ajax({
'url' : '<THE_URL_TO_YOUR_PHP>?countryCode=' + countryCode,
'method' : 'GET',
'success' : function(data){
console.log(data);
// do your handling here
},
'error' : function(data){
console.log(error);
// this function is executed on an HTTP error
}
});
}
</script>
PHP
This is your php file that would do your validation. In principle it is a different file than the file that outputs the html as shown above.
$countrycode = $_GET['countryCode'];
# handle countrycode
echo "<What you want to return to JS>";
Edit
On the additional question of how to get session variables to js.
Would I navigate to your page in my browser, the following would happen: If I requested a file with an .php extension, the PHP processer gets run on it. This processer identifies all code between the tags <?php and ?> as PHP, and thus runs all this code. If it encounters an echo statement, it echo's out the specific value at the location of the php-block.
After PHP is done processing, the page is served (given) to your browser, where it will be interpreted as a combination of HTML/javascript/... Javascript interprets everything between the tags <script> and </script> as javascript.
So, what if we where to make a request to index.php?par=val on your server, and index.php looks like
<script type="text/javascript">
function doStuff(){
var param = <?php echo json_encode($_GET['par']);?>;
}
</script>
(the json_encode function ensures that the variable is in proper json format. Of course you can change the `$_GET['par']; to be whatever you would like.)
Remember, PHP only cares about whats between the <?php and ?> tags, so this would output:
<script type="text/javascript">
function doStuff(){
var param = "val";
}
</script>
You will need to edit this to match your requirements of course, but this is the basics of passing parameters from PHP to client-side (JS)

Related

Passing Javascript Variable To PHP Using Ajax Echo's Undefined Index

I minimized the code snippets to show only the code needed, and the url for the server side file is actually connected to a url on my server.
HTML FILE
<head>
<script>
var btid = 1;
$.ajax({
url: "serverSide.php",
method: "POST",
data: { "btid": btid }
});
</script>
</head>
<body>
<?php include("serverSide.php"); ?>
</body>
serverSide FILE
<?php
$btid = $_POST['btid'];
echo($btid);
?>
DESCRIPTION
So what is going on is when the page loads, the javascript code runs. It creates a variable named btid equal to 1. This variable is then sent to a file on my server that is a php file. I want to echo that variable through php. But when I load the page, I get an error log stating that the code $btid = $_POST['btid']; has an Undefined Index.
I don't think your code is going to work as designed. You are using include("serverSide.php"); in the body of the HTML, but it is never going to have any $_POSTvalues unless you are posting a form.
Your ajax call is not doing anything with the value that is being returned.
I think you should remove the include("serverSide.php"); from the body of your HTML (it is serving no purpose in its current incarnation) and use the returned value of your ajax call to put the value of btid in the HTML (if that is where you want it).
When you use PHP's include as in <?php include("serverSide.php"); ?> PHP will execute the code on the file being included. That is what is causing your error, when the code is first evaluated it has no $_POST['btid'] because you haven't called it yet.
Your javascript will run on page load and make the ajax call correctly, but you are not using the response anywhere. In order to store the response from the Ajax call you need to add a success handler.
If I understood what you are trying correctly, your code should look more like this:
HTML FILE
<head>
</head>
<body>
<div id="response"></div>
<script>
var btid = 1;
$.ajax({
url: "serverSide.php",
method: "POST",
data: { "btid": btid },
success: function(res) {
$('#response').text(res);
}
});
</script>
</body>
What we are doing is making the ajax call and when the call is successful we assign the returned value as the div content. Also, I switched the script tag to the end of the body because we need to be sure all the document has loaded before changing anything (could have used $( document ).ready()).

change php variable with ajax

I have an php variable like this:
PHP Code:
$php_value = 'Am from PHP';
And I want to be able to change this variable with jQuery and the jQuery is on the same page?
You can't.
By the time the page has been delivered to the browser and the JavaScript has run, the PHP program that generated the page will have finished running and the variable will no longer exist.
JavaScript will allow you to send new data to the server (Ajax), where the server could store the data somewhere (a database is usual), and read the response.
JavaScript will also allow you to modify the page in in the browser (DOM) (including with the data included in the response for an Ajax request).
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it:
$php_value = 'Am from PHP';
if exists($_POST['php_value_from_jquery']) {
$php_value = $_POST['php_value_from_jquery'];
}
If I understand your question correctly, AJAX cannot post data to PHP code on the same page. I've been told that it can, but it is not trivial - still, I cannot imagine how that is possible. At any rate, AJAX is easy if a secondary PHP file is used.
Here is an example of what I mean. If you try this:
<?php
echo 'Hello';
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body>
</body>
</html>
The popup will contain the HTML for the page.
However, if you use two files:
file1.php
<?php
echo 'Hello';
?>
file2.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'file1.php',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body></body>
</html>
The popup will contain only the word "Hello".
To use ajax, you must call an external PHP file.
After considering the above, note that Quentin's answer is important -- even if you use AJAX to set a PHP variable on the server, that variable disappears after the AJAX completes -- just like the PHP variables all disappear after your index.php has finished rendering the DOM and presenting it to the visitor's browser.
So, what's to be done? Two options.
(1) As Quentin points out, you can store values permanently in a database, or
(2) You can use a PHP superglobal, such as a $_SESSION variable. For example:
Client side: file2.php
var storeme = "Hello there";
$.ajax({
type: 'POST',
url: 'file1.php',
data: 'stored_on_server=' +storeme,
success: function(data) {
alert(data);
}
});
file1.php
<?php
session_start();
$SESSION['a_variable_name'] = $_POST['stored_on_server'];
You can later retrieve that variable value thus:
$.ajax({
type: 'POST',
url: 'file3.php',
success: function(data) {
alert(data); //a popup will display Hello There
}
});
file3.php
<?php
session_start();
echo $SESSION['a_variable_name'];
You can't able to change the php value using javascript. i.e Server scripts runs first after that client side script will take effect in that case you cant able to modify the same, since they already rendered in browsers
If jQuery is going to be processing the data, then you can assign the PHP variable to a jQuery variable like this:
<script>
var jquery_value = <?php echo $php_value; ?>
</script>
As far as I know, because jQuery is client-side and php is server side, it's not possible to assign a jQuery variable back to PHP.

How to pass values from AJAX and JQuery to PHP in the same file

I am current have the following script. I want pass a value from javascript to php by using AJAX. What's wrong with my code?
<script type=" text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.post("index.php",{host:document.referrer},function(data){});
});
</script>
<?php
$dataString=$_POST['host'];
echo $dataString;
?>
Since the PHP is executed first, you will never see the echo $dataString from your AJAX request. This code will post your request to the server, but you'll never see the result.
Right now here is what is happening:
Your web server renders out your page.
Your browser posts a request to index.php, and ignores the result
From the docs you can see this:
$.post('index.php', function(data) {
$('.result').html(data);
});
The data in that function will return what echo $dataString; outputs from your script.
Also, your post isn't configured correctly. You need to put data: before {host:document.referrer}

export variable in JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Access a JavaScript variable from PHP
I have one JS code that return my geolocation (latitude, longitude) and I would like to reuse these information in a PHP code. My webpage has .php extention and I have set global variable but it doesn't work.
How can I do that ?
<script type="text/javascript">
function getCoordPosition(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
});
}
}
</script>
<?php
echo 'Latitude is $latitude';
?>
You can't just combine the two; Javascript executes in the browser, PHP on the server (before the page even reaches the browser). If you want to communicate a Javascript result to your server, your should submit it using a form, or use AJAX for asynchronous requests.
One of the methods are from $_GET method
var test1 = "myvalue";
var link = "thispage.php";
window.location = link+"?test1="+test1;
Then read the value from the testpage.php
Another methods is $.get, or $.post request to a php page.
$.post("mypage.php", {
myvar : "myvalue",
"myanothervar" : "myanothervalue"
}, function(data) {
//data contains the output from the script
});
I think the issue is that you are mixing client side code (javascript) with server side code (php). The php on the server cannot access the information from the client at run time since the client runtime doesn't exist yet. The client must submit it back to the server for use.
The php code executes and the response is sent to the client. Then the client page is executed from the top of the page to the bottom. At that point the server doesn't know what's going on on the client. You could load the client page and and then use jQuery to make a server side call (AJAX) back to php to pass it the information.
something like (I'm a bit rusty on jQuery)
$.get('myurl/sendgeolocation', { lat : lattitude, long : longitude }, function (data) {});
Then you would want the server do do whatever it needs to do in the function(data) callback to update the screen as necessary or whatever.
Your PHP code is processed first by the server and then sent to the viewer. Then the JavaScript code is executed, so PHP has no way to know what JavaScript is doing since it is processed prior to the JavaScript. You could use AJAX to pass the JavaScript information to a PHP script and then get something back from it, but it really depends on what you want to do with all this.
This is what exactly the answer you expect
//index.php
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function getCoordPosition()
{
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position){
latitude = position.coords.latitude;
longitude = position.coords.longitude;
obj ={};
obj.latitude = position.coords.latitude;
obj.longitude= position.coords.longitude;
//latlngvalue = $.get('index.php',obj,"html");
$.ajax({
url:'fetch.php',
data:obj,
dataType:'html',
success:function(obj){
latlng = obj.split('-');
$('#latlng').html("Latitude : "+latlng[0]+"| Longitude :"+latlng[1]);
}
});
});
}
}
</script>
</head>
<body>
<div id="latlng"></div>
<button onclick="getCoordPosition()" >Get Geocode</button>
</body>
</html>
//fetch.php
<?php
if(isset($_GET['latitude']) && isset($_GET['longitude'])):
echo $_GET['latitude'].'-'.$_GET['longitude'];
endif;
?>

Calling JavaScript within Php block and vice-versa

echo "<a href=#> Delete </a>";
Whenever a user hits Delete, a javascript function should be called for confirmation. Somewhere in the Javascript function, php code should be used for delete operation. How do I do that? Use something like "some php code goes here" and "some javascript function();" for me to know where to put what. Thanks.
This assumes that you are using jQuery...
<a href='javascript:delete();'>Delete</a>
<script type="text/javascript">
function delete()
{
$.post("/your_script.php", {}, function(result) {
});
}
</script>
JavaScript functions execute on the client (in the browser) and PHP executes on a server. So, the JavaScript must send a message - via HTTP - to the server to be handled by PHP. The PHP would perform the delete. Make sense?
The message sent to the server might be sent via AJAX.
Maybe you should use Ajax: http://en.wikipedia.org/wiki/Ajax_%28programming%29
PHP is a server-side technology, while JS is a client-side. They cannot interact with each other - in other words: they're completely independent.
PHP can only output code that is a JS code:
echo 'document.getElementById("test").appendChild(document.createTextNode("' . $myVar . '");';
It's all PHP can do. JavaScript cannot direct interact with PHP as well. You'll have to use AJAX to send a new HTTP request and process returned data.
PHP is a server-side language, thus you can not output PHP script to the browser and expect that it will parse it with the PHP engine.
What you're looking for is probably AJAX, or simply redirecting the user to another page (with different URL parameters) or submitting a form.
AJAX doesn't require from the browser to reload the page, while the two other methods does.
Anyway, you can execute a JS script with the "onclick" method, that's executed when the user clicks on the element: Delete
But the following approach looks better and considered as an ideal one:
Delete
<script type="text/javascript">
document.getElementById("myId").onclick = myFunc;
</script>
Since this involves Ajax, let's assume you can use jQuery to handle the XHR an so on.
<script>
$('#del').click(function(ev){
ev.preventDefault();
var del_conf=confirm('Are you sure you want to delete this item?');
if(del_conf){ $.post('delete.php',{'del':1,'id':123123},function(data){
alert(data.result);},'json');
}
});
</script>
<a id='del'>Delete</a>
Okay, so that's some JS and HTML. Now, you need a separate PHP script to handle the post. To go with the example, this would be saved in the same directory, named 'delete.php'.
<?php
$del=(int)$_POST['del'];
$id=(int)$_POST['id']
if($del<1 || $id<1){ exit; }
else{
//do your DB stuff
}
if($db_success){
echo json_encode(array('result'=>'success'));
}
else{
echo json_encode(array('result'=>'error'));
}
here is another example using jQuery:
<div id="message"></div>
<a class="action" type="delete" rel="1234567">delete</a>
<script type="text/javascript">
$('a.action').click(function(){
var $this = $(this);
var processResponse = function(data){
//optionaly we can display server response
$('#message').html(data);
return;
};
var postPparams = {
module:'my_module_name',
action:$this.attr('type'),
record_id: $this.attr('rel')
};
$.post('/server.php',postPparams, processResponse);
});
</script>

Categories