jQuery ajax call not triggering success function on Safari 9.1 - javascript

In a project I have a particular ajax call that works fine on PC Chrome/Firefox, but on Safari 9.1 it fails to trigger the success function.
The ajax call:
$('#new_file_form').submit(function(e) {
e.preventDefault();
var form_data = new FormData($(this)[0]);
$.ajax({
url: '/includes/ajax/file-manager.php',
type: 'POST',
data: form_data,
processData: false,
contentType: false,
success: function(result) {
JSON.parse(result);
alert(result);
if (result == true) {
$('#new_file_form').reset;
$('#new_file_modal').modal('hide');
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-info-sign blue"></i>File successfully saved.',
callback: function() {
location.reload();
}
});
} else if (result == false) {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>File not saved.',
callback: function() {
location.reload();
}
});
} else {
bootbox.alert({
size: 'small',
message: '<i class="glyphicon glyphicon-exclamation-sign orange"></i>Whoa! That escalated quickly..',
callback: function() {
location.reload();
}
});
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
This doesn't throw any errors. The file is uploaded and the data inserted into the database, it's just the success function that sits there and seems to be laughing at me.
Based on the returned error in Safari it seems useful to post the file-manager.php code:
if(!empty($_POST['file_name']) && !empty($_POST['file_type']) && !empty($_POST['file_user'])) { // && !empty($_FILES['file'])
$ownerid = $mysqli->real_escape_string($_POST['file_user']);
$ownertype = 1;
$name = $mysqli->real_escape_string($_POST['file_name']);
$visible = $mysqli->real_escape_string($_POST['visible']);
$filetype = $mysqli->real_escape_string($_POST['file_type']);
$ownerid = filter_var($ownerid, FILTER_SANITIZE_NUMBER_INT);
$visible = filter_var($visible, FILTER_SANITIZE_NUMBER_INT);
$filetype = filter_var($filetype, FILTER_SANITIZE_NUMBER_INT);
$cdate = date('Y-m-d H:i:s');
$edate = $cdate;
$u_file_name = $_FILES['file']['name'];
$u_tmp_file = $_FILES['file']['tmp_name'];
$u_file_type = $_FILES['file']['type'];
$u_file_error = $_FILES['file']['error'];
$u_file_content = file_get_contents($_FILES['file']['tmp_name']);
$upload_result = '';
if($u_file_error == 'UPLOAD_ERROR_OK') {
if($u_file_name == '') {
$upload_result = false;
} else {
$sql = "SELECT path FROM filetypes WHERE id = '$filetype'";
$result = $mysqli->query($sql);
$record = $result->fetch_object();
$file_type_path = $record->path;
$extension = end(explode(".", $u_file_name));
if($ownertype == 1) {
$s_file_name = preg_replace("![^a-z0-9]+!i", "-", $name).'-'.date('Y-m-d_H-i').'.'.$extension;
$s_file_dest = LOCAL_BASE_PATH.'/uploads/'.$ownerid.'/'.$file_type_path;
$s_file_location = $s_file_dest.'/'.$s_file_name;
$s_file_path = '/uploads/'.$ownerid.'/'.$file_type_path.$s_file_name;
}
if(!file_exists($s_file_dest)) {
mkdir($s_file_dest, 0755, true);
}
move_uploaded_file($u_tmp_file, $s_file_location);
$sql = "INSERT INTO files (ownertype, owner, type, visible, extension, name, path, cdate, edate) VALUES ('$ownertype', '$ownerid', '$filetype', '$visible', '$extension', '$s_file_name', '$s_file_path', '$cdate', '$edate')";
$result = $mysqli->query($sql);
$upload_result = true;
}
}
echo json_encode($upload_result);
exit();
}
When I alert the ajax result before parsing it, I get a PHP error:
Strict Standards: Only variables should be passed by reference...

Related

how to use network printer for print blade using laravel

i have a bill blade in laravel. i need to print that bill in a particular network printer.Now i use dompdf for stream() but doesnot print . and i have no idea for connecting a printer in the section
<script>
$(document).ready(function() {
$( "#Kitchen" ).click(function(e) {
var orderid = $(e.currentTarget).attr('data-id');
$.ajax({
type: 'POST',
url:"{{url('Send-Order-to-Kitchen')}}/"+orderid,
data:{
"_token": "{{ csrf_token() }}",
},
success: function (data) {
// console.log(data);
toastr.options = {
"closeButton": true,
"newestOnTop": true,
"positionClass": "toast-top-right"
};
toastr.success(data.msg);
},
error: function (xhr) {
if (xhr.status == 401) {
window.location.href = "{{url('staff/login')}}";
}else if(xhr.status == 200){
window.location.href = "{{url('staff/login')}}";
}
}
});
});
});
</script>
public function Sendordertokitchen($id){
set_time_limit(180);
Order::where('id',$id)->update(['status' => 1]);
$order = Order::find(22);
// return view('manager/kitchen_receipt',compact('order'));
$pdf = PDF::loadView('manager/kitchen_receipt', compact('order'));
$file = 'Kitchen_Print_'.$order->token_id.'.pdf';
return $pdf->download($file);
// return response()->json(['msg' => 'Order menus send to the kitchen successfully']);
}

Ajax undefined value in PHP

When I call the function I always get an undefined value, I don't understand what can ruin it.
You are logged in as undefined, Error undefined
Ajax script:
function Submit() {
console.log('asd')
$.ajax({
url: "Server.php",
type: "POST",
dataType: "json",
data: {
name: "Test2",
email: "Test#gmail.com"
},
success: function(data, textStatus, jqXHR) {
console.log("You are logged in as: ", data.name);
$('#user').html("You are logged in as: " + data.name);
},
error: function(request, error, data) {
console.log(arguments);
alert(" Can't do because: " + error + " DATA: " + data);
}
})
}
PHP Script:
<?php
header("Content-type: application/json; charset=utf-8");
$errors = [];
$data = [];
if (empty($_POST['name'])) {
$errors['name'] = 'Name is required.';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email is required.';
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name'];
}
echo json_encode($data);
?>
I tried every solution in vain, so I still get an indefinite value. I’m slowly starting to think there’s nothing wrong with the script.
You want to use data.name but you never return name. hence the undefined.
I've added data.name in the example below and it seems to work fine.
<?php
header("Content-type: text/html; charset=utf-8");
$errors = [];
$data = [];
if (empty($_POST['name'])) {
$errors['name'] = 'Name is required.';
}
if (empty($_POST['email'])) {
$errors['email'] = 'Email is required.';
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name'];
}
echo json_encode($data);
?>
Also the parameters used in the succes function are in a different order than you seem to use, in your case the request will have your data in it
the callback parameter not
success:function(request, data, error)
but
success: function(data, textStatus, jqXHR)
data.name of course undefined because it is string
and your Server.php return this
{"success":true,"message":"Success!"}
no data.name but data.success and data.message
so you have to write
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
$data['name'] = $_POST['name']; // add this
}

Bootstrap treeview nodes do not expand

I have a problem with a specific bootstrap treeview, I have tried everything but the node does not expand, I use ajax request through a load file where I retrieve the information coming from the database, the data appears normally, the only one I have already tried all the methods that the treeview bootstrap provides, but it returns that it does not know the method used, below I will send the specific code that I use.
Function that calls a tree:
var levelTree = 2;
function getTree() {
var data = '';
$.ajax({
url: 'atividades/atividades_load.php',
data: {idObraAtiva: <?php echo $idObra; ?>},
async: false,
dataType: 'json',
type: 'post',
beforeSend: function () {
},
success: function (retorno) {
data = retorno;
console.log(retorno);
},
error: function () {
bootbox.alert('Erro, contate o suporte!');
}
});
return data;
}
$('#atividadeTree').treeview({
data: getTree(),
levels: levelTree,
backColor: "#C4E3F3",
onNodeSelected: function (event, data) {
if (data.qtdfilhos == 0) {
$('#table_Andamento').bootstrapTable('refresh', {url: 'atividades/atividade_andamento_load.php?q=' + data.id});
}
$('#table_AtividadeFilha').bootstrapTable('refresh', {url: 'atividades/atividade_filha_load.php?p=' + data.id});
$('#fmAndamento_idatividade').val(data.id);
$('#fmAtividadeSub_idAtividade').val(data.id);
},
onNodeExpanded: function (event, data) {
$.ajax({
url: 'atividades/atividades_load.php',
data: {idObraAtiva: <?php echo $idObra; ?>,idNo:data.id},
async: false,
dataType: 'JSON',
type: 'POST',
beforeSend: function (){
},
success: function (filho){
$('#atividadeTree').treeview('addNode',[filho, data.id,
{silent: false} ]);
console.log(filho);
},
error: function () {
bootbox.alert('Erro, contate o suporte!');
}
});
}
});
Function that calls the data, and reorganizes the treeview
<?php
include('../../sessao.php');
require_once('../../J3_FrameWork/Conexao.php');
function getItemPai($_arrLista, $_id)
{
foreach ($_arrLista as $item) {
if ($item->id == $_id) {
if (!property_exists($item, 'nodes')) $item->nodes = array();
return $item;
}else
if (property_exists($item, 'nodes')) {
if (is_array($item->nodes)) {
$aux = getItemPai($item->nodes, $_id);
if ($aux != null)
return $aux;
}
}
}
return null;
}
$idObra = $_REQUEST['idObraAtiva'];
if (isset($_REQUEST['idNo'])) {
$idNo = $_REQUEST['idNo'];
}else{
$idNo = -1;
}
$conexao = Proxy::mrObra();
$param = array("_parameters" => array($idObra, $idNo));
$resultado = $conexao->comando('GetAtividadesArvore', json_encode($param));
$resultado = json_decode($resultado);
$lista = $resultado->result[0];
$listanova = array();
foreach ($lista as $item) {
$novoitem = new stdClass();
$novoitem->id = $item->ID;
$novoitem->text = $item->DESCRICAO. ' - ' .$item->QTDFILHOS;
$novoitem->qtdfilhos = $item->QTDFILHOS;
$novoitem->valor = $item->VALOR;
$novoitem->qtdativsub = $item->QTDATIVSUB;
if($item->QTDFILHOS > 0)
{
$novoitem->nodes = array();
}
if ($item->IDPAI == -1) {
array_push($listanova, $novoitem);
} else {
array_push($listanova, $novoitem);
}
}
echo json_encode($listanova);
?>
Função que chama os dados, e reorganiza a treeview
<?php
include('../../sessao.php');
require_once('../../J3_FrameWork/Conexao.php');
function getItemPai($_arrLista, $_id)
{
foreach ($_arrLista as $item) {
if ($item->id == $_id) {
if (!property_exists($item, 'nodes')) $item->nodes = array();
return $item;
}else
if (property_exists($item, 'nodes')) {
if (is_array($item->nodes)) {
$aux = getItemPai($item->nodes, $_id);
if ($aux != null)
return $aux;
}
}
}
return null;
}
$idObra = $_REQUEST['idObraAtiva'];
if (isset($_REQUEST['idNo'])) {
$idNo = $_REQUEST['idNo'];
}else{
$idNo = -1;
}
$conexao = Proxy::mrObra();
$param = array("_parameters" => array($idObra, $idNo));
$resultado = $conexao->comando('GetAtividadesArvore', json_encode($param));
$resultado = json_decode($resultado);
$lista = $resultado->result[0];
$listanova = array();
foreach ($lista as $item) {
$novoitem = new stdClass();
$novoitem->id = $item->ID;
$novoitem->text = $item->DESCRICAO. ' - ' .$item->QTDFILHOS;
$novoitem->qtdfilhos = $item->QTDFILHOS;
$novoitem->valor = $item->VALOR;
$novoitem->qtdativsub = $item->QTDATIVSUB;
if($item->QTDFILHOS > 0)
{
**$novoitem->nodes = array();**
}
if ($item->IDPAI == -1) {
array_push($listanova, $novoitem);
} else {
array_push($listanova, $novoitem);
}
}
echo json_encode($listanova);
?>

AJAX - JSON Error

When I am trying to receive data from the server side, error I am getting:
06-30 11:23:57.119: I/chromium(7486): [INFO:CONSOLE(50)] "{"readyState":4,"responseText":"","status":404,"statusText":"Not Found"}", source: file:///android_asset/www/js/index.js (50)
JS file:
$j.ajax({
type: 'POST',
url: 'http://www.myrandomurl.com/SupportData/login.php',
crossDomain: true,
data: {email: e, password :p},
dataType: 'json',
async: false,
success: function (response){
//alert ("response");
//alert(JSON.stringify(response));
//console.log(JSON.stringify(response));
if (response.success) {
myApp.alert("you're logged in");
//window.localStorage["email"] = e;
//window.localStorage["password"] = p;
console.log(window.localStorage["email"]);
//localStorage.removeItem('email');
mainView.router.loadPage('main.html');
} else {
myApp.alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
//myApp.alert('Could not connect to the database' + error);
console.log(JSON.stringify(error));
//window.location = "index.html";
}
});
PHP side:
$sql = "SELECT login_id, email_id, password FROM login WHERE email_id='$myusername' and password='$mypassword'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$row = mysql_fetch_array($result);
if($num_rows == 1) {
$response['success'] = true;
}else {
$response['success'] = false;
}
echo json_encode($response);

Ajax 200 Success/failed execution

I have an issue with ajax and I am kinda new at this. The issue that I am having is even if log in fails ajax is still running the success block of code. How do I direct the code to return a failed status.
I'm not asking for you to inspect my code just more as a reference. I just need to know how to tell my code to send anything other than a 200 for okay so that I can display the errors on the screen.
I type in false information and the ajax thinks that the login happened but it really didn't.
AJAX Section
jQuery(document).ready(function(){
document.body.style.paddingTop="3px";
$('a[href^="#fallr-"]').click(function(){
var id = $(this).attr('href').substring(7);
methods[id].apply(this,[this]);
return false;
});
var methods = {
login : function(){
var login = function(){
var username = $(this).children('form').children('input[type="text"]').val();
var password = $(this).children('form').children('input[type="password"]').val();
var remember = $(this).children('form').children('input[name="remember"]').val();
var token = $(this).children('form').children('input[name="token"]').val();
if(username.length < 1 || password.length < 1 || token.length < 1){
alert('Invalid!\nPlease fill all required forms');
console.log(token)
} else {
var data = {
username: username,
password: password,
remember: remember,
token: token,
}
$.ajax({
type: "POST",
url: "login.php",
data: data,
dataType: "text",
success: function(data){
$('#error').append('Success');
// $.fallr.hide();
// window.location.href = "http://www.bettergamerzunited.com/members/";
},
error: function(data) {
$('#error').append('falied');
}
});
}
}
$.fallr.show({
icon : 'secure',
width : '400px',
content : '<h4 class="titles">Login</h4>'
+ '<span id="error"></span>'
+ '<form>'
+ '<input placeholder="Username" name="username" type="text"/'+'>'
+ '<input placeholder="Password" name="password" type="password"/'+'>'
+ '<input type="checkbox" name="remember" type="remember"/'+'> Remember Me'
+ '<?php echo $hidden; ?>'
+ '</form>',
buttons : {
button1 : {text: 'Submit', onclick: login},
button4 : {text: 'Cancel'}
}
});
}
};
});
Login Section
require 'core/init.php';
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = New Validate ();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
if ($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
$response = $login;
echo $response; // <-- Im going to have an if statement that determines if $login was true or false. But testing still.
} else {
foreach ($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
This is the class that handles the login.
public function login($username = null, $password = null, $remember = false) {
if(!$username && !$password && $this->exists()) {
Session::put($this->_sessionName, $this->data()->id);
} else {
$user = $this->find($username);
if($user) {
if($this->data()->password === Hash::make($password, $this->data()->salt)) {
Session::put($this->_sessionName, $this->data()->id);
if($remember) {
$hash = Hash::unique();
$hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));
if(!$hashCheck->count()) {
$this->_db->insert('users_session', array(
'user_id' => $this->data()->id,
'hash' => $hash
));
} else {
$hash = $hashCheck->first()->hash;
}
Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
}
return true;
} else {
try{
throw new Exception('The Username or Password combination doesn\'t match. \n Please try again.');
} catch(Exception $e) {
echo $e->getMessage();
}
}
} else {
try{
throw new Exception('The Username you provide does not match anything in our system. Please Try again or Register.');
} catch(Exception $e) {
echo $e->getMessage();
}
}
}
return false;
}
You can add below code for ajax error section ..in this way you will get idea of what's exactly is error and can debug it.
error:
function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
}
Use the PHP header function.
header('HTTP/1.0 403 Forbidden'); // or whatever status code you want to return.
There can be nothing else outputted before using the header function.

Categories

Resources