I'm trying to get echoed variable from php and display on the console. I'm using jquery to send data and I know the backend php file script is working fine. Since I want to see the progress and the backend php script echo out the iteration number while the script is running, I'm trying to see how I can get the echoed variable with jquery and display on the console.
I've tried success, onloading but it doesn't seem to work. Any help would be very appreciated. Thank you!
EDIT
$.ajax({
url: location,
type: 'POST',
data:{
iteration:"10",
readsize:"200",
slimdepth:"3",
sourcedirectory:source,
packagepath:MP
},
dataType:'json',
success: function (response) {
console.log("SUCCESS!");
console.log(response);
},
onInteractive:function (response) {
console.log(response.responseText);
},
complete:function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log("Failure!");
console.log(response.responseText);
}
});
So this is how I send the data and backend php script gets the parameters without problems and it runs. Now I can't see anything until php is done running and then it echo everything. In the backend php script, I have iteration number that I want to check and that is the problem since I can't check while it is running but only it is done running.
From what I could understand from your question probably this is what you are looking for.
You are sending data to PHP file with jQuery post or send:
$.post(file.php, {post}, function(data){
});
If you want to log returned data from php in console you must use console.log() function:
$.post(file, {post}, function(data){
console.log(data)
});
and now data will be logged into browser console.
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
I'm new to this community and a beginner with programming. I'm trying to post a JSON data with AJAX to another PHP file and my code is as follow:
--- AJAX code ---
<?php session_start(); ?>
//other codes in between
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
//alert('Transaction completed by ' + details.payer.name.given_name);
alert(data.orderID);
// Call your server to save the transaction
return fetch('/paypal-transaction-complete', {
method: 'post',
body: JSON.stringify({
orderID: data.orderID
})
});
});
var orderid_data = data.orderID;
$.ajax({
url: "test_parse.php",
type: "POST",
data: {'order_ID': orderid_data },
success: function(data){
alert(data);
});
--- PHP code ---
var_export($_POST);
echo $_POST["order_ID"];
I've realised that my $_POST return an empty array.
Any help would be greatly appreciated :)
Since you open [...]test_parse.php directly in your browser, there is no POST-data present anymore, therefor its empty.
The POST-Data is part of the request. If you open it manually in the browser you perform a GET request.
What can you do to see the var_export?
You can use Chrome or Firefox for example both have Developer-Tools which allow you to trace the exact POST-Request you performed via ajax.
For Chome:
Hit F12 to open the Dev Tools
Navigate to Network
Now perform your Ajax-Post-Request and find it in the Network list. By clicking on the requests you will see all details you will need. Most Imporant for you is Response
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 am using $.ajax to get a JSON response from a php script. if i log the data variable from the $.ajax success function it outputs a properly formatted JSON object, however when I try to access properties of the data var it's undefined. here is the php the is being sent back:
echo json_encode(array("status"=>true, "success"=>"Login Success", "message"=>"You have been logged in successfully."));
and here is my ajax call:
$.ajax({
type: "POST",
data: {
login: true,
username: $('#login-username').val(),
password: $('#login-password').val()
},
async: false,
url: "./php/client-login.php",
success: function (data) {
console.log(data.status);
if (data.status) {
console.log(data.success);
displayModal(data.success, data.message, "./js/login-modal-code.js");
} else if (!data.status) {
displayModal(data.error, data.message, "./js/login-modal-code.js");
}
},
error: function (jqXHR, status, responseText) {
console.log(status);
}
});
if i add the dataType: "json" option to the $.ajax call I get a parse error and if i try to do $.parseJSON(data); to access the data in the data var I get and unexpected token error. I'm not really sure what I'm doing wrong, I've used this setup before and it always has worked before but for some reason it isn't now. anyone see where i've gone wrong?
EDIT: forgot to mention here is the response from the php script:
{"status":true,"success":"Login Success","message":"You have been logged in successfully."}
EDIT 2: Here is a screen of my console. the top .length call is the json that was logged from console.log(data) and the bottom one is from the response in chrome dev tools network tab for the response from the php script. they line up perfectly yet the second is showing a length of 93, how can i fix this?
I was reading on jQuery Docs and found that "dataType: jsonp" does not work with sync request, and you're making this kind of request since you have async: false. Turning it on may solve your problem.
Also, give a look at the docs.
Good luck!
So I figured out a workaround for this problem, first I did JSON.stringify on the data followed by JSON.parse and lastly $.parseJSON() to get a javascript object to work with. Not sure why there are 2 invisible characters being added between when it leaves the php script and reaches the $.ajax call so if anyone knows why let me know
I want to begin by saying sorry for asking this question because I know this has been asked a lot on here already. I've search through the site and used Google, and looked at other examples but I can't figure out what's wrong. Running the script with FireBug running shows the POST is sent but nothing gets received. I've posted the code below.
Jquery Code:
$('#studio').submit(function (event) {
$('#formLaunch').click();
$.ajax({
url: 'test.php',
type: 'POST',
data: {
search_var: 'test'
},
dataType: 'html',
success: function (data) {
//$('#result').html(data);
alert(data);
}
});
event.preventDefault();
});
PHP Code:
<?php
$term = $_POST['search_var'];
echo $term;
?>
The end result of the code (once the AJAX request starts working) will process sent variables and echo an image which I want displayed in a DIV box on the page. For starters though just trying to get this basic 'shell' to work properly.
Thanks in advance for any help or direction.
Jeff
Always provide an error function, especially when in development. I suspect you have an error for a response (404, 500, etc). Providing an error function for debugging purposes will help you see this more quickly.
try this
$.post('test.php',{'search_var': 'test'},function(data){
alert(data);
});