Problems with ajax and session variable in Web2Py - javascript

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

Related

Function inside element event JS with an UploadControl from devexpress

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()
}

Django not adding a string to models

I am having a problem after I restarted my project from scratch
I can add a value manually to my django model, but when it comes from a variable the user entered, it only pass a blank string..
Some pictures of the logs to be more explicit:
Process:
So, I am having a simple model Tech and I have a page where you can add a new name to Tech model.
I enter the name (here i entered the name ede dede), click add, then i send it to the backend using AJAX.
In the shell in VSCODE I see I received the element, but when I add it to my django model Tech, and then print the new object in Tech, it has an ID, everything, but the name is a blank string ""
Moreover, When i print it in my python code, it doesnt even give me the queryset, i have nothing.
How come?
Here is a piece of my code
VIEWS.PY:
#ajax_required
#require_http_methods(["POST"])
def AddNewEmployee(request):
newtechname = request.POST.get('new_employee').title()
response_data = {}
print('new employee: '+newtechname)
print(type(newtechname))
if Tech.objects.filter(name=newtechname).exists():
response_data['success'] = False
response_data['result'] = 'This name already exists'
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
else:
techname = Tech(name=newtechname)
techname = Tech(selected=True) #add new tech to model
techname.save() #save new name to model
response_data['success'] = True
response_data['result'] = 'Added a new teammate successfully!'
response_data['tech_id'] = techname.id #get new name id from model
response_data['tech_name'] = techname.name
response_data['tech_selected'] = techname.selected
print(techname)
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
MODELS.PY
class Tech(models.Model):
name = models.CharField(max_length=200)
selected = models.BooleanField(default=False)
def __str__(self):
return self.name
JS:
$('#add-employee').on('submit',function(e){
e.preventDefault();
if(e.target.getAttribute('id')==('add-employee')){
console.log('form submitted!'); //sanity check
AddNewEmployee();
}
});
function AddNewEmployee(){
console.log('AddNewEmployee is working!');
console.log($('#addtech_id').val()); //get the input value from input id
const addemployee_form_url = $('#add-employee').attr('action'); //get the form url
new_employee = $('#addtech_id').val(); // data sent with the post request
console.log(typeof new_employee);
let request_data = {
'new_employee': new_employee,
'csrf_token':csrftoken
}
$self = $(this)
$.ajax({
url : addemployee_form_url, //endpoint
type : "POST", //httpmethod
data : request_data,
//handle a successful response
success : function(response){
$('#addtech_id').val(''); //remove the value from the input
console.log(response); // log the returned json to the console
console.log("A connexion to the backend has been established with success!"); // sanity check
//Add to selected list
if (response['success']){
AddToSelectedList(response['tech_id'], response['tech_name']);
$('#results').html("<h5><div class='alert-box alert radius' data-alert style='color:green;'>"+response['result']+"</div><h5>");
}
else{
$('#results').html("<h5><div class='alert-box alert radius' data-alert style='color:red;'>This name is already in the list!</div><h5>");
}
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
What I dont understand is, why is it printing (in views.py) newtechname correctly, which i can even see its type is a string so no problem, then, it passes an empty string to Tech model when techname = Tech(name=newtechname)
Thanks for your help!
The problem is here
else:
techname = Tech(name=newtechname)
techname = Tech(selected=True) #add new tech to model
techname.save() #save new name to model
You are trying to create an object that does not exist as Tech(name=newtechname) doesn't create the object, you can use that after using Tech.objects.create()
So in your case changing that with the traditional objects.create() has resolved the issue.

Can't show data in javascript console

I have a registration form in my Laravel project. I submit that registration form data to laravel controller using ajax from javascript. After successfully stored those registration data in database I return the insertedID from controller to javascript and use console.log() function to show that id. In my javascript, console.log() shows that id and auto disappear after half mili second. But I don't want it to disappear.
Here is my js code
var name = $('#reg_name').val(); //reg_name is the id of the input field
var email = $('#reg_email').val(); //reg_email is the id of the input field
$.get( 'signup', {'name': name, 'email': email,'_token':$('input[name=_token]').val()}, function( data )
{
//Here 'signup' is my route name
console.log(data);
});
Here is my controller function
public function signup(RegistrationFormValidation $request)
{
$data = new User();
$data->name = $request->name;
$data->email = $request->email;
$data->save();
$lastInsertedId = $data->id;
if($lastInsertedId > 0)
{
return $lastInsertedId;
}
else
{
return 0;
}
}
Here I concise my code.
What's the problem in my javascript ?
If you are loading a new page, the default behaviour of the Chrome Dev Tools is to clear the logs. You can enable the Preserve log checkbox at the top of the console to prevent this behaviour.
In other situations, the data emitted to the console is modified after the logging to reflect subsequent updates. To prevent this, one can log a JSON serialized version of the data:
console.log(JSON.stringify(data))
(but probably this is not your case).

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

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