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.
Related
I want to do a simple ajax post request to another page, with the same code I've another time, but this time it does not seem to work, even though the alert I put at success works. The variables do not seem to transfer, but even disregarding the variables and used putting a simple request on the other page does not seem to help. This is my code now:
<script>
$(function(){
$('.sortable').sortable({
stop:function()
{
var ids = '';
$('.sortable div').each(function(){
id = $(this).attr('id');
if(ids == '')
{
ids = id;
}
else
{
ids = ids+','+id;
}
}),
$.ajax({
url:'<?php $_SERVER["DOCUMENT_ROOT"]. "inhoud/dashboard/change_order.php"?>',
data:{ids: ids, user_id: '<?php echo $user_id; ?>'},
type:'POST',
success: alert('yay')
});
}
});
});
</script>
Everything in the script seems to work. The ids array fills exactly how it is supposed to be, and also the user_id is rightly defined. I have tried every way to link to the document, but every way seems to fail. What is supposed to happen is that the call to the other page gets made, where the data given in the post requested is handled, but even though almost exactly the same code works in multiple other scenarios, this time it seems to fail.
You need to add a function inside the success
like this ->
success: function(){ alert('yay'); // do something }
I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>
I'm working on a like system with PDO, PHP and AJAX.
But, its not working.
Here's the PHP Code.
$get_likes_sql = "SELECT * FROM `likes` WHERE post_id=:post_id AND liker_id=:my_id";
$get_likes = $db->prepare($get_likes_sql);
$get_likes->execute(array(
":post_id" => $post_id,
":my_id" => $my_id
));
$likes_numrows = $get_likes->rowCount();
if ($likes_numrows == 0) {
echo "<a class='like-link' id='$post_id' title='Like'>Like</a>";
} else {
echo "<a class='like-link' id='$post_id' title='Unlike'>Unlike</a>";
}
Here's the AJAX script.
$(document).ready(function(){
$(document).on('click', '.like-link', function(){
if($(this).attr('title')=='Like'){
$.post('ajax.like.php',{pid:$(this).attr('id'),action:'like'},function(){
$(this).text('Unlike');
$(this).attr('title','Unlike');
});
}else{
if($(this).attr('title')=='Unlike'){
$.post('ajax.like.php',{pid:$(this).attr('id'),action:'unlike'},function(){
$(this).text('Like');
$(this).attr('title','Like');
});
}
}
});
});
The Problem is that nothing happens after clicking on like link neither on unlike link.
This is where debugging comes into place. First off, let's see if the AJAX call succeeds. Put in console.log('foo'); statements, with different strings to trace what the JavaScript code does. If the AJAX call is being made, you should be able to see it in the debugger as well.
After that, you should be able to see the results going into the PHP script. You can dump the variables at the top var_dump($_POST);exit;.
There should also be some code where the $_POST variable is linked to $post_id and $my_id.
Since this isn't the complete code example, I can only help you this much. Please let us know if you managed to debug it. Else the complete code example would be nice for us to help you out some more.
use Console.log function to see which part of your code is executed and which is not
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>";
?>
I have this JS function and I'm looking for the simplest way to send a variable to php and have php return an array to my JS. I have the second part down I just need help sending the variable. Here's my function:
function myEvent(){
//console.log(uploaded);
var length = uploaded.length;
var content = document.getElementById("Profile");
if(length == 0){
content.innerHTML = '<p style="text-align:center"><b> You uploaded no events. </b></p>';
}
else {
content.innerHTML = " ";
for(var i=0; i<length;i++){
var entry = document.createElement('li');
var EID = uploaded[i][0];
entry.innerHTML= ''+uploaded[i][1]+'';
content.appendChild(entry);
}
return false;
}
}
I want to be able to send EID which is a unique ID to a PHP script every time I click the link.
Any help? I'm using Jquery but I'm not too familiar with it. If there's an option using JS alone I would really appreciate it.
You can do that using Ajax. There's also another really simple way to send data to a php script on any server (same domain or not) while making that php script interact with your page
first you create a script tag:
var tag = document.createElement('script');
the src of that tag will be the url of the php script that will receive the variable:
var myVar = 'foo';
tag.src = '/path/to/my/script.php?variable='+myVar;
you add the script tag to the dom to request it
document.getElementsByTagName('head')[0].appendChild(tag);
on the server side the php script receives the variable and does whatever it should do with it, and optionally it can echo any javascript that will run on the page afterwards:
<?php
echo "alert('".$_GET['variable']."')";
that's pretty much it, WARNING, be aware that this is just a simple example, to implement something like this on a production site you need to make sure that doing so won't open your site to XSS attacks, code injection etc... how to do that is beyond what is being discussed here but be aware
Make sure you view this using firebug, or anything similar in order to see the returned results, in the jquery done function you can then do data[0], etc for the arrays
html
<!DOCTYPE html>
<html>
<head>
<title>JQuery Test</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="myjs.js"></script>
</head>
<body>
<button id="sendData">Send Data</button>
</body>
</html>
JS
$(document).ready (function (){
$("#sendData").on ("click", function (){
jQuery.ajax ({
url: "index.php",
type: "POST",
data: {returnArray: 1}
}).fail (function (){
console.log ("failed");
}).done (function (data){
console.log (data);
});
});
});
PHP
if (isSet ($_POST ['returnArray']))
{
$a = array ("a", "b", "c", "d");
header('Content-type: application/json');
echo json_encode ($a);
exit;
}
I am sure you can figure this out... show some effort.. and don't be afraid to ask if you still don't understand.. just as long as you try.
Use JavaScript's XMLHttpRequest to send a message to the server running PHP. When the PHP script responds, the XMLHttpRequest object will let you know and you'll be able to grab the XMLHttpRequest.responseText.
It would be a good idea to have PHP respond with JSON, which it can do easily. Then you can parse the responseText with JavaScript's JSON.parse function and just use it.
The following two articles will show you how to use the standard objects.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
http://www.php.net/manual/en/function.json-encode.php
You'll just have to be sure you don't try talking to a different website than the one your page is loaded from, unless you want to learn all about cross domain requests.