I am having some issues running an AJAX request to the php class that contains the AJAX request. The AJAX request is called used a button, and works partially.
My AJAX request is held in a header.php file, which is included in my kpi2.php. If I specify the "url" for the AJAX call to a test file (in the same directory) the POST is successful and I can see the output. I was under the impression if I removed the "url" option it would indeed post to the same page, what am I doing wrong here?
function executeRefresh(){
if (control){
$(".loader").show();
$.ajax({
type: "POST",
data: { refresh: '1' },
success: function(json) {
if(!json.error) location.reload(true);
$(".loader").hide();
}
});
}
}
Output when no url is specified (meaning it should be posted to the same file that is calling the AJAX)
Written from /home/kpi/pages/kpi2.phpArray
(
)
This is the output when I have the option url: "test.php" (which has the exact same output but just in a different file.
Written from /home/kpi/pages/test.phpArray
(
[0] => refresh
)
EDIT:
To obtain the output generated from above, a simple export.
$v1 = print_r(array_keys($_POST),true);
$fp = fopen('../data/output.json', 'w');
fwrite($fp, 'Written from /home/kpi/pages/test.php'.$v1);
fclose($fp);
As for the control variable, it is just a simple listener that is true/false depending if the control key is clicked. It does indeed work and I've never had issues with it before.
As for the location.reload() I tried removing it and now it seems that it isn't even writing the php code now.
Originally in the header.php I had a button on the navbar that would call the AJAX function thus having the kpi2.php (which included the header.php) to have something posted to it. Once it was posted it would then call another php class.
Instead what I did was get rid of the onclick=executeRefresh() and then just listened to the button press specifically in the kpi2.php class. This way I could instantly execute the AJAX request to the other class without the un-needed post request to the class.
$(function() {
$(".btnRefresh").click( function()
{
if (control){
$(".loader").show();
$.ajax({
url:"../setup/kpi_quality.php",
type: "GET",
data: { casp: 'AVANT-CAP-321' }, // name of the post variable ($_POST['id'])
success: function(json) {
//if(!json.error) location.reload(true);
$(".loader").hide();
}
});
}
}
);
});
Related
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
For some reason my jQuery AJAX request submits the first POST successfully, but then it causes a second GET which does not submit the post data, causing a Index Undefined error. When viewing the logs with Firebug, I see it does the first POST successfully posting the data I want to submit, but then it does a second GET request pulling the entire "SecondPage.php" file without posting any data, overriding the DIV it was set to display in.
Here's the code:
$(document).on('change', '.SubmitRadioButton', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'SecondPage.php',
cache: false,
data: $(this.form).serialize(),
success: function(html) {
window.alert('Successfully submitted AJAX request!');
$("#DIVinFirstPage").load("SecondPage.php");
}
});
return false;
});
What am I doing wrong?
Also - I have noticed that on this second PHP page I have to make a reference to my "Header.php" file that performs all the functions. Why is it that with this ajax request, it doesn't inherit all the rules from the page as a PHP include("File.php") does? Is there any way around this so I don't have to re-initialize and re-download all the PHP and JavaScript files? I tried include_once("File.php") in the PHP and that didn't correct it either.
jQuery load is the same thing as doing a $.get request. Is only a wrapper.
.load()
So you are basically doing a post request with some data on this part of the code
$.ajax({
type: 'post',
url: 'SecondPage.php',
cache: false,
data: $(this.form).serialize(),
success: function(html) {
window.alert('Successfully submitted AJAX request!');
And then inside the success making a get request to the same page on this line.
$("#DIVinFirstPage").load("SecondPage.php");
Then the page SecondPage.php is giving you an Index Undefined Error because SecondPage.php is expecting POST data which is not being sent in the .load call.
Since the Index Undefined is a php error, that sends the 500 error code to the browser.
So you need to either check if the variables are set using isset on SecondPage.php or make the load call another page that is not expecting any data.
Another alternative would be to have the script that handles the POST on a separate php file and then do the .load to the second page of your form.
In the success callback of the first POST request, you perform a JQuery load(). According to documentation http://api.jquery.com/load/, "It is roughly equivalent to $.get(url, data, success)".
You see your success callback function has a parameter named "html". That is the response served to your from SecondPage.php after the POST request. I imagine that contains the content you want to populate your div with.
Perhaps try:
success: function(html) {
window.alert('Successfully submitted AJAX request!');
$("#DIVinFirstPage").html(html);
}
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.
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.
I want to make an AJAX call to a php file called functions.php, where I have mutliple related functions (all making database changes to accounts, ie. add, edit, delete). I've been struggling with this, because the AJAX call seems to work fine, but the response that comes back from the server is empty (content-lenght: 0). I went back to square one and just used AJAX to send data to a php file that only contained the php code to handle that one call (ie. no functions), and it works fine. As soon as I wrap that simple statement into a function, it fails again. So something I'm doing causing the php not to send a respone when I'm wrapping it in a function.
Do you have to call a specific php function somehow from your ajax script, or somewhere in your form element? How does the php file know which function you're requesting in your ajax call if there are multiple functions? Or does it just sort it out by matching the $_POST element with the data being sent over, regardless of which function that $_POST element is in?
I suspect that my PHP code is to blame:
function delete_account(){
require(ROOT_PATH . "/inc/database.php");
$deleteAccount = $_POST['accountName'];
try {
$results = $db->prepare("DELETE FROM account WHERE account_id_PK = ?");
$results->bindValue(1, $deleteAccount);
$results->execute();
} catch(Exception $e) {
echo "ERROR: Data could not be removed from the database. " . $e;
exit;
}
return;
}
Also, when I press the submit button and my ajax call is fired off, it immediately returns the success message in the browser, and as I'm watching the Network tab on my google dev tools window, the success message is displayed seemingly before the php file is even loaded. I've tried setting async: false.
Adding AJAX code:
function deleteAccount(){
event.preventDefault();
var accountName = $('.account_name').filter(":selected").attr("name");
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: {accountName:accountName},
async: false,
success: function(response){
$('#results').html(response + " has been deleted.");
}
});
};
If you have multiple functions in your PHP file, then you can do something like:: pass in extra parameter in you jQuery ajax, like:
$.ajax({
url: "some_file.php?action=get_accounts"
}).done(function() {
$( this ).addClass( "done" );
});
and in your PHP file use switch to call appropriate function depending on value of action variable in your ajax, like:
//in PHP
.....
$action = $_GET['action'];
switch ($action) {
case "get_accounts":
//call the function
get_accounts();
break;
case "otherFunction":
....
break;
}