this is my Ajax function (for polling), wrapped in $(document).ready. Every second, a request should be sent to update.php.
(Note that getParameterByName and arrayIndexExists are my own functions)
(function poll() {
setTimeout(function() {
$.ajax({
url: "../update.php",
method: "POST",
data: {"game": getParameterByName("game")},
dataType: "json",
complete: poll,
success: function(data) {
console.log("Updating");
console.log(data);
}
});
}, 1000);
})();
This is what I have here in update.php:
header('Content-type: application/json');
$game = $_POST["game"];
$returnArray = array();
// do stuff with the data......
echo json_encode($returnArray);
When it works (say 60% of the time), something like this appears in the console every second or so:
But when it doesn't work, nothing appears in the console at all.
Apparently, the request is still being sent, just that there is no response:
I had spent the whole morning yesterday trying to figure out the problem but I don't know what I'm doing wrong and how to get it working 100% of the time. Thanks.
Related
Posting from javascript ajax (which according to alerts it hits correctly and succeeds at) I cannot get the post from my PHP code.
<script>
function SavePlot() {
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
success:function() {
alert("gets here");
}
});
}
</script>
So above it reaches the gets here alert, so it should be posting, however it isnt caught by the below php:
if(isset($_POST['action']) && $_POST['action'] == 'SavePlot') {
echo '<script>alert("Doesnt get here")</script>';
}
I've tried many other answers but couldn't seem to succeed.
First of all, whatever you echo in your php script won't show up automatically in your current HTML DOM.
However, you can retrieve what you've echo-ed in the PHP in your AJAX call:
success: function(response){
console.log(response);
alert("gets here");
}
In your console, you should see:
<script>alert("Doesnt get here")</script>
Try specifying dataType as HTML in your ajax request.
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
dataType : 'HTML',
success:function() {
alert("gets here");
}
});
I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.
I posted a more specific question on this yesterday, but I think my problem is more basic than what I initially asked.
I am trying to use PHP to set a setTimeout() with a wait variable from a database, but any script I echo doesn't work, even if it involves no PHP manipulation. Take a look below.
Here is the ajax call
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
success: function(html)
{
$("#contentWindow").html(html);
}
});
}
// Initial Load
loadContent();
And here is the PHP it receives.
echo '<h1>Upload content to start the show</h1>';
echo '<script>
setTimeout(loadContent, 4000);
</script>';
The is showing, so I believe the ajax and the PHP is working properly. The script works properly when I place it inside the javascript file, but the script won't run when it's echoed to the page.
My problem is the javascript I echo doesn't run. How can I use PHP to send javascript to the user? Why is what I wrote not functioning?
UPDATE: I realized that when I echo script, it echoed to the middle of the body and technically is above where the script file is loaded on the bottom of the body. Can I echo to the bottom of the body?
Here is a workaround:
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
success: function(html)
{
var myArray = html.split("|");
var message = myArray[0];
var counter = parseInt(myArray[1]); //Minor fix
$("#contentWindow").html(message);
startCounter(counter);
}
});
}
function startCounter(counter){
//counter as the value of 1000 milliseconds are equal to 1 second
setTimeout(loadContent, counter);
}
PHP File
$refreshTimer = 1000; //This is a test
echo "Upload content to start the show|".$refreshTimer; //The message and the counter
If you return just the script portion in your php file you can set the dataType in the .ajax call to 'script' and it will execute the returned javascript (http://api.jquery.com/jquery.ajax/)
So:
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
dataType: 'script',
success: function(html)
{
$("#contentWindow").html(html);
}
});
}
// Initial Load
loadContent();
Then in your PHP:
echo 'setTimeout(loadContent, 4000);';
I tried to use ajax requests and response async, but it seems not to work.
I'm sending every second ajax request.
The console should print out "DON'T WAIT" every second and "WAIT5" every 5 Seconds (sleep in php).
But what happens is, that "DON'T WAIT" get logged, then the whole site/script waits 5 Seconds and both messages are logged 5 times.
How can I make this async, so "DON'T WAIT" comes really every second and doesn't wait for the other script ?
//Edit:
This is an example.
The idea is later to Execute a code ( not setInterval ) which need 10 seconds to get the done-status. In this time the other setInterval should work as normal and not waiting !
The sleep as sleep(rand(5,10));
Javascript:
function getProductionStatus() {
jQuery.ajax({
url: "report.sessioncall.php",
dataType: "json",
async: true
})
.done(function(data) {
console.log(data);
});
}
function getProductionStatusLong() {
jQuery.ajax({
url: "report.sessioncall1.php",
dataType: "json",
async: true
})
.done(function(data) {
console.log(data);
});
}
window.setInterval(getProductionStatus, 1000);
window.setInterval(getProductionStatusLong, 1000);
PHP:
<?php
session_start();
sleep(5);
$_SESSION["jobs"] = "WAIT5";
$sessionstatus = json_encode($_SESSION["jobs"]);
echo $sessionstatus ;
?>
AND
<?php
session_start();
$_SESSION["jobs"] = "DONT WAIT";
$sessionstatus = json_encode($_SESSION["jobs"]);
echo $sessionstatus ;
?>
The rule
Ajax requests are asynchronous by default. If you don't change this by using $.ajaxSetup({async:false}), there is no need to write async: true in your ajax request.
The reason for this is, that in the most cases, it's bad practice to make synchronous ajax request, because you can worsen your user experience by preventing your browser to react on user input.
Your specific solution
Just change
window.setInterval(getProductionStatusLong, 1000);
to
window.setInterval(getProductionStatusLong, 5000);
I would not trust this to work.
Instead try something like this - it will not run exactly on the second, nothing will, but it may be closer to what you want
var cnt = 0
function getProductionStatus() {
$.ajax({
url: "report.sessioncall.php",
dataType: "json"
})
.done(function(data) {
console.log(data);
cnt++
if (cnt==5) {
getProductionStatusLong()
cnt=0;
}
else {
setTimeout(getProductionStatus, 1000);
}
});
}
function getProductionStatusLong() {
$.ajax({
url: "report.sessioncall1.php",
dataType: "json"
})
.done(function(data) {
console.log(data);
getProductionStatus();
});
}
$(function() {getProductionStatus()});
Trying to use the values I return from my php yet there are not working properly.
<script type="text/javascript">
$(function () {
$('#delete').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
if (response.success == 'success') {
// fade out the deleted comp
$("#c"+response.computer_id+"").fadeOut("slow");
// remove from the drop down
$("#comp_selection option[value='#c"+response.computer_id+"']").remove();
} else {
alert('Some error occurred.');
}
});
});
});
</script>
I am returning from the php file :
echo json_encode($ajax_result);
which is returning :
{"computer_id":1,"success":"success"}
EDIT: I found a small error in code outside of this where I was returning a different value than expected. All is well and the above was indeed correct to start with.
You should debug using firebug or whatever developer tools you have in your browser - firebug in Firefox is very good for this as you can see the JSON data passed back from the AJAX call.
That said, your issue is that the data is probably under response.d - so look at response.d.success and response.d.computer_id
Maybe the content you are receiving from your PHP server is sent as simple text, and must be sent with the headers set for JSON content:
header('Content-Type: application/json');