PHP script not echoing data when called via AJAX - php

I have been staring at this problem for the past 2 hours and can't seem to fathom it, even after validating that everything loads correctly when scouring the console.
I basically have two sliders on my page which will eventually populate results in a table, every time I change my slider I send an array of two values to my AJAX script:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
The browser successfully finds update_results.php but it does not perform the logic on the page ( I assume it has found the page as the 404 error does not appear in my console. )
At this point in time the script is extremely bare-bones as I'm obviously trying to establish communication between both files:
<?php
$vals = $_GET['values'];
echo $vals;
In this case $vals is never echoed to the page, am I missing something in my AJAX? I know the values enter the function as alerted them out before attaching the PHP script.

Ajax Calls are suffering from Browser Cache. If your browser thinks, that he already knows the content of update.php, he will return the cached content, and not trigger the script. Therefore your
modified code might simply not get executed. (Therefore your insert query wasn't executed)
To ensure this is not happening in your case, it is always a good idea to pass a parameter (timestamp) to the script, so your browser thinks it's another outcome:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?random_parameter=" + (new Date().getTime());
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
This will ensure that - at least - the browser cache is refreshed once per second for update_results.php, no matter what browser cache-settings or server-side cache advices are telling.

when Ajax is done, the success callback is triggered and the output of you php script is saved in data.
you can handle the data like this:
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
dataType: "text",
success: function(data) {
document.write( data )
}
});
PHP, running at server, is unaware of what happening at the front-end browser and it simply respond to ajax request as any other normal http request. So the failure of SQL query has nothing to do with javascript, which only responsible for sending ajax request and receiving and handling the response. I guess there's some errors in your php script.

Related

PHP: Assigning an AJAX response value into PHP Variable

I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing

Sending Ajax data to current page

I've got some data that will be used as part of an image gallery but I don't want to refresh the page between loading the data (there are interface items that I wish to stay visible). However when I submit the data to the same page via ajax JS registers a successful execution of the code (the alert box shows up) but PHP fails to harvest the data.
My JQuery looks like this
$(".gallery_thumbnail").click(function(){
var id=$(this).attr("data-id");
$.ajax({
type: "GET",
url: "test.php",
data: {newid:id},
dataType: 'text',
success:function(result){
// Test what is returned from the server
alert(result);
}
});
});
And my PHP looks like this\
if(isset($_GET['newid'])){
echo "success";
}
else{
echo "fail";
}
I've seen similar questions and tried copy and pasting the answers but I can't seem to get this to work. I've also tried for the url parameter:
http://localhost/test.php and simply removing the url parameter altogther.
Check if the request is ajax, then do the ajax processing
// this code should go before any of the web page code
if (isset($_GET['ajax'])){
if(isset($_GET['newid'])){
echo "success";
}
else{
echo "fail";
}
exit;
}
set a param to see if it is an ajax request
$.ajax({
type: "GET",
url: "test.php",
data: {newid:id, ajax: 'true'},
dataType: 'text',
success:function(result){
// Test what is returned from the server
alert(result);
}
});
I think the problem is that you're a little mixed up about what you're trying to accomplish here or how you should do it.
Try
if(isset($_GET['newid'])){
// Do whatever you want when the script gets an AJAX request
// You want to exit early to avoid having the whole page show up in the alert()
exit;
}
// Your normal, non-AJAX PHP code goes here
Note that your page is coming back in its entirety in the alert() because you aren't exiting early, which you probably want to do for an AJAX response. The way you have it setup, the whole page is sent back as if you're requesting it from a browser viewport.

Sending multiple variables in ajax

I have the following ajax request:
var value = $.ajax({
type: "POST",
url: "url.php",
data: { $(someform).serialize(), something: test_number },
cache: false,
async: true
}).success(function(data){
alert("success!");
}).error(function() {
console.log("FAILED");
});
But it is logging FAILED although the url is right. What happens is that the page refreshes the page and the php query isn't done. I guess there are no errors within the url... any idea on why this happens?
You are kind of mixing methods to send your POST data. You can't serialize a query strong and then also append additional data to it using javascript object construct. You will likely need to manually append the last data element to the query string like this:
data: $(someform).serialize() + '&something=' + encodeURIComponent(test_number),
Of course there could still be a problem on the server-side script which is causing a non-200 HTTP response code (and triggering error handler). You just need to fix this first, and if you still have a problem, debug the server-side issue.

How to execute multiple HTTP Request to the same page from the same client

I want to run some AJAX calls at the same page from the same client.
Ajax calls start correctly but the server queued the requests and execute jsut one per time.
I've also check the start request time and the returned message time.
Studying the second one there's a difference between the requests which is multiple than the before request.
Help me please!
$("document").ready(function() {
$(".user-id").each(function() {
var id = $(this).html();
getData(id);
});
});
function getData(id) {
$.ajax({
url: 'loadOperatorDiagram.php',
type: 'GET',
data: {id: id},
async: true,
cache: false,
success: function(resp) {
$("#boxes").append(resp);
draw(id); // A javascript function which draw into a canvas
}
});
}
loadOperatorDiagram.php get some queries and its execution time is about 5 seconds. The first one ajax request response after 5 seconds, the second one after 10 and so on. But everyone starts asyncronusly and correctly with a difference of few milliseconds
If you are using sessions in php (sounds like it, otherwise you could do at least 2 simultaneous requests...), you should close it as soon as possible in your php script as php will block the session.
Just use session_write_close(); as soon as you have what you need from the session.

Jquery ajax error - Requests adding GET var

My ajax function has stopped working all of a sudden.
function get_file_info()
{
$.ajax({
type: "GET",
url: "http://localhost/includes/get_file_info.php",
dataType: "json",
jsonp: false,
jsonpCallback: "callbackName",
success: function(data) {
return data;
}
});
}
I did some debugging and found that the ajax request is going to
http://localhost/includes/get_file_info.php?_=1297356964250
I am just would like to know what it is and can be used for, also how to remove so the ajax request is like below so it works again.
http://localhost/includes/get_file_info.php
Many Thanks
If you add:
cache: true,
to your call it will remove the timestamp which is there to always call a different URL's so the browser doesn't cache the result. This is standard for calls except for datatypes script and jsonp.
As others have stated though, it would be good to change the server side to stop turning away anything with GET's, maybe check if the get is a _ and only numeric, if not then turn it away...
The "_=1297356964250" query string is jQuery's method of preventing the URL being cached and returning an old result. Adding this ensures that you're retrieving a new response every time.
This is not the cause of your request breaking down. It must be from another issue. Have you tried logging your response and seeing what it returns?
success: function(data) {
console.log(data);
}

Categories