Test blocked with CasperJS - casperjs

This is my code:
casper.then(function() {
this.click('.btn-attendee');
this.waitForSelector(
'#form_signup2',
function() {
this.wait(3000, function() {
//El parametro 'INFO' es para que el echo aparezca en color VERDE
this.echo('Existe el popup SIGNUP', 'INFO');
this.capture('signup.jpg', undefined, {
format: 'jpg',
quality: 75,
});
this.echo('pantallazo signup', 'INFO');
this.wait(4000, function() {
this.fill('form#form_signup2', {
'first_name': 'Perico',
'last_name': 'Palotes',
'email': new Date().getTime()+'#testing.es',
'password': '123456'
//Ponemos false porque sino nos haria el SUBMIT del formulario y no queremos eso.
//En el email la pasamos un numero aleatorio para que no de fallo al ejecutar el script varias veces
}, false);
this.evaluate(function() {
document.getElementById('checkbox1').style.display="block";
})
this.click('#checkbox1');
this.wait(1000, function() { this.click('.final_button'); });
this.wait(15000, function() {
this.capture('signup2.jpg', undefined, {
format: 'jpg',
quality: 75,
});
this.echo('pantallazo signup2', 'INFO');
this.wait(1000, function() {
this.echo('Existe el popup del paso2 SIGNUP', 'INFO');
this.wait(2000, function() {
//RELLENAMOS EL FORMULARIO DEL 2º POPUP DE SIGNUP EMAIL
//FORMUARIO FASE 1
this.fill('form#form_step3', {
'user_alias': new Date().getTime()+'Perico',
'town': 'Valencia',
'role': 'uno',
'company': 'testing_company'
//Ponemos false porque sino nos haria el SUBMIT del formulario y no queremos eso.
}, false);
this.wait(2000, function() {
this.capture('form2.jpg', undefined, {
format: 'jpg',
quality: 75,
});
this.echo('pantallazo form2', 'INFO');
//MY PROBLEM
//Here I try to make a this.wait with a this.echo, but if I do get stuck in the test phase ... this.echo('pantallazo signup2', 'INFO')
});
});
});
});
});
});
},
function(){
//El parametro 'ERROR' es para que el echo aparezca en color ROJO
this.echo('error login', 'ERROR')
},
10000
);
});
In the last attempt this.wait I have put in with the other this.wait with this.echo for example, but if I do and I run the script I get stuck here:
this.echo('pantallazo signup2', 'INFO');
That I can do to make this wait another where I have mentioned that the test is not blocked?

Related

Ajax/laravel delete methode work only when i click twice

i'v been searching for 2 days and i didint find an answer , so i made a function to delete a property onclick using ajax. but i have a weird probleme i must click twice on the button to work , i dont know why here is my code :
here is my button :
<a style="cursor: pointer"
id="{{ $i->id }}"
data-name="client/{{ Auth::guard('client')->user()->id }}/proprety"
class="delete tooltip left"
title="Supprimer">
<i class="icon-feather-trash-2"></i>
</a>
and here is my script :
$('table').on('click', '.delete', function() {
var id = $(this).attr("id");
var name = $(this).attr("data-name");
Swal.fire({
title: "Es-vous sûr?",
text: "Vous ne pourrez pas revenir en arrière!",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Oui, supprimez-le!",
cancelButtonText: "Non, annuler!",
reverseButtons: true
}).then(function(result) {
if (result.value) {
$.ajax({
url: "/proprety/" + id,
method: "DELETE",
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
});
Swal.fire(
"Supprimé!",
"Vos données ont été supprimées.",
"success"
)
window.location.href = "/" + name;
// result.dismiss can be "cancel", "overlay",
// "close", and "timer"
} else if (result.dismiss === "cancel") {
Swal.fire(
"Annulé",
"Votre données ont en sécurité :)",
"error"
)
}
});
});
UPDATE : the first button trigger sweetalert , after i confirm on sweetalert for the first time nothing happen , i need to repeat the process and trigger sweetalert again to work
UPDATE 1 : This is my controller to delete property :
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Proprety $proprety
* #return \Illuminate\Http\Response
*/
public function destroy($proprety){
$proprety = Proprety::find($proprety);
Image::where('proprety',$proprety->unique)->delete();
Promotion::where('proprety',$proprety->id)->delete();
$proprety->delete();
return 1;
}
You have to click twice because of the way you wrapped the javascript.
Instead of writing this: $('table').on('click', '.delete', function() { ...
you should write this:
$(document).ready( function() {
$(document).on('click', '.delete', function(){ ...
So your new JS syntax should be
$(document).ready( function() {
$(document).on('click', '.delete', function(){
var id = $(this).attr("id");
var name = $(this).attr("data-name");
Swal.fire({
title: "Es-vous sûr?",
text: "Vous ne pourrez pas revenir en arrière!",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Oui, supprimez-le!",
cancelButtonText: "Non, annuler!",
reverseButtons: true
}).then((result) {
if (result.value) {
$.ajax({
url: "/proprety/" + id,
method: "DELETE",
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
});
Swal.fire(
"Supprimé!",
"Vos données ont été supprimées.",
"success"
)
window.location.href = "/" + name;
// result.dismiss can be "cancel", "overlay",
// "close", and "timer"
} else if (result.dismiss === "cancel") {
Swal.fire(
"Annulé",
"Votre données ont en sécurité :)",
"error"
)
}
});
});
});
EDIT:
here are the syntaxes for done() and fail() functions of sweetalert:
$(document).ready( function() {
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
var url = "{{ route('delete-susomething', ':id') }}";
url = url.replace(':id', id);
var el = this;
var name = $(this).attr('data-name');
Swal.fire({
title: 'Are you sure? <h6>(Page closes in 10 seconds)</h6>',
html: "Blah Blah",
icon: 'warning',
timer: 10000,
showCancelButton: true,
confirmButtonColor: 'green',
cancelButtonColor: '#d33',
confirmButtonText: 'Go ahead',
cancelButtonText: 'Cancel',
}).then((result) => {
if (result.value){
$.ajax({
url: url,
type: 'POST',
data: {'_method':'DELETE', '_token': '{{ csrf_token() }}'},
dataType: 'json'
})
.done(function(response){
swal.fire('Oh Yeah!', "Successfully Deleted.", response.status);
})
.fail(function(){
swal.fire('Damn!', 'Beats me, but something went wrong! Try again.', 'error');
});
}
})
});
});
now in your controller that deletes the item, after deleting, you need to return a response, so add return 1; at the end of the function that handles the deletion.

How to show the detail in a Master-Detail form with Datatables Jquery

I am designing a system with Net Core 5 MVC, I have to show a Master-Detail, I already have the Master view that contains a Datatable, I would like that when clicking on the ID field (according to the image), the view with the detail would be displayed , but I don't know how to call the Detail view.
Header image
The code I have in the master is the following (Controller, JS, View):
This's the controller code:
[HttpPost]
public IActionResult LoadDataGrid()
{
var draw = Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
var sortColumnDir = Request.Form["order[0][dir]"].FirstOrDefault();
var searchValue = Request.Form["search[value]"].FirstOrDefault().ToUpper();
pageSize = length != null ? Convert.ToInt32(length) : 0;
skip = start != null ? Convert.ToInt32(start) : 0;
recordsTotal = 0;
List<VDiagramaMasterModel> ListVDiagramaMasterModel = Singleton.Instance.EntityManager.GetEntities<VDiagramaMasterModel>();
ListVDiagramaMasterModel = (from d in ListVDiagramaMasterModel select d).ToList();
/* Si tenemos una cadena de busqueda */
if (searchValue != "")
{
ListVDiagramaMasterModel = ListVDiagramaMasterModel.Where(x => x.DiagramaId.ToString().Contains(searchValue) ||
x.FechaElaboracion.ToString().Contains(searchValue) ||
x.DiagramaNumber.ToUpper().ToString().Contains(searchValue) ||
x.DiagramaName.ToUpper().ToString().Contains(searchValue) ||
x.StatusProcesoName.ToUpper().ToString().Contains(searchValue)).ToList();
}
recordsTotal = ListVDiagramaMasterModel.Count;
/* Reordenar segun lo solicitado en el Grid */
switch (sortColumn)
{
case "diagramaId":
if (sortColumnDir == "asc")
ListVDiagramaMasterModel = ListVDiagramaMasterModel.OrderBy(x => x.DiagramaId).Skip(skip).Take(pageSize).ToList();
else
ListVDiagramaMasterModel = ListVDiagramaMasterModel.OrderByDescending(x => x.DiagramaId).Skip(skip).Take(pageSize).ToList();
break;
default:
break;
}
return Json(new { draw, recordsFiltered = recordsTotal, recordsTotal, data = ListVDiagramaMasterModel });
}
The Javascript File where I load the Master Datatable
$(document).ready(function () {
filter: true, // Filtrado de datos
info: true, // Resultado de busquedas
processing: true, // Muestra/Oculta la leyenda procesando
scrollX: true, // Scroll Horizontal
select: true, // Permite seleccionar el renglon
ordering: true, // Activa el ordenamiento
autoWidth: false, // Apaga el ancho automatico
scroller: { "loadingIndicator": true }, // Complemento de representación virtual para DataTables para mostrar muchos datos en la pantalla muy rápidamente.
serverSide: true, // Habilitar procesamiento del lado del servidor
deferRender: true, // Habilitar renderizado diferido para cargar con AJAX
responsivePriority: 1,
data: null,
ajax: {
url: "/DiagramaMaster/LoadDataGrid/",
type: "POST",
datatype: "json",
},
columns: [ // Definicion de columnas, ID's
{
data: "diagramaId", name: "diagramaId",
render: function (data) {
/* return "<a href='/DiagramaMaster/Details/" + data + "'>" + ("00000" + data).slice(-5) + "</a>"; */
return "<a href='/DiagramaDetail/Details/" + data + "'>" + ("00000" + data).slice(-5) + "</a>";
/*return "<a href ='#WinModal' data-id='" + data + "' data-bs-toggle='modal' class='btnGrdDetails'>" + ("0000" + data).slice(-4) + "</a>";*/
}
},
{
data: "tipoProcesoId", name: "tipoProcesoId",
render: function (data) {
return ("00" + data).slice(-2);
}
},
{ data: "tipoProcesoName", name: "tipoProcesoName"},
{
data: "fechaElaboracion", name: "fechaElaboracion",
render: function (value) {
var dt = new Date(value).toLocaleDateString('es-MX', { year: 'numeric', month: '2-digit', day: '2-digit' });
return dt; }
},
{ data: "diagramaNumber", name: "diagramaNumber"},
{ data: "diagramaName", name: "diagramaName"},
{ data: "diagramaDescripcion", name: "diagramaDescripcion"},
{ data: "diagramaNotas", name: "diagramaNotas" },
{
data: "totalTelaKilos", name: "totalTelaKilos",
render: $.fn.dataTable.render.number(',', '.', 3, '')
},
{
data: "incluirCuellos", name: "incluirCuellos",
render: function (data, type, row) {
if (data == true) { return '<input type="checkbox" checked disabled>'; }
else { return '<input type="checkbox" readonly>'; }
return data;
}
},
{
data: "incluirEstampe", name: "incluirEstampe",
render: function (data, type, row) {
if (data == true) { return '<input type="checkbox" checked disabled readonly>'; }
else { return '<input type="checkbox" readonly>'; }
return data;
}
},
{ data: "statusProcesoId", name: "statusProcesoId" },
{ data: "statusProcesoName", name: "statusProcesoName" },
{ data: "referenciaId", name: "referenciaId"},
{
data: "actionBar", name: "actionBar", title: "Acción", width: "100px", sortable: false,
render: function (data, type, full, meta) {
return "<button href='#WinModal' id='btnDetails' data-id='" + full.diagramaId + "' data-bs-toggle='modal' type='button' class='btnDetails btn btn-primary btn-sm' title='Ver'><i class='fa-solid fa-file-lines'></i></button> " +
"<button href='#WinModal' id='btnEdit' data-id='" + full.diagramaId + "' data-bs-toggle='modal' type='button' class='btnEdit btn btn-primary btn-sm' title='Editar'><i class='fa-solid fa-pencil'></i></button> " +
"<button href='#WinModal' id='btnDelete' data-id='" + full.diagramaId + "' data-bs-toggle='modal' type='button' class='btnDelete btn btn-danger btn-sm' title='Eliminar'><i class='fa-solid fa-trash'></i></button> ";
}
},
],
order: [[0, 'asc']],
// 0:diagramaId, 1:tipoProcesoId, 2:tipoProcesoName, 3:fechaElaboracion, 4:diagramaNumber, 5:diagramaName
// 6:diagramaDescripcion, 7:diagramaNotas, 8:totalTelaKilos, 9:incluirCuellos, 10:incluirEstampe,
// 11: statusProcesoId, 12:statusProcesoName, 13:referenciaId, 14:actionBar
columnDefs: [
{ visible: false, targets: [1, 6, 7, 11] },
{ searchable: false, targets: [1, 2, 6, 7, 8, 9, 10, 11, 12, 13, 14] },
{ sortable: false, targets: [1, 6, 7, 8, 9, 10, 11, 13, 14] },
{ className: "dt-body-center", targets: [0, 9, 10, 12, 13, 14] },
{ className: "dt-body-right", targets: [8] },
{ "width": "20px", "targets": [0] },
{ "width": "25px", "targets": [3, 9, 10] },
{ "width": "30px", "targets": [2, 13] },
{ "width": "70px", "targets": [8, 12] },
{ "width": "80px", "targets": [4] },
{ "width": "350px", "targets": [5] },
],
// Cargar el Idioma Español //
language: {
url: "/js/language_pack/es-ES.json"
},
});
/* ******************** */
/* Dibujar la DataTable */
/* ******************** */
tableBase.draw()
}); // Fin $(document).ready(function () {});
View to load the master
#* Archivo cshtml para cargar el Maestro #*
<div id="divContainer" class="container-fluid">
<h1>Listado de Diagramas</h1>
<hr/>
<div class="row">
<p><button href="#WinModal" id="btnNew" type="button" asp-action="Create" class="btnNew btn btn-primary btn-md" data-bs-toggle="modal" title="Nuevo Diagrama" ><i class="fa-solid fa-plus"></i> Nuevo</button></p>
</div>
<span class="text-danger">#ViewBag.ErrorMessage</span>
<div class="table table-responsive">
<table id="tableGrid" class="display cell-border"">
<thead style="font-size:12px; color: white; background-color: #2C3E50;">
<tr>
<th>#Html.DisplayNameFor(model => model.DiagramaId)</th>
<th>#Html.DisplayNameFor(model => model.TipoProcesoId)</th>
<th>#Html.DisplayNameFor(model => model.TipoProcesoName)</th>
<th>#Html.DisplayNameFor(model => model.FechaElaboracion)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaNumber)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaName)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaDescripcion)</th>
<th>#Html.DisplayNameFor(model => model.DiagramaNotas)</th>
<th>#Html.DisplayNameFor(model => model.TotalTelaKilos)</th>
<th>#Html.DisplayNameFor(model => model.IncluirCuellos)</th>
<th>#Html.DisplayNameFor(model => model.IncluirEstampe)</th>
<th>#Html.DisplayNameFor(model => model.StatusProcesoId)</th>
<th>#Html.DisplayNameFor(model => model.StatusProcesoName)</th>
<th>#Html.DisplayNameFor(model => model.ReferenciaId)</th>
<th></th>
</tr>
</thead>
<tbody style="font-size:12px;">
</tbody>
</table>
</div>
</div>
#section scripts{
<!-- Para usar las funciones del grid -->
<script src="/js/dtg_config/diagramamaster.js"></script>
}
In order not to extend too much, the Detail is set up in a similar way (View, Controller, JS), but as I mentioned, I don't know how to do it so that when the ID is clicked, it brings me the view with the Detail and puts it in a DataTable, the following code is where I put together the DT of the detail.
// js para configurar la DataTable del detalle
$(document).ready(function () {
/* Nombre del Modelo con el que se trabajara, se */
/* pasa como parametro a la accion del controlador */
//var workingModel = { Name: "CatConsignatarioModel" };
/* *********************************************** */
$('#tableGrid').DataTable({
dom: "lfrtip", // DOM [B]: Butons (PDF, Excel, etc.), [l]:Cantidad [f]:Filtro, [r]:Visualizacion del proceso, [t]:Tabla [i]:Informacion, [p]:Paginación
//buttons: ["copy", "excel"], // Botones de "copy", "excel", "pdf", "csv" y "print"
filter: true, // Filtrado de datos
info: true, // Resultado de busquedas
processing: true, // Muestra/Oculta la leyenda procesando
scrollX: true, // Scroll Horizontal
select: true, // Permite seleccionar el renglon
ordering: true, // Activa el ordenamiento
autoWidth: false, // Apaga el ancho automatico
responsive: true, // Tabla responsiva
lengthMenu: [[50, 100, 150, -1], [50, 100, 150, "All"]],
responsivePriority: 1,
scroller: { "loadingIndicator": true }, // Complemento de representación virtual para DataTables para mostrar muchos datos en la pantalla muy rápidamente.
serverSide: true, // Habilitar procesamiento del lado del servidor
deferRender: true, // Habilitar renderizado diferido para cargar con AJAX
responsivePriority: 1,
data: null,
ajax: {
url: "/DiagramaDetail/LoadDataGrid/", //<<- This is where I don't know how to put the DiagramId
type: "POST",
datatype: "json",
},
columns: [ // Definicion de columnas, ID's
{
data: "diagramaId", name: "diagramaId",
render: function (data) {
/* return "<a href='/DiagramaMaster/Details/" + data + "'>" + ("00000" + data).slice(-5) + "</a>"; */
return "<a href ='#WinModal' data-id='" + data + "' data-bs-toggle='modal' class='btnGrdDetails'>" + ("0000" + data).slice(-4) + "</a>";
}
}
],
// corte la definicion de columnas para efectos de que no se haga tan extenso
});
/* ******************** */
/* Dibujar la DataTable */
/* ******************** */
tableBase.draw()
});

I want to delete data without refreshing whole page using ajax

I am new at Laravel, I am trying to delete data with ajax, when I click to delete button, the page is refreshing but data is deleting perfectly but that should not be reloaded.
Controller
public function destroy($id)
{
$delete = Digitizing::where('id', $id)->delete();
return back();
}
HTML view
<a href="{{route('digitizing.delete',$digitizing->id)}}"
class="btn btn-danger" onclick="deleteConfirmation({{$digitizing->id}})">Delete</a>
<script type="text/javascript">
function deleteConfirmation(id) {
Swal.fire({
title: "Delete?",
text: "Please ensure and then confirm!",
type: "warning",
showCancelButton: !0,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('digitizing/delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
</script>
**Delete wants a get method because you have to give only ID to delete.**
**WEB.PHP**
Route::get('digitizing/delete/{id}','YourController#destroy');
**SCRIPT**
let id = $('#my_id').val();
$.ajax({
type: 'GET',
url: "{{url('digitizing/delete')}}/" + id,
data: {
_token: '{{csrf_token()}}',
},
success: function () {
alert('Successfully Deleted');
}
}).fail(function(){
console.log('problem with route = digitizing/delete');
});

CKEDITOR - create new button in toolbar

I'm trying to create a new button in CKEDITOR toolbar and do something with it but no way...
I haven't any error in my console and nothing appear in the toolbar...
My code :
var textarea = $('#tiny_mce_block').find('textarea');
var textareaId;
$(document).ready(function () {
textareaId = textarea.attr('id'); // Récupère l'ID du textarea pour être transformé par CKEDITOR
ckeditor_init(); // Initialisation de CKEDITOR
});
/*************************
CKEDITOR
************************/
function ckeditor_init() {
CKEDITOR.replace(textareaId, {
removePlugins: 'autosave, elementspath', //, liststyle, tabletools, contextmenu <= à ajouter pour supprimer click droit
language: 'fr',
entities: false,
entities_latin: false,
contentsCss: [
'/css/ckeditor_audio_transcription_v1.css',
'/plugins/bower_components/ckeditor/contents.css'
],
allowedContent: true,
extraAllowedContent: 'show, word',
disallowedContent: 'script, script; *[on*]',
enterMode: CKEDITOR.ENTER_P,
autoParagraph: false,
ignoreEmptyParagraph: true,
toolbar: [
['Bold', 'Italic', 'Underline', '-', 'TextColor'],
['Undo', 'Redo'],
['Find', 'Replace', 'SelectAll'],
['Maximize']
],
on: {
// Register command and button along with other plugins.
pluginsLoaded: function () {
var editor = this;
// Registers a command that applies the style.
// Note: it automatically adds Advanced Content Filter rules.
this.addCommand("alignementCommand", { // create named command
exec: function (edt) {
alert(edt.getData());
}
});
// Add toolbar button for this command.
this.ui.addButton && this.ui.addButton('alignementBoutton', {
label: 'Alignement',
command: 'alignementCommand',
toolbar: 'insert'
});
}
}
});
}
Where is the problem ?
Thank you !

Getting "SyntaxError: JSON.parse: unexpected character" When aparently the response is correct

I'm crazy with this error, I'm traying to make an Ajax login form, this is my code:
My HTML:
<div id='login-box' name='login-box' class='radius-all-tiny'>
<div class='bt-wrapper bt-wrapper-hover'>
<span class='bt-icon bt-icon-hover btn-users'></span>
</div>
<div id='login-banner' name='login-banner'>
" . $content['SESSION_BANNER'] . "
</div>
<div class='radius-all-tiny' id='login-error' name='login-error'>
</div>
<form id='login-frm' name='login-frm' method='post' action='./'>
<input type='text' id='usuario' name='usuario' placeholder='" . $content['SESSION_USER'] . "' />
<input type='password' id='contrasena' name='contrasena' placeholder='" . $content['SESSION_PASS'] . "' />
<div class='submit-wrap'><input class='bt-submit radius-all-medium' type='submit' id='enviar' name='enviar' value='" . $content['CONTACT_FRM_SEND'] . "' /></div>
</form>
</div>
My JS:
<script type='text/javascript'>
$(document).ready(function() {
// FORCE BROWSER NOT CACHE AJAX CALLS
$.ajaxSetup({ cache: false });
// HIDE ERROR DIALOG
$('#login-error').hide();
// LOGIN/OUT BUTTON BEHAVIOR
$('#bt-login').click(function(){
$('#login-error').hide();
$.fancybox.open({
href : '#login-box',
padding : 0,
onClosed : function() { }
});
});
// LOADING ANIMATION
var ajaxload = '<img src=\"../img/components/spinner-dark.gif\" alt=\"" . $content['MAIN_LOADING'] . "\" />';
$('#login-frm').bind('submit', function(){
// AUTHENTICATING...
// VALIDAMOS QUE NO HAYAN CAMPOS VACÍOS
if (($('#usuario').val().length < 1) || ($('#contrasena').val().length < 1))
{
$('#login-error').html('EMPTY');
$('#login-error').show();
return false;
}
// SI NO ESTÁN VACÍOS LOS CAMPOS, ENTONCES VALIDAMOS...
$.ajax({
type: 'POST',
cache: false,
url: '../libs/class.log.in.out.php',
data: {usuario: $('#usuario').val(), contrasena: $('#contrasena').val()},
dataType: 'json',
success: function(data)
{
if (data.success)
{
// ESCRIBIMOS LA VARIABLE DE SESIÓN
// CERRAMOS FANCYBOX
$.fancybox.close();
// RECARGAMOS LA PÁGINA PRINCIPAL
document.location.href = $('#urlactual');
}
else
{
// MOSTRAMOS ERROR DE AUTENTICACIÓN
$('#login-error').html('FAILED_AUTH');
$('#login-error').show();
}
}
});
return false;
});
});
</script>
My class.log.in.out.php:
/////////////////////////////////////////////////
// TRANSPORTADOR DE DATOS
/////////////////////////////////////////////////
$data = array(
'success' => false,
'msg' => 'No se encontró ningún dato...'
);
// SOLICITAMOS LOS VALORES DE CONEXIÓN
$usr = (isset($_REQUEST['usuario']) ? $_REQUEST['usuario'] : 'NULL');
$pwd = (isset($_REQUEST['contrasena']) ? $_REQUEST['contrasena'] : 'NULL');
// VALIDAMOS LOS DATOS
class_exists('Database') || require ('class.database.php');
$resp = "";
$thisstt = false;
// INSTANCIAMOS LA CLASE DE BASE DE DATOS
$dbs = new Database();
$datos = $dbs->logIn($usr, $pwd, "", $thisstt);
if ($thisstt)
$resp = $datos['usuario'];
else
$resp = "" . $datos['error'] . " Usuario: " . $usr . "";
// DEVOLVEMOS EL ESTADO DE LA VALIDACIÓN
$data = array(
'success' => $thisstt,
'msg' => utf8_encode($resp)
);
/////////////////////////////////////////////////
// EMPAQUETADO DE DATOS
/////////////////////////////////////////////////
header("Content-Type: application/json; charset=UTF-8");
echo json_encode($data);
I receive this response from de class.log.in.out.php (Using Firefox's developer tools):
When the authentication fail:
{"success":false,"msg":"Los datos ingresados son incorrectos... Usuario: 123"}
When the authentication is correct:
{"success":true,"msg":"gchinchilla"}
But Firefox says that the Syntax is incorrect, could you help me?
I apologize for my bad english, I'm learning it...
i do not see any need of converting array to object for json_encode.
i will suggest using :
echo json_encode($data);
instead of :
echo json_encode((object)$data);
SOLVED! There was an "codification error", I have converted the PHP file from UTF-8 to UTF-8 Without BOM.
More info here: http://es.wikipedia.org/wiki/UTF-8#Byte_order_mark_.28BOM.29

Resources