Function inside element event JS with an UploadControl from devexpress - javascript

I want to validate a response that my JsonResult gives in the controller side, but I don't know in which way I can do it, because I do not use ajax to connect with the controller in this scenario,also Im using an element from devexpress, and I don't know how I could be able to handle a validation inside the event:
//Here is the function that saves the file, I validate the file in the controller
function GuardarImg(s, e) {
UploadControlImagen2.UploadFile(function (data) {
//Here I want to show an alert deppending on the respons
if (data == 2) {
return swa({ title:'Imagen no soportada',text:'La imagen debe de ser de un tamaño minimo de 500x500px y no superior a 1500x1500px',icon:'warning'})
}
})
}
here is the normal code without the try of validation that I made
function GuardarImg(s, e) {
UploadControlImagen2.UploadFile()
}

Related

Codeigniter Can't change view page

I need your help with an issue that is dragging me crazy.
You have to know that My view page has 4 view pages called: Header, Menu, Sub menu and Content and I'm using SQL database to store the information the user fill in Content.
I want to change Content page after the user hit submit button.
The submit button will call a JS that arranges the information into an array and call a controller function that call a database function and fill the table and send a TRUE if the table was filled. After all that code, I take the created array and TRUE and send it to a new Content view and display the information that the user filled and tell him "upload success".
The main problem is the new content view isn't showing, I checked the database and the information is uploaded. This is part of the controller function that is sended to the database.
This is the Javascript, i'm using ajax.
$("#btn_enviar").click(function(){
var r = confirm("Los datos ingresados no podran ser modificados una vez enviados, presione aceptar si desea continuar");
if (r == true){
var url = base_url + "/inventario/insert_inventario";
$.ajax({
type: "POST",
url: url,
data: $("#form_inventario").serialize(),
success: function(data)
{
$("#contenido").html(data.mensaje);
}
});
var elem = document.getElementById('btn_enviar');
}
return false;
});
This is the Controller. array_db is the array with the user information.
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
if($obj_inv){
$edit_view = $this->load->view(base_url()."inventario/edit",$array_db,TRUE);
$response = array('mensaje' => $edit_view
);
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;
} else {
echo('ERROR: Uno o mas datos son incorrectos o no estan llenados.');
}
This is the model. Inventario_model is the function that calls the database and return a True or False is the information is inserted.
public function insert_inventario($array_data) {
$id = $this->db->insert('inventario',$array_data);
$obj_activo = $this->db->get('inventario');
return $id;
}
What I'm missing? Why the edit view isn't showing?
The only clue I have is, in development Console is throwing me this:
http://[IP]/Inventario_Remedy/inventario/insert_inventario Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Edited to show the error log
PHP 1. {main}() C:\Xampp\htdocs\Inventario_Remedy\index.php:0
PHP 2. require_once()
C:\Xampp\htdocs\Inventario_Remedy\index.php:293
PHP 3. call_user_func_array()
C:\Xampp\htdocs\Inventario_Remedy\system\core\CodeIgniter.php:514
PHP 4. Inventario->insert_inventario()
C:\Xampp\htdocs\Inventario_Remedy\system\core\CodeIgniter.php:514
PHP 5. Inventario_model->insert_inventario()
C:\Xampp\htdocs\Inventario_Remedy\application\controllers\Inventario.php:105
PHP 6. CI_DB_query_builder->insert()
C:\Xampp\htdocs\Inventario_Remedy\application\models\Inventario_model.php:29
PHP 7. CI_DB_driver->query()
C:\Xampp\htdocs\Inventario_Remedy\system\database\DB_query_builder.php:1608
PHP 8. CI_DB_driver->display_error()
C:\Xampp\htdocs\Inventario_Remedy\system\database\DB_driver.php:675
PHP 9. CI_Exceptions->show_error()
C:\Xampp\htdocs\Inventario_Remedy\system\database\DB_driver.php:1698
PHP 10. _error_handler()
C:\Xampp\htdocs\Inventario_Remedy\system\database\DB_driver.php:182
PHP 11. CI_Exceptions->show_php_error()
C:\Xampp\htdocs\Inventario_Remedy\system\core\Common.php:623
CI VERSION 3.0

SOAP PHP and angular

I'm trying to consume a SOAP Web Service used in a PHP file.
When I access the PHP file directly, it works. (http://bacly.fr/baclymphp/getffbadsample.php)
When I try to access it from an AngularJS like this:
function loadwsffbad() {
var players={}
var urlphp="http://localhost/cordova/mbacly/www/php/";
$http.get(urlphp+"getffbadsample.php").then(function(data) {
players = data.data;
console.log(players);
},function(status) {
alert("pas d accès réseau");
});
}
I get this in console:
Fatal error: Class 'SoapClient' not found in C:\wamp\www\cordova\mbacly\www\php\getffbadsample.php on line 5
I saw in other posts that I need to check that SOAP is enabled on the server, which is the case (http://bacly.fr/baclymphp/info.php), As it works directly with the php file, I guess it is not the pb.
getffbadsample.php:
<?php
$clientSOAP = new SoapClient('http://ws.ffbad.com/FFBAD-WS.wsdl');
$Auth["Login"]="******";
$Auth["Password"]="*****";
//Encodage de vos identifiants en Json (sérialisation des objets)
$AuthJson = json_encode($Auth);
$Query["Function"]="ws_getresultbylicence";
$Query["Param"]["Licence"]="06468814";
$QueryJson = json_encode($Query);
//Appel de la fonction distante
$Return = $clientSOAP->getResult($QueryJson,$AuthJson);
echo $Return;
?>
Thank for your help.

Problems with ajax and session variable in Web2Py

I'm developing an app in Web2Py that consists in a little e-commerce. Have a controller and page that the link is localhost:8000/topranchos/produto, with products, were topranchos is the app.
In the page produto there are a list of products like this:
The image is in this link
When the button "Adicionar ao carrinho" is clicked, the javascript function is executed:
<script>
function adicionarCarrinho(prod, qtde) {
quantidade = document.querySelector(qtde).value
console.log(quantidade)
if(quantidade > 0) {
$.get("{{=URL(f="adicionarCarrinho")}}", {produto: prod, qtde: quantidade} )
.done(function( data ) {
console.log (data)
var atual =document.querySelector(".badge-carrinho").innerHTML;
document.querySelector(".badge-carrinho").innerHTML =
parseInt(quantidade) + parseInt(atual);
alert("Adicionado ao carrinho com sucesso");
});
}
else alert("Selecione a quantidade de itens deste produto que você deseja");
}
</script>
It's make a requisition to the action default/adicionarCarrinho:
def adicionarCarrinho():
if request.vars:
session.carrinho.append(
#{'produto':db(db.produto.id == request.vars['produto']).select(),
{'produto':int(request.vars['produto']),
'quantidade':int(request.vars['qtde'])}
)
print "----------"
print session.carrinho
return str("OK")
Where session.carrinho have a list that was declared on db.py model:
#carrinho
session.carrinho = []
On the terminal, the command print session.carrinho print the item received by the ajax request, but when I add other itens the list is empty. When I click on the page of carrinho, that shows the session.carrinho's informations, the var is empty.
How can I repair this? I tried use cookies of course Web2Py book, but I dummie on Web2Py and not has success yet :/
thank you!
The model file is executed on every request, so you are resetting session.carrinho back to an empty list on every request. Instead, in the model, this:
session.carrinho = []
should be something like:
session.carrinho = [] if session.carrinho is None else session.carrinho

Refresh page after "OK" alert popup with javascript

I tried to refresh the page after deleting an item from my back-end list.
Here's the HTML
<a href="index.php?id=<?php
echo $array[id_news];
?>&?action=delete" onClick="return conferma()">Remove</a>
Here's the PHP
if ($_POST['action'] = "delete") {
$sql="DELETE FROM news WHERE id_news=".$_GET['id'];
if (!mysql_query($sql)) {}
}
Here's the Javascript
function conferma() {
return confirm('Confermi di voler cancellare la news selezionata?');
window.location.reload();
}
The popup appears but after clicking OK the page don't refresh.
You are returning on the confirm() line, so the reload never gets executed. Change to:
function conferma() {
if(confirm('Confermi di voler cancellare la news selezionata?')){
// call the delete script via ajax now.....
window.location.reload();
}
return false;
}
It looks like you need to use AJAX to call the delete script, because otherwise the reload will happen and the anchor's href will never be visited.
You are return the boolean result from confirm dialog action, and then reloading, so the script never reach the reload
function conferma() {
ritorno = confirm('Confermi di voler cancellare la news selezionata?');
if(ritorno)
window.location.reload();
else console.log('ok nothing to do');
}
To Fix:
if ($_POST['action'] = "delete") {
by
if ($_POST['action'] == "delete") {

How to call javascript function in the index of a controller in codeigniter?

I'm trying to call a javascript function inside my controller to display a warning message in page if a verification I do in the index function of this controller is false.
Here is my code:
<?php
public function index() {
$this->load->model('uploads_m');
$this->load->helper('form');
$template_vars = Array();
$this->load->vars($template_vars);
$data = Array();
$data['currentUploadId'] = $this->uploads_m->get_lastUploadId();
$data['fileTypes'] = $this->uploads_m->getAllFileTypes();
$data['existingFiles'] = Array();
if (isset($data['currentUploadId'])) {
$data['existingFiles'] = $this->uploads_m->get_UploadedFilesFromUploadId($data['currentUploadId']);
}else {
// TODO create warning message to tell that uploadid was not generated
}
$this->load->view('include/header');
$this->load->view('upload_files', $data);
$this->load->view('include/footer');
}
?>
I have a JS function stored in an extern js file that I wanted to call in this TODO.
It should be called this way :
show_msg_xajax("warning", "System was unable to find an Upload ID");
Since the check condition is being done in the index() of the controller, I don't know how to call this js function.
if it was being invoked by an event in the view, I'd create an ajax method to execute this function. but how can I call the javascript function it in the index()?
I already checked this answer: Calling javascript function from controller codeigniter but it didn't help me.
The solution I found was to send the function directly to the footer of that page... so I added a new variable to a footer template I have (where I call my javascripts).
in the index function in the controller I did:
if (isset($data['currentUploadId'])) {
$data['existingFiles'] = $this->uploads_m->get_UploadedFilesFromUploadId($data['currentUploadId']);
} else {
// TODO criar alerta de erro no sistema que não gerou UPLOADID
$template_vars['foot_javascripts_inline'] = 'show_msg_xajax("error", "System was unable to find an Upload ID");';
}
and in my footer template I added:
if (isset($foot_javascripts_inline)) { ?>
<script> <?php echo $foot_javascripts_inline ?> </script>
}
Thanks anyway for the help
You need to add your file with JS function as a view:
$this->load->view('path-to-js-message');

Categories

Resources