Sending Ajax data to current page - php

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.

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

Self-POST AJAX request

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();
}
});
}
}
);
});

jQuery does 2 loads... and returns 500 error

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);
}

PHP script not echoing data when called via AJAX

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.

Passing the ID to url string via jquery and then picking it by PHP without page refresh?

I want to pass the ID to the urlstring via jQuery without refreshing jQuery and # tag so that I could get the ID via php $_get['ID'] function.
But the problem is that
If I use #, page did not get refreshed, however PHP did pick the ID from url.
If I don't use #, then php do picks the ID but Page get refreshed.
I want to pass an id to php without refreshing the page.
//javascript
function com(id) {
location.href = '#?ID=id'; //by this way way,page doesn't refresh, ID appears in the url string but ID is not picked by PHP as # is there
// location.href = '?ID=id'; this way way, ID appears in the url string , ID is also picked by PHP as # is there.But page get refreshed.
$.ajax({
type: "Post",
url: "getdata.php",
async: true,
cache: false,
success: function(data) {},
});
}​
//php for getdata.php
<?php echo $_GET['ID']; ?>
You need to educate yourself about server-side vs. client-side operations. Javascript is client side. The server (running PHP in your case) knows nothing about what javascript is doing unless you send some information back. This can be accomplished via a page refresh or via ajax (put simplistically).
What you want is ajax which is an asynchronous request that goes back to the server. The server can then handle it and choose to pass information back to the page. Look into jQuery's ajax.
Update based on your updated comment:
function com(id) {
//forget about appending the id. This isn't doing anything.
//You can use it for informational purposes or so that if someone cuts and pastes
//the link you can handle it server side appropriately.
location.href = '#?ID=id';
//instead focus on this call. append your query string to the url
$.ajax({
type: "POST",
url: "getdata.php?ID=12345",
async: true,
cache: false,
success: function(data) {
alert(data); //should alert the id processed by php
},
});
}​

Categories