jQuery and Php variable calling - javascript

I have a problem with jQuery and PHP.
I have a .php file that contains a variable, for example var surname = "";
The problem that I am facing is, I want remotely access it from a .html file and give it a value from another variable in the .html file.
Is there any way to do it?
Thanks.

Ok, so you said you wanted to get a variable from HTML and send it to the PHP file to change data, that is what the variable 'varfromhtml' is.
You just need to give it a value you want to send, you can get the value of a div using jQuery eg
<div id="div">data</div>
var varfromhtml = $.("#div").val();
The variable 'varfromhtml' is now equal to 'h08sahdas', you can mess around with that to get it right for you.
Here is the final script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var varfromhtml = $.("#div").val();
$(document).ready(function(){
$.ajax({
method: "POST",
action: "myfile.php",
data: {
varfromhtml:varfromhtml
},
success: function(data){
$('#mydiv').val(data);
}
});
</script>

Related

How to get js variable's value into a PHP variable later used for MySQL without submit or click on any button using JS/Jquery? [duplicate]

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.

Javascript variable within a php variable

I have php function that checks if an entry exists in my database that I call with class::checkThis($my_entry);
In my script javascript is used to determined the name of the folder I am selecting, so $my_entry is supposed to look like this :
(in normal is determined by php and the part in bold is what is determined by javascript)
C:/library/user/apatik/folder1
As you guess I can't find a working way to mix up thoses languages, and I don't really have any experience in javascript yet to figure out this.
The php code that returns the first part of the path is simply $_SESSION['cwd'].'/' and the javascript variable that returns the selected folder's name is data_name and is determined by var data_name = $(this).attr('data-name');
Is there a way to get something like if (class::checkThis($_SESSION['cwd'].'/'.data_name) == true) ?
None of what I tried so far worked and I'm having troubles finding an alternative.
Thanks for the help
You'll need to make an AJAX request to accomplish this. You'll load the page as normal, except for the dynamic part. Then you can populate the dynamic part (I've illustrated it as #content here) based on the result of the AJAX call:
var data_name = $(this).attr('data-name');
...
$.ajax('http://example.com/my_php_script.php?data_name=' + data_name)
.done(function(data){
// "data" is the resulting output of the PHP script
$('#content').append(data);
});
NOTE: The solution above uses jQuery.
Then, in your my_php_script.php, you can do something like this:
if (class::checkThis($_SESSION['cwd'] . '/' . $_GET['data_name']) == true) {
...
}
Ajax jQuery is your best solution.
This one using post method with event, just for reference...
Am I exist?
Am I exist too?
$('.anchor').click(function(){
var data_name = "name=" + $(this).attr('data-name');
$.ajax({
type: "POST",
url: "is_exist.php",
data: data_name,
success: function (data) {
alert(data.response);
}
});
};
is_exist.php
if(isset($_POST['name'])){
$data['response'] = class::checkThis($_SESSION['cwd'].'/'.$_POST['name']) == true ? "exist" : "buried";
echo json_encode($data);
}

Get value from a text file using javascript

I have a text file which has one value in it, this value is updated over time but that doesn't matter, the thing is I want to get this value from the .txt file using javascript and then when I have gotten this value, I would like to change my current variable value to that new value from the .txt file. Because there is only one value at a time like 1 or 10, it just needs to get the value in the .txt file and not a specific value.
My javascript/html so far:
<div class="curVariable">
Cur variable: <span id="curVar"></span>
</div>
<script type="text/javascript">
var curVar= 1;
document.getElementById("curVar").innerHTML = curVar;
</script>
Assuming that the file is on the server, use the following jQuery code:
$(document).ready(function() {
$("#butt").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
}
});
});
});

How can i target javascript variable using jquery?

I want to know how an I target javascript variable using jquery. Here is situation of my web page where I want to use some details that are stored in javascript variable which I will use in user registration. My page codes looks like this
<html>
<head>
<script>
var userData =
{"country":"null","region":"","timezone":"null","key":"sessionSecret","browser":"Chrome","bversion":"0.0","loggedIn":"false"};
</script>
</head>
<body>
<form id="register">
<button id="regbtn">Register</button>
</form>
</body>
<script src="jquery.js"></script>
<script src="custom.js"></script>
</html>
So now how can I use custom jquery function that will target "userData" variable on click of "regbtn"?
I am doing in my custom javascript is
$( document ).ready(function() {
$('#regbtn').click(function(){
//do something here that will target that userData variable and will send its data using ajax
//$ajax function will send data to page with details that user entered and userData
});
});
But I don't know how to target that userData variable using json. This variable in json data format out put of php. Can anyone help me?
And with negative votes I'd appreciate if you tell me why are you voting negative this question. I am not pro so asked this question. May be this is stupid but not for me. So thank you anyways for seeing this question
If you need to access your json object "userData", you'll want to add the following in your click function:
var country = userData['country'];
var region = userData['region'];
and so on.
You could send the whole object without separation if you plan on sending it via AJAX. Below is an example of this:
$(function() {
var userData = {"country":"null","region":"","timezone":"null","key":"sessionSecret","browser":"Chrome","bversion":"0.0","loggedIn":"false"};
$('#regbtn').click(function() {
$.ajax({
url: "someURL",
data: userData,
type: "POST",
cache: false,
dataType: "json"
}).done(function(data, textStatus, jqXHR) {
// check if response was valid/invalid or do other stuff here
});
});
});

Load php in background with javascript, not passing variables

I'm working on this function that loads a php file in the background:
<div id="content1"></div>
<script type="text/javascript">
<!--
$("#content1").load("/bm_products_filter.php");
//-->
</script>
The original php code is this:
<?php require('/bm_products_filter.php');
?>
With the original code the page works fine, with the java code it gives errors. This is because the php doesn't use the variables in the current page. I know how to pass variables to the external php but is there a way that it uses all the variables on the current page?
I am not sure if I got you wrong but you cannot load PHP files with JavaScript or JQuery.
JavaScript is client sided and has no access to the server if you want to load some data on a point of time when the template builds / is built without PHP oyu have to use an Ajax request which is also pretty simple with JQuery.
Please check out:
http://api.jquery.com/jquery.ajax/
If you can rewrite the bm_products_filter.php to return a JSON output, you can use a function as below to get values returned from the php.
jsonKey1 I have used below is one of the JSON keys returned from the php.
function getToken() {
var requestStr = "./bm_products_filter.php";
$.ajax({
url: requestStr,
type: "GET",
cache: true,
dataType: 'json',
success: function (data) {
bmProductsData = data.jsonKey1;
}
});
}
Hope this helps.

Categories

Resources