JS variable to PHP variable without buttons or refresh - javascript

I've searched for over an hour and tried many examples but none do what I need. From JavaScript I can display the necessary variable in PHP or HTML with <b id="citynm"></b> but I need to make citynm $citynm. I've tried looking in AJAX for the first time but could only get it to work with a button click or page refresh.
I need to run the JavaScript to get citynm and then make it into $citynm for PHP use on any page without running the JS again. The JS is only run once upon entering the site. But the $citynm will be run on several pages in different needs (such as echo "You live in ".$citynm).

The best way is to store the value you want for citynm into a session variable as below:
$_SESSION['citynm'] = $citynm
You have to do this either at page load, or by ajax. Then, you can use $_SESSION['citynm'] in any pages you want since its global.

USECASE 1: via user input
in your html document:
<input type="text" name="citynm" id="citynm" value="Brussels">
inside your javascript file (using jquery here for readability):
(function(){
$('#citynm').on('blur',function(){
// when the input value has changed, post its value to server.
var citynm = $(this).val();
$.post('http://domain.com/path/to/your/php/file.php',{citynm: citynm},function(data){
// if the request is successful, the following script will be executed.
alert("server said: "+data);
});
});
})(jQuery);
And inside the file.php file:
<?php
session_start();
if(isset($_POST['citynm']) && strlen($_POST['citynm'])>0){
$_SESSION['citynm'] = $_POST['citynm'];
}
echo "citynm is ". $_SESSION['citynm'];
?>
USECASE 2: no userinput
var cityname = city.short_name;
if (status == google.maps.GeocoderStatus.OK) { document.getElementById("citynm").innerHTML = cityname; }
(function(){
$.post('http://domain.com/path/to/your/php/file.php',{citynm: cityname},function(data){
// if the request is successful, the following script will be executed.
alert("server said: "+data);
});
})(jQuery);

Related

Refresh page when value is = 1

Hello im trying make a system for when on value on my datebase is 1 my index page refresh. this is my code!
All PHP code works, only my index.php not refresh.
index.php
<script>
inverval_timer = setInterval(function update() {
$.get("base_de_dados/update/loadMensagens.php", function(data) {
$("#numseiCategoria").html(data);
window.setTimeout(update);
})
}, 5000);
</script>
loadMensagens.php
<?php
include_once '../bdados.php';
$fila = $conn->query("SELECT * FROM tickets_update");
while($Filas = $fila->fetch_assoc()){
$condicao = $Filas['condicao'];
}
if($condicao == 1){
$condicao = 0;
$queryAtualizar = $conn->query("UPDATE tickets_update SET condicao='$condicao'");
echo "
<div id='a'></div>
<script>
$.ajax({url:'updateMensagens.php', success:function(result){
$('#a').html(result)
}});
</script>";
}
?>
updateMensagens.php
<script>
$(document).ready(function(){
location.reload();
});
</script>
At a glance there are a couple of reasons your page isn't reloading. Firstly, the reload method being wrapped in that .ready() probably prevents it from being called, as I believe the ready event only fires when the DOM first loads.
$(document).ready(function(){
location.reload(); // Will never fire if script is added to DOM after initial load.
});
But I think there's another issue as your code simply appends this HTML...
<div id='a'></div>
<script>
$.ajax({url:'updateMensagens.php', success:function(result){
$('#a').html(result)
}});
</script>";
...onto the end of #numseiCategoria's inner text, which probably doesn't make the browser execute the script anyway (I'm assuming that jQuery's .html() is basically an alias for innerHTML here, I can't be bothered to go and check).
But, in terms of good practices, there's more to it than that...
updateMensagens.php seems to be incredibly redundant, unless there's more to it than you're showing. Let's have a think about how you intended it to work, ignoring the fact that your method of adding scripts to the page is incorrect.
You have your main script in index.php, which sends a get request to loadMensagens.php, which does some database stuff. So far so good...
Your PHP script then echoes some JS, which your main script appends to the page. This JS tells the client to send another get request, this time to updateMensagens.php, and to once again append the result to the page.
This second request returns only a script telling the browser to reload the page. And now we've run into problems.
This is a really awkward and long-winded way to go about this, especially once you try to scale the approach up to larger projects. You're trying to do certain things with PHP which are much more easily done with JS. I'll briefly highlight a couple of things for you.
Firstly, echoing HTML back to the client like that is not great, it gets very unwieldy very quickly. It's much cleaner to return any necessary data to the front end as JSON (or a similar format) and handle generating HTML with JS. jQuery makes generating complex documents rather easy, as you're already using it I'd recommend that approach.
Secondly, this system of using ajax requests to fetch a script from the server to append to the page to perform a simple action with JavaScript is diabolical. Please see my untested, 4AM alternative.
index.php
<script>
inverval_timer = setInterval(function update() {
$.get("base_de_dados/update/loadMensagens.php", function(data) {
let res = JSON.parse(data);
if(res.condiciao === true) {
location.reload();
}
});
}, 5000);
</script>
loadMensagens.php
<?php
$return = [];
include_once '../bdados.php';
$fila = $conn->query("SELECT * FROM tickets_update");
while($Filas = $fila->fetch_assoc()){
$condicao = $Filas['condicao'];
}
if($condicao == 1){
$return['condicao'] = true;
$condicao = 0;
$queryAtualizar = $conn->query("UPDATE tickets_update SET
condicao='$condicao'");
} else {
$return['condicao'] = false;
}
echo json_encode($return);
As an addendum, you seem to be using setTimeout wrong. On one hand I'm quite sure the method is supposed to take 2 arguments, but on the other hand I'm not sure why it's being used at all.
Goodnight.

JQuery to submit PHP not executing

After hours of playing with this, it hit me that my JQuery simply isn't executing.
I have a page that I am trying to submit to a PHP script without refreshing/leaving the page. If I use a typical form action/method/submit, it inserts into my database just fine. But when I use JQuery, the JQuery will not run at all. The alert does not show. (I'm new to JQuery). I have tried to research this, but nothing is working.
Here is my main page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('submitpicks').on('submit','#submitpicks',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
</script>
</head>
<body>
<form name="submitpicks" id="submitpicks" action="" method="post">
<script language="javascript">
var v=0;
function acceptpick(thepick,removepick){
var userPick = confirm("You picked " + thepick + ". Accept this pick?");
//var theid = "finalpick" + v;
var removebtn = "btn" + removepick;
//alert(theid);
if(userPick==1){
document.getElementById("finalpick").value=removepick;
document.getElementById(removebtn).disabled = true;
document.getElementById("submitpicks").submit();
v=v+1;
}
}
</script>
<?php
include "Connections/myconn.php";
//$setid = $_SESSION["gbsid"];
$setid = 11;
$setqry = "Select * from grabBagParticipants where gbsid = $setid order by rand()";
$setresult = mysqli_query($conn, $setqry);
$u=0;
if(mysqli_num_rows($setresult)>0){
while($setrow = mysqli_fetch_array($setresult)){
//shuffle($setrow);
echo '<input type="button" name="' . $setrow["gbpid"] . '" id="btn' . $setrow["gbpid"] . '" value="' . $u . '" onClick=\'acceptpick("' . $setrow["gbpname"] . '", ' . $setrow["gbpid"] . ');\' /><br />';
$u=$u+1;
}
}
?>
<input type="text" name="finalpick" id="finalpick" />
<input type="submit" value="Save" />
</form>
<div id="results"> </div>
</body>
</html>
Here is my PHP:
<?php
include "Connections/myconn.php";
$theGiver = 1;
$theReceiver = $_POST['finalpick'];
$insertsql = "insert into grabBagFinalList(gbflgid, gbflrid) values($theGiver, $theReceiver)";
mysqli_query($conn, $insertsql);
?>
you can use e.preventDefault(); or return false;
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault();
$.post('submitpick.php', $(this).serialize(), function(data) {
$('#results').html(data);
});
// return false;
});
});
</script>
Note: in your php you not echo out anything to get it back as a data .. so basic knowledge when you trying to use $.post or $.get or $.ajax .. to check the connection between js and php .. so in php
<?php
echo 'File connected';
?>
and then alert(data) in js .. if everything works fine .. go to next step
Explain each Step..
before everything you should check you install jquery if you use
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
from w3schools website.. its totally wrong .. you should looking for how to install jquery ... then
1st to submit form with js and prevent reloading.. and you used <script> in your main page
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
<script>
output : alert with Form submitted Without Reloading ... if this step is good and you get the alert .. go to next step
2nd add $.post to your code
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
$.post('submitpick.php', $(this).serialize(), function(data){
alert(data);
});
});
});
<script>
and in submitpick.php >>> be sure your mainpage.php and submitpick.php in the same directory
<?php
echo 'File connected';
?>
output: alert with File connected
Have you heard of AJAX(asynchronous javascript and XML). While it may not be something that is easy to learn for someone who is new to JQuery and javascript, it does pretty much what you need. Well, its a bit more complicated than that, but basically AJAX submits information by using HTTP requests (much like normal forms) but without refreshing the page.
Here's a link to a tutorial: http://www.w3schools.com/ajax/ with vanilla javascript.
Here's one with Jquery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
And here's an example of how you can set it up with Jquery:
$(document).ready(function() {
$.ajax({
method: "POST",
url: "/something.php"
dataType: "JSON",
data: {formData:{formfield1: $('formfield1').val(), formfield2: $('formfield2)'.val()}},
success: function(data){
if (data["somevalue"]) == something {
dosomething;
} else {
dosomethingelse
},
error: function() {
alert("Error message");
}
});
});
This is only a basic example, now what does all this stuff mean anyway. Well, there are several methods, some of them are POST and GET, these are HTTP request methods, which you can use to do several things. I'm no expert on this stuff, but here's what they do:
Method
POST
POST basically works, to submit information to a server, which is then usually inserted to a database to which that server is connected to. I believe most forms utilize POST requests, but don't quote me on that.
GET
GET on the other hand requests data from a server, which then fetches it into the database and sends it back to the client so it can perform an action. For instance, whenever you load a page, GET requests are made to load the various elements of a page. What's important to note here, is that this request is made specifically to retrieve data.
There are other types of HTTP requests you can use such as PUT and DELETE, which I'd say are the most common along with GET and POST. Anyway I'd recommend that you look them up, its useful information.
Url
The url represents the path to which you are making a request, I'm not exactly sure how it works with PHP, I think you just need to call the PHP page in question and it will work properly, but I'm not sure, I haven't used PHP since my last semester, been using Rails and it doesn't work quite the same. Anyway, lets say you have some PHP page called, "Something.php" and lets say that somethihng PHP has the following content:
<?php
$form_data = $_POST['data'];
$array = json_decode(form_data, true);
do something with your data;
$jsonToSendBack = "{status: 1}";
$response = json_encode($jsonToSendBack);
echo $response;
?>
So basically what that file received was a JSON, which was our specified datatype and in turn after we finish interpreting data in the server, we send back a response through echo our echo. Now since our datatype is a JSON, the client is expecting a response with JSON, but we'll get to that later. If you're not familiar with JSON, you should look it up, but in simple terms JSON is a data exchange format that different languages can utilize to pass data to each other, like in this example, where I sent data to PHP through Javascript and vice-versa.
DataType
Data type is basically, the type of information that you want to send to the server, you can specify it through ajax. There are many data types you can send and receive, for instance if you wanted to, you could send XML or Text to the server, and in turn it should return XML or text, depending on what you chose.
Success and Error
Finally, there's the success and error parameters, basically if a request was successful, it returns a status code of 200, though that doesn't mean that other status codes do not indicate success too, nonetheless 200 is probably the one you'd like to see when making HTTP requests. Anyway, success basically specifies that if the request succeeded it should execute that function code I wrote, otherwise if there is an error, it will execute the function within error. Finally, even if you do have a success on your request, that doesn't mean everything went right, it just means that the client was successful in contacting the server and that it received a response. A request might be successful but that doesn't generally mean that your server-side code executed everything perfectly.
Anyway, I hope my explanation is sufficient, and that you can take it from here.

Calling PHP function nl2br in html doc

I am working on a site in which I have a user entry field that I would like to insert line breaks after every new line in the user input without making an entirely new php page. Here's my code (js):
var newstreamSummary = document.getElementById("addNewstreamSummaryBox").value;
if(newstreamSummary !== ""){
document.getElementById("previewNewstreamSummary").innerHTML = newstreamSummary;
/* newstreamSummary = <?php echo nl2br(newstreamSummary);?> */
}
That block lives in a js function called showPreview(), when running it says the showPreview() is not defined. It also does not work when I put the php call in a separate <script> tag. I would like to call this function without having a new page as this is the only time in the project where I'm using php currently. Or if there's a js function that does the same thing. Thanks all for any advice.
Php is server side. The only way of using php in that case would be making an Ajax call
to a php script which processes your test and returns this text processed.
There is no need for that in your case. Just add this line after your if statement:
newStringSummay = newStringSummay.replace(/\n/g, "<br>");

Calling PHP script with Cordova

I'm working on an app that's supposed to contain the same information as an already existing website.
What I wanted to do was create a Cordova app that calls an external PHP script which in turn gets information from the database that the website is using.
Right now I'm working on calling the PHP script but it just doesn't seem to work.
Here is the script I'm trying to call:
<?php
$a = 1;
$b = json_encode($a);
return $b;
?>
Ofcourse this is just to test the connection. The URL for this file is http://localhost:8888/get_posts.php
Here is the code for the app:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
$(this).find('.homeText').html(data);
});
});
This fetches the file whenever the page is shown (handy) and then puts the new data into the page. The problem is that the page remains empty at all times, when it should be showing a "1". Can anyone see where it goes wrong?
Error message: XMLHttpRequest cannot load localhost:8888/get_posts.php. Cross origin requests are only supported for HTTP.
UPDATE: The error message dissapeared when adding http:// to the url, but the problem persists.
I've changed the code to:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
alert(data);
});
});
and it shows me an empty alert box.
Solution: Had to use echo instead of return for the script to show me a result.
http:// was also required so the script is allowed to communicate.
You have to 'echo' your response not returning it like so
<?php
$a = 1;
$b = json_encode($a);
echo $b;
?>

Using javascript variable in PHP with ajax [duplicate]

This question already has answers here:
Passing Javascript Variable to PHP using Ajax
(2 answers)
Closed 8 years ago.
I am thinking to use Speedof.me api to find out the user download speed accurately.I will use the value of the download speed to determine which video quality will be used to stream video to the user.
<html>
<head>
<script src="http://speedof.me/api/api.js" type="text/javascript"></script>
</head>
<body>
<h2>SpeedOf.Me API Consumer - Sample Page</h2>
<script type="text/javascript">
SomApi.account = "SOM5380125e96067"; //your API Key here
SomApi.domainName = "domain.com"; //your domain or sub-domain here
SomApi.config.sustainTime = 2;
SomApi.onTestCompleted = onTestCompleted;
SomApi.onError = onError;
SomApi.startTest();
function onTestCompleted(testResult) {
var speed = testResult.download;
}
</script>
<?php
//how can i use the speed variable here
}
?>
</body>
</html>
I am a begineer with javascript and i would like to use the javascript variable in the php as shown above without reloading the page.I know that javascript is executed client-side and php is server-side but from what i read online is that ajax is the way to go.Also is there a way in which i can store the result of speedof.me so that i don't need to run the test every time the same user view a video
Thanks for helping me out guys
you can make an ajax call to server to use the javascript variable in php
function onTestCompleted(testResult) {
var speed = testResult.download;
$.ajax({
url:"link to php script" // e.g test/index.php
type:"POST", //method to send data
dataType:"json", //expected data from server
data:{speed:speed}, //data to send server
success:function(data){
alert(data); //alert response data after ajax call success
}
});
}
on php script you can use that javascript variable speed after checking $_POST[]
echo $_POST['speed'];
passing PHP values to javascript can just be echoed. But javascript to PHP is a bit complicated.
Server scripts like PHP are executed first before Browser scripts (i.e. javascript) do their job. this means, after the page has loaded, your php won't do any good anymore, EXCEPT, you use Ajax requests.
what I use is jquery function .post() (if you're wondering why i use post, you can do your own reading about this functions including .ajax() and .get() )
PHP code somewhere found in /project/execute.php
$speed = $_POST["speed"];
echo $speed * 5;
and in your javascript...
<script type="text/javascript">
SomApi.account = "SOM5380125e96067"; //your API Key here
SomApi.domainName = "domain.com"; //your domain or sub-domain here
SomApi.config.sustainTime = 2;
SomApi.onTestCompleted = onTestCompleted;
SomApi.onError = onError;
SomApi.startTest();
function onTestCompleted(testResult) {
var speedresult = testResult.download;
// here's the magic
$.post("/project/execute.php", {speed:speedresult}, function(result) {
alert(result);
} )
}
PS. DON'T FORGET TO IMPORT JQUERY IN YOUR SECTION OR THE BOTTOM MOST PART OF THE BODY
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
You do not seem to understand the fundamental differences between Clientside and Serverside Code.
The PHP Code will be executed serverside; only the output is sent to the browser. Then the browser executes the Javascript.
One solution to your problem would be to load the video dynamically with Javascript (either per Ajax or a simple video link naming convention). To store the speed test results, use a Cookie.
It doesn't work that way. As you said, JavaScript is client side. Your PHP page is processed by the server first--meaning, all PHP code gets executed first before any of your HTML, CSS, and JS. It doesn't matter if your JS is positioned first before PHP since PHP will get evaluated first. After that, it's sent back to the client for the browser to process HTML, CSS, and JS.
For your case, after running the speed test, send the value back to a PHP script via AJAX. You can use jQuery to make AJAX calls easier. Store a cookie using JS to indicate that the test has been executed once. You'll need to modify your JS so that it will check if this cookie is present and skip the speed test.
try this :-
<?php
echo "<script>alert(speed)</script>";
?>

Categories