Codeigniter Can't change view page - javascript

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

Related

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).

Passing variables through PHP -> Javascript -> AJAX - Options?

I am currently working on a CMS where there are a lot of communications between PHP and JavaScript (+ AJAX). I am having difficulties storing variables all through the flow.
For instance: after login you can select a site to edit. When on click, I store the site_id in a POST-variable. After that I redirect to the pages-overview-page where I read out all my pages from the database by using this site_id.
If I add a page, the following happens:
1.The $_POST['site_id'] is put into javascript by echoing:
echo "<script>var siteid =".$_POST['siteid'].";</script>"
2.My JavaScript then does an AJAX call:
$(".leftpanelinner").on('click','._add-page', function(event){
event.preventDefault();
$(".sortable").load("ajax_scripts/page-actions.php/add_page",{siteID: siteid, callFunction:'add_page' });
});
3.This on it's turn fires an php-script which adds a page to the site with a query to my database and then reloads the main div of my page:
public function new_page($iSite_id, $sTemplate, $sTitle, $sMeta, $sCSS, $sJS, $sFavicon, $aContent, $aMenu)
{
$oPagemodel = new page_model;
$iPage_id=$oPagemodel->insert_pagemodel($iSite_id, $sTemplate, $sTitle, $sMeta, $sCSS, $sJS, $sFavicon, $aContent, $aMenu);
return $iPage_id;
}
public function insert_pagemodel($iSite_id, $sTemplate, $sTitle, $sMeta, $sCSS, $sJS, $sFavicon, $aContent, $aMenu)
{
$this->set_pagemodel($sTemplate, $sTitle, $sMeta, $sCSS, $sJS, $sFavicon, $aContent, $aMenu);
$sSQL = "INSERT INTO `pages` (f_site_id, object) VALUES ('".$iSite_id.', '.serialize($this)."');";
if (mysql_query($sSQL)) {$this->iID = mysql_insert_id();} else {return false;}
return $this->iID;
}
Isn't there a simpler way to store a variable through JavaScript/PHP/AJAX or is the above the best way?
You can use cookies for this.
<?php
$foo = 'lorem';
setcookie('the_foo',$foo,time() + (86400 * 7));
echo $_COOKIE['the_foo'];
?>
You can get and set cookies with js as well.

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

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