Am trying to get progress of file being copied
initially i send a request to copy the file using the below code. once the file is created. i send a response success=1 and start the copying process and also call getProgress
$.ajax({
url:'copyFile.php',
type: 'post',
dataType: 'json',
data: {'data':someData},
success: function(data) {
if(data.success){
progressIndex=setInterval(getProgress, 1000 );
}
},
error:function(err){
console.log(err);
}
});
function getProgress(){
$.ajax({
url:'FileUploadProgress.php',
type: 'post',
dataType: 'json',
data: {'progress':'1'},
success: function(data) {
if(!data.success){
clearTimeout(progressIndex);
}
},
error:function(err){
console.log(err);
}
});
}
FileUploadProgress.php
class FileUploadProgress{
private $filename;
private $progress;
public function setfileProgress($filename,$progress){
$this->filename=$filename;
$this->progress=$progress;
}
function returnProgress(){
if(empty($this->filename) || empty($this->progress)){
echo json_encode(array('success'=>'0'));
}else{
echo json_encode(array('success'=>1,'filename'=>$this->filename,'progress'=>$this-
>progress));
}
}
}
$fileuploadprogress=new FileUploadProgress;
if($_POST['progress']){
$fileuploadprogress->returnProgress();
}
while copying am getting the progress and calling the function setfileProgress
to set the progress. Also in client side i have requested for progress , but wat am getting is success=0 and $this->progress is empty
Am i missing anything in my code. Please let me know
You have to make way to query some datasource to get your progress status.
Like dumping progress status in some DB table or file, etc..
However PHP have some hacks, that works in some enviroment.
Check following docs: Session Upload Progress.
Related
In my dashboard.php I have a Javascript function that is called based on the user clicking a button. When the button is clicked, it calls a JavaScript function called getTeamMembers and values are passed across to it. The values passed across to this function are then sent to a PHP function (which is also located in dashboard.php).
However I am not getting any success and was hoping that someone could guide me on where I am going wrong. I am a noob when it comes to AJAX so I assume I am making a silly mistake.
I know my function is definitely getting the intended variable data passed to it, after doing a quick window.alert(myVar); within the function.
This is what I have so far:
function getTeamMembers(teamID,lecturer_id) {
var functionName = 'loadTeamMembersChart';
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: { functionName: 'loadTeamMembersChart', teamID: teamID, lecturer_id: lecturer_id },
success: function(){
alert("OK");
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
}
);
}
Before calling the desired php function, I collect the sent varaibles just before my php Dashboard class starts at the top of the file. I plan to pass the variables across once I can be sure that they are actually there.
However, when I click the button, nothing can be echo'd from the sent data.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if (!empty($_POST["teamID"]) && !empty($_POST["lecturer_id"]))
{
$teamID = $_POST['teamID'];
$lecturer_id = $_POST['lecturer_id'];
echo $teamID;
echo " is your teamID";
}
else
{
echo "no teamID supplied";
}
}
you else statement in you success function , and that's not how you set fail callback, try the following and tell us what do you see in the console.
function getTeamMembers(teamID,lecturer_id) {
jQuery.ajax({
type: "POST",
url: 'dashboard.php',
dataType: 'json',
data: {functionname: 'loadTeamMembersChart', arguments: [teamID, lecturer_id]},
success: function(data) {
console.log(data);
},
fail: function(error) {
console.log(error);
},
always: function(response) {
console.log(response);
}
});
}
Seems like your function is not returning a success message when getting into the following statement.
if ($result) {
"Awesome, it worked"
}
Please try to add a return before the string.
if ($result) {
return "Awesome, it worked";
}
It can be other factors, but the information you provided is not enough to make any further analysis.
So I am trying to post some some data from one PHP file to another PHP file using jquery/ajax. The following code shows a function which takes takes data from a specific div that is clicked on, and I attempt to make an ajax post request to the PHP file I want to send to.
$(function (){
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
const sha_obj = JSON.stringify({"sha": sha_id});
$.ajax({
url:'commitInfo.php',
type:'POST',
data: sha_obj,
dataType: 'application/json',
success:function(response){
console.log(response);
window.location.replace("commitInfo");
},
error: function (resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
Then on inside the other php file 'commitInfo.php' I attempt to grab/print the data using the following code:
$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);
However, nothing works. I do not get a printout, and the $_POST array is empty. Could it be because I am changing the page view to the commitInfo.php page on click and it is going to the page before the data is being posted? (some weird aync issue?). Or something else? I have tried multiple variations of everything yet nothing truly works. I have tried using 'method' instead of 'type', I have tried sending dataType 'text' instead of 'json'. I really don't know what the issue is.
Also I am running my apache server on my local mac with 'sudo apachectl start' and running it in the browser as 'http://localhost/kanopy/kanopy.php' && 'http://localhost/kanopy/commitInfo.php'.
Also, when I send it as dataType 'text' the success function runs, but I recieve NO data. When I send it as dataType 'json' it errors. Have no idea why.
If anyone can help, it would be greaat!
You don't need to JSON.stringify, you need to pass data as a JSON object:
$(function() {
$(".commit").on('click', function() {
const sha_id = $(this).data("sha");
const sha_obj = {
"sha": sha_id
};
$.ajax({
url: 'commitInfo.php',
type: 'POST',
data: sha_obj,
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(resp, xhr, ajaxOptions, thrownError) {
console.log(resp);
}
});
});
});
And on commitInfo.php, you have to echo string on json format
=====================================
If you want to redirect to commitInfo.php you can just:
$(".commit").on('click',function(){
const sha_id = $(this).data("sha");
window.location.replace("commitInfo.php?sha=" + sha_id );
});
I am trying to use Slim in my project and I am having trouble getting the AJAX call set up correctly:
$.ajax({
url: "/api/addresses/",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: {QID: QID, departmentID: departmentID}
},
error: function(err) {
alert(err.statusText);
},
success: function(data) {
...
My Slim File looks like so:
require_once('Slim3.php');
function loadEndpoint()
{
global $app;
//fetch
$app->post('/addresses', function($request, $response, $args){
$objDB = new DB;
$json = $objDB
-> setStoredProc("canvas_fetch_module_department_addresses")
-> setParam("QID", $args['QID'])
-> setParam("departmentID", $args['departmentID'])
-> execStoredProc()
-> parseXML();
return $response->write($xml);
});
}
I don't even see the AJAX call being made in my console so I assume that is where the problem is. Anything noticeable with the setup?
I've faced same problem using AJAX and SLIM:
Remove '/' from calling URL "/api/addresses"
If there is no error in API I hope this will fix your issue?
Read this for more detail: http://help.slimframework.com/discussions/problems/7071-optional-route-parameters-force-either-or-no-in-urls
I am designing some PHP pages to process forms. In these pages I want to redirect if result is successful or print a message if there was an error. Structure of pages is like this:
$arg = $_POST["arg"];
if (isset($arg)) {
if (function($arg)) {
header ("Location: page2.php");
}
else {
echo "Response was not successfully";
}
}
else {
echo "$arg parameter was not defined";
}
When I need to print messages I use cftoast for JQuery (http://www.jqueryscript.net/other/Android-Style-jQuery-Toaster-Messages-Plugin-cftoaster.html)
To handle all forms I am using this Javascript function:
$(document).ready(function() {
$("#asynchronousForm").submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$("body").cftoaster({content: data});
window.location.href = ""; //Refresh page to clear possible errors
}
})
return false;
});
My problem is, when form redirects, sometimes appears problems like no redirection and shows empty toast, refreshing page with duplicated input fields... How can I solve this problem? I am using JQueryMobile as skeleton of my webpage.
A good way to handle AJAX responses is to use JSON.
It will allow you to send multiples data and do a redirect or show message depending of AJAX result.
In PHP you can use json_encode() to convert and array to JSON.
$arg = $_POST["arg"];
if (isset($arg)) {
if (function($arg)) {
exit(json_encode(array('redirect' => 'page2.php')));
}
else {
exit(json_encode(array('message' => 'Response was not successfully')));
}
}
else {
exit(json_encode(array('message' => $arg.' parameter was not defined')));
}
AJAX:
You just have to add dataType: 'json'.
You can also use $.getJSON()
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(json) {
if ( json.redirect )
window.location.href = json.redirect;
else
$("body").cftoaster({content: json.message});
}
})
I am aware this question has been answered before but I am somehow unable to hit an action within my controller.
Here is the Action
public JsonResult GetUpdate()
{
//get a list of valid elements
var result = getContent();
return Json(result, JsonRequestBehavior.AllowGet);
}
In my script:
$.ajax({
type: 'GET',
url: '#Url.Action("GetUpdate")',
dataType: 'json',
success: function (constraints) {
alert("Application updated");
},
error: function (ex) {
alert('Failed to retrieve update.' + ex);
}
});
Using fiddler I can hit GetUpdate but from the browser the Ajax call fails. Am I correctly accessing the URL?
Update:
The following is the error message:
"NetworkError: 404 Not Found - protocol://localhost:port/Controller/#Url.Action(%22GetUpdate%22)"
The following works through Fiddle:
protocol://localhost:port/Controller/GetUpdate
Razor code (C# and all other server-side script) is only executed from .cshtml files, therefore C# and Razor can't be used in .js files.
'#Url.Action("GetUpdate")' doesn't generate a URL, it's just a string, therefore you are trying to request protocol://domain:port/Controller#Url.Action("GetUpdate") which doesn't exist.
Here's what you can do:
In the .cshtml file you can store the generated URL in a JavaScript variable and pass it to the external JS file.
You can move your external JavaScript to the .cshtml file so you can use Razor.
use a relative string path like /Controller/GetUpdate
I would recommend the first one.
You can try this out,where _ApplicationPath is protocol://localhost:port/
$.ajax({
type: 'GET',
url: _ApplicationPath + "/ControllerName/GetUpdate",
dataType: 'json',
success: function (constraints) {
alert("Application updated");
},
error: function (ex) {
alert('Failed to retrieve update.' + ex);
}
});