Ajax request returns nothing. why? - php

Below is the ajax request.
$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(deleted, undeleted){
if(undeleted == 0) {
alert('All ' + deleted + ' files delted from the server');
} else {
alert(deleted + ' files deleted and ' + undeleted + ' files could not be deleted');
}
}, 'json');
and here goes the delete.php
<?php
if(isset($_POST['deletearray'])) {
$files = $_POST['deletearray'];
$dir = $_POST['dir'];
$deleted = 0;
$undeleted = 0;
foreach($files as $file) {
if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {
$deleted ++;
} else {
$undeleted ++;
}
}
echo json_encode($deleted, $undeleted);
}
return;
?>
Up on running the code it deletes the files successfully but no message displays.
I also tried changing the ajax request as:
$.post('delete.php', {deletearray:deletearray, dir:dir}, function(deleted, undeleted){
alert("php finished");
}, 'json');
still it does not display the message. So i guess something is wrong in the delete.php file. Please help.

First thing-
Use $_POST['deletearray'] instead of $_POST[deletearray]
Second thing-
You cannot return different variables from the PHP scrtipt, every thing you print there is returned in the ajax callback, so just write this-
PHP
json_encode(array('totalDeleted' => $deleted, 'totalUndeleted' => $undeleted));
AJAX
...
function(response){
response=JSON.parse(response);
console.log(response);
}

The best way to do jquery + ajax + php is as next:
jquery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function do_ajax() {
//set data
var myData = new Array();
myData.push({name:'deletearray',value:'deletearray'});
myData.push({name:'dir',value:'dir'});
//ajax post
$.ajax({
dataType: 'json',
url: 'delete.php',
type: 'post',
data: myData,
success: function(returnData) {
if(returnData.undeleted == 0) {
alert('All ' + returnData.deleted + ' files delted from the server');
} else {
alert(returnData.deleted + ' files deleted and ' + returnData.undeleted + ' files could not be deleted');
}
}
});
}
</script>
PHP:
<?php
$myData = $_POST;
if(isset($myData['deletearray']) AND isset($myData['dir'])) {
$files = $myData['deletearray'];
$dir = $myData['dir'];
$deleted = 0;
$undeleted = 0;
foreach($files as $file) {
if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {
$deleted ++;
} else {
$undeleted ++;
}
}
print(json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted)));
exit();
}
?>

You should use json_encode like following:
json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted));
And you have to get vars with data.undeleted and data.deleted
$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(data) {
if(data.undeleted == 0) {
alert('All ' + data.deleted + ' files delted from the server');
} else {
alert(data.deleted + ' files deleted and ' + data.undeleted + ' files could not be deleted');
}
}, 'json');

Related

Ajax sometimes fails to parse the large JSON response

I am calling a PHP service with below ajax code :
jQuery.ajax({
url: 'index.php?option=com_sheet&task=getReportsData',
timeout: 300000,
dataType: "json",
type: "GET",
data: {
'project': projectsStr,
'startweek': startweek,
'endweek': endweek
}
}).done(function(response) {
if (response.success && response.data) {
var projectData = response.data;
if (projectData.projectReportData.length > 0) {
loadDataTable(response.data);
} else {
jQuery('#projectReportData').html("<br/><h2>No Matching Results</h2>");
}
}
}).fail(function(jqXHR, textStatus) {
jQuery(".overlay")[0].style.display = '';
if (textStatus === 'timeout') {
alert('Failed from timeout');
}
alert(textStatus);
});
The php code that provides the response prints the response with :
$data = (object)array_merge(['projectReportData' => $projectReportData]);
header("Content-Type: application/json");
$post_data = json_encode($data, JSON_FORCE_OBJECT);
ob_start('ob_gzhandler');
echo new JResponseJson($data);
ob_end_flush();
jexit();
This ajax works fine sometimes and is able to parse the JSON. But most of the times gives "parsererror".
Below code fetch the data from the DB :
$db = JFactory::getDbo();
$query = "CALL getReportData('" . $startweek . "','" . $endweek . "')";
$db->setQuery($query);
$res = $db->query($query);
$returnArr = [];
$i = 0;
while( $r = $res->fetch_assoc()){
$projectReportData[$i] = $r;
$i++;
}
when i change dataType to text the pointer reaches the .done() but console.log(response) returns a blank.

json - Form success message not showing on successful submission with PHP

I have difficulty in showing success message on form. Its showing all the error messages but not the success message.
On controller file its showing when I comment $this->model_catalog_outofstockquery->addQuery($this->request->post);
but this line is necessary.
On submitting form the entries are successfully loading to the database.
I have already call model from the constructor
My code on controller file is-
public function write() {
$this->load->language('product/outofstock_enquiry');
$json = array();
if ($this->request->server['REQUEST_METHOD'] == 'POST') {
if ((utf8_strlen($this->request->post['name']) < 3) || (utf8_strlen($this->request->post['name']) > 25)) {
$json['error'] = $this->language->get('error_name');
}
if (!filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL)) {
$json['error'] = $this->language->get('error_email');
}
if ((!filter_var($this->request->post['quantity'],FILTER_VALIDATE_INT))) {
$json['error'] = $this->language->get('error_quantity');
}
if (!isset($json['error'])) {
$json['success'] = $this->language->get('text_success');
$data['product_id'] = $this->request->post['product_id'];
$data['product_name'] = $this->request->post['product_name'];
$data['name'] = $this->request->post['name'];
$data['email'] = $this->request->post['email'];
$data['quantity'] = $this->request->post['quantity'];
$data['notify'] = 0;
$this->model_catalog_outofstockquery->addQuery($this->request->post);
}
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
The script on the view file under the form is
<script type="text/javascript"><!--
$('#button-submit').on('click', function() {
$.ajax({
url: 'index.php?route=product/outofstock_enquiry/write&product_id=<?php echo $product_id; ?>',
type: 'post',
dataType: 'json',
data: 'name=' + encodeURIComponent($('input[name=\'name\']').val()) + '&email=' + encodeURIComponent($('input[name=\'email\']').val()) + '&product_name=' + encodeURIComponent($('input[name=\'product_name\']').val()) + '&quantity=' + encodeURIComponent($('input[name=\'quantity\']').val()) ,
data: $("#form-ask").serialize(),
beforeSend: function() {
$('#button-submit').button('loading');
},
complete: function() {
$('#button-submit').button('reset');
},
success: function(json) {
$('.alert-success, .alert-danger').remove();
if (json['error']) {
$('#outofstock_enquiry').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + '</div>');
}
if (json['success']) {
$('#outofstock_enquiry').after('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '</div>');
$('input[name=\'name\']').val('');
$('input[name=\'email\']').val('');
$('input[name=\'product_name\']').val('');
$('input[name=\'quantity\']').val('');
$('input[name=\'product_id\']').val('');
}
}
});
});
//--></script>

Ajax call doesn't work from iPhone app and arduino

I've created an Arduino project wich sends the coordinates to an URL. The URL does some ajax calls. In the browser it works fine, but when I'm trying it with the Arduino it doesn't work. So I tried to do the same thing with an iOS app, but I got the same problem. This is the code on the page that the Arduino and iOS app request.
var directionsService = new google.maps.DirectionsService();
var base_url = window.location;
var received_data = <?php echo json_encode($received_data); ?>;
$.ajax({
url: 'http://gps-tracker.domain.nl/_api/handler.php',
data: { action: 'post', device_id: received_data['device_id']},
type: 'GET',
dataType:"jsonp",
jsonp:"callback",
success: function (response){
var error = [];
var total = response.length;
for (var type in response) {
if(response[type].types == 'area'){
var x = checkInsideCircle(response[type].longitude, response[type].latitude, received_data['longitude'], received_data['latitude'], response[type].reach / 1000);
if(x == false){
// Outside
error.push(true);
}else{
// Inside
error.push(false);
}
}else if(response[type].types == 'route'){
// Check route
checkOnRoute(response[type].start_latitude, response[type].start_longitude, response[type].end_latitude, response[type].end_longitude, response[type].type, response[type]['reach'], type, function(result) {
error.push(result);
if(error.length == total){
if(error.indexOf(false) >= 0){
// Device is inside route or area
outside = false;
}else{
// Send data to database
$.ajax({
url: 'http://gps-tracker.domain.nl/_api/handler.php',
data: { action: 'post', device_id: received_data['device_id'], longitude: received_data['longitude'], latitude: received_data['latitude']},
type: 'GET',
dataType: 'json',
success: function (response){
console.log('good');
},error: function(jq,status,message) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
}
}
});
}
}
},error: function(jq,status,message) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
Here is the code from the handler.php file, that the ajax request requests.
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : false;
// Switch actions
switch($action) {
case 'get':
$callback ='callback';
if(isset($_GET['callback'])){
$callback = $_GET['callback'];
}
$routes = ORM::for_table('gps_tracker_route')
->inner_join('gps_tracker_device', array('gps_tracker_device.device_id', '=', 'gps_tracker_route.device_id'))
->where('gps_tracker_route.device_id', $_GET['device_id'])
->where('gps_tracker_device.device_id', $_GET['device_id']);
if($routes = $routes->find_many()){
foreach($routes as $k=>$v){
$v = $v->as_array();
if($v['status'] == 'on' or strtotime(date('Y-m-d H:i:s')) > strtotime($v['start_time']) and strtotime(date('Y-m-d H:i:s')) < strtotime($v['end_time'])){
$response1[$k] = $v;
$response1[$k]['types'] = 'route';
}
}
}
$area = ORM::for_table('gps_tracker_area')
->inner_join('gps_tracker_device', array('gps_tracker_device.device_id', '=', 'gps_tracker_area.device_id'))
->where('gps_tracker_area.device_id', $_GET['device_id'])
->where('gps_tracker_device.device_id', $_GET['device_id']);
if($area = $area->find_many()){
foreach($area as $k=>$v){
$v = $v->as_array();
if($v['status'] == 'on' or strtotime(date('Y-m-d H:i:s')) > strtotime($v['start_time']) and strtotime(date('Y-m-d H:i:s')) < strtotime($v['end_time'])){
$response2[$k] = $v;
$response2[$k]['types'] = 'area';
}
}
}
if(isset($response1) and isset($response2)){
$response = array_merge($response1, $response2);
}elseif(isset($response1)){
$response = $response1;
}else{
$response = $response2;
}
if ( isset($response) ) {
if ( is_array($response) ) {
if (function_exists('json_encode')) {
header('Content-Type: application/json');
echo $callback.'(' . json_encode($response) . ')';
} else {
include( ABSOLUTE_PATH . '/classes/json.class.php');
$json = new Services_JSON();
echo $json->encode($response);
}
} else {
echo $response;
}
exit(0);
}else{
exit();
}
break;
case 'post':
$_GET['timestamp'] = date("Y-m-d H:i:s");
$record = ORM::for_table('gps_tracker_device_logging')->create($_GET);
$record->save();
$item = ORM::for_table('gps_tracker_device_logging')
->where('id', $record->id);
if($item = $item->find_one()){
$item = $item->as_array();
echo json_encode($item);
}
break;
default:
die('invalid call');
}
Can someone help me?
EDIT
I think it is something with Javascript. I don't know if it's possible to use javascript when a device, like Arduino, makes a http request to a server. Someone know?
I think that it's because you need a Web Browser that supports JavaScript.
I don't work with Arduino, but from what I know it does not have a "real" Web Browser - it can only pull/download data but can't execute the JS part.
For JS to work you need something to run it. That is why it works in a the browser.

Upload a file using AJAX and PHP

I'm trying to make a script to upload files to my server.
What's really bothering me is that the success call is executed though the file is not uploaded.
HTML
<form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
<label>Castellà</label><input name="mapa_es" id="mapa_es" type="file" />
<div id="progressbox_es" style="display:none;">
<div id="progressbar_es">
<div id="statustxt_es">0%
</div>
</div>
</div>
</form>
JS
$(document).ready(function() {
$('#mapa_es').change(function() {
var formData = (this.files[0]);
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
console.log(percentComplete + '%');
//Progress bar
$('#progressbox_es').show();
$('#progressbar_es').width(percentComplete + '%')
$('#progressbar_es').css('background-color', '#6699FF');
$('#statustxt_es').html(percentComplete + '%');
if (percentComplete > 50)
{
$('#statustxt_es').css('color', '#000');
}
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.floor((evt.loaded / evt.total) * 100);
//Progress bar
$('#progressbox_es').show();
$('#progressbar_es').width(percentComplete + '%');
$('#progressbar_es').css('background-color', '#6699FF');
$('#statustxt_es').html(percentComplete + '%');
if (percentComplete > 50)
{
$('#statustxt_es').css('color', '#000');
}
console.log(percentComplete + '%');
}
}, false);
return xhr;
},
url: 'processupload.php',
type: 'POST',
data: formData,
async: true,
beforeSend: function() {
},
success: function(msg) {
console.log(msg);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
and the PHP code in processupload.php
<?php
if (isset($_FILES["mapa_es"]) && $_FILES["mapa_es"]["error"] == UPLOAD_ERR_OK) {
$UploadDirectory = 'mapes/';
if ($_FILES["mapa_es"]["size"] > 5242880) {
echo "File size is too big!";
}
$File_Name = strtolower($_FILES['mapa_es']['name']);
$File_Ext = substr($File_Name, strrpos($File_Name, '.'));
$Random_Number = rand(0, 9999999999);
$NewFileName = $Random_Number . $File_Ext;
if (move_uploaded_file($_FILES['mapa_es']['tmp_name'], $UploadDirectory . $NewFileName)) {
echo 'Success! File Uploaded.';
} else {
echo 'error uploading File!';
}
} else {
echo 'Something wrong with upload!';
}
?>
I will appreciate any help you could give me. Thanks.
EDIT: I followed gtryonp suggestions and I got into more problems.
When I try to var_dump($_FILES) all I get is an empty string.
I also tried to submit the form using $().submit instead on $().change and it worked, I think it may be because of "enctype="multipart/form-data" on the form tag.
Is there any way to achieve it without having to submit the whole form?
Your processupload.php is ending with a die(message) and will be take as a normal program end, so the success event will be fired and the console.log('FILE UPLOADED') will be your response always, even in error cases. Change all your die(message) with echo message, something like:
if (move_uploaded_file($_FILES['mapa_es']['tmp_name'], $UploadDirectory . $NewFileName)) {
echo 'Success! File Uploaded to '.$UploadDirectory . $NewFileName;
} else {
echo 'error uploading File!';
}
...
and change the success function for something that echoes the possible answers to your screen. Something like:
success: function(msg) {
console.log(msg);
},
HAGD

Extracting data from a ajax response

I need to extract the URL's from the php datas, how can i achieve this?
PHP
$query = 'SELECT * FROM picture LIMIT 3';
$result = mysql_query($query);
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url.=$rec['pic_location'].";";
}
echo json_encode($url);
Ajax
<script type="text/javascript">
$(document).ready(function() {
$(".goButton").click(function() {
var dir = $(this).attr("id");
var imId = $(".theImage").attr("id");
$.ajax({
url: "viewnew.php",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert("first: " + arr[0] + ", second: " + arr[1]);
alert(arr[0]);
$(".theImage").attr("src", +arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});
});
});
</script>
the alert message isn't working its just printing H T ( i think these are http://... )
You're returning a string which is not parsed as JSON.
Just add dataType: "json" to the ajax settings.
And since you're reading it as an array in your javascript you should return it like so:
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[] = $rec['pic_location'];
}
You are sending a string in your PHP and expecting an array as response in javascript. Change you PHP to
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[] = $rec['pic_location'];
}
And javascript to
$.ajax({
url: "viewnew.php",
dataType: "JSON",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret[0]);
var arr = ret;
alert(arr);
alert("first: " + arr[0] + ", second: " + arr[1]); // THIS IS NOT WORKING!!!!
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});

Categories