empty (blank) fetch data return from php - javascript

I am sending an id by fetch to php to fetch the name of a project. Now when I am sending this result to console to verify that it brings it correctly but it only brings a blank or empty space. Thank you very much if you got this far
Javascript, where you capture the id by clicking and sending the id by fetch
var enlaces=document.getElementsByClassName('enlace');
for(let el of enlaces){
el.addEventListener('click', obtener_id_proyecto);
}
function obtener_id_proyecto(e){
e.preventDefault();
console.log('presionaste en un proyecto');
var id_p=this.id;
//Enviando datos por Fetch
let datos=new FormData();
datos.append('id', id_p);
fetch('inc/funciones/funciones.php',{
method: 'POST',
headers:{'Content-Type': 'application/json;charset=utf-8'},
body: JSON.stringify(datos)
})
.then(function(response) {
if(response.ok) {
return response.text();
} else {
throw "Error en la llamada Ajax";
}
})
.then(function(datosRecididos){console.log(datosRecididos)});
}
PHP
function obtenerNombreProyecto(){
$id_proyecto=$_POST['id'];
include 'conexion.php';
try{
$sql= mysqli_query($conexion,"SELECT nombre FROM proyectos WHERE id = {$id_proyecto}");
return json_encode($sql);
} catch(Exception $e){
echo "Error! : ". getMessage($e);
return false;
}
}
Console screenshot
https://prnt.sc/9Cr8fKRuqAX1

Probably there is a problem with this address: './inc/funciones/funciones.php'. Are you sure about that? Why you put a . in the beginning of it?

Related

Call CodeIgniter method from JQuery

I want to call codeigniter method using jquery. My ajax call is working but getting an error. I have added my controller, model, ajax call and error.
According to:
$("body").on("click", ".call-ajax", function() {
// obtém o valor do link
console.log("chamada ajax");
var caminho = "http://localhost/xxxxx/public/uploads/anexos/";
data = {
id_rec: $(this).data("id_rec"),
anexo: caminho + $(this).data("anexo")
};
console.log(data);
// AJAX para o controller
$.ajax({
url: "reclamacao/delete_anexo",
data: data,
type: "POST"
}).done(function(resp) {
console.log("deleção OK");
// Display the resposne
//$("#result").append($("<li/>").html(resp));
});
});
It correctly calls
Check Image 1
But this error occurs:
Check image 2
My CONTROLLER CODE:
public function delete_anexo($id, $file)
{
try
{
if (!$this->input->is_ajax_request())
{
$this->output->set_status_header(404);
return;
}
if (!$this->anexo_model_reclamacao->delete_anexo($id, $file))
throw new Exception("Erro ao excluir", 1);
$alert = 'Operação Realizada com sucesso.';
}
catch (exception $e)
{
$alert = $e->getMessage();
}
bootbox_alert($alert);
}
MODEL CODE:
public function delete_anexo($id, $file) {
$this->db->delete($this->table, array('id_reclamacao' => $id, 'file' => $file));
return true;
}
This declaration in the controller public function delete_anexo($id, $file) assumes that the $id and $file are in the url e.g. reclamacao/delete_anexo/{$id}/{$file} which is clearly not what you want by your data jquery declaration. Thus you need to capture the post vars like so:
public function delete_anexo()
{
try
{
if (!$this->input->is_ajax_request()) {
$this->output->set_status_header(404);
exit;
}
$id = $this->input->post('id_rec');
$file = $this->input->post('anexo');
if (is_null($id) || is_null($file)) {
throw new Exception('Parameters missing');
}
if (!$this->anexo_model_reclamacao->delete_anexo($id, $file)) {
throw new Exception("Erro ao excluir", 1);
}
$alert = 'Operação Realizada com sucesso.';
}
catch (exception $e)
{
$alert = $e->getMessage();
}
bootbox_alert($alert);
}
The second error image that you have posted is clearly stating that the second argument is missing from your method call, please double check whether both the arguments are getting posted when you are making the ajax call.

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.

Insert data in sql with ajax not working

I'm trying to insert data in a sql table using ajax and php, but it's not working. My ajax give me the result like it works, but when i look at the table, there's not in it. Doing it without ajax works fine, so i guess my php is working ok.
Here's the code:
HTML:
<form action="servico.php?p=cadUsr" method="POST" id="frmCadUsr">
Nome: <input type="text" maxlength="255" name="txtNome" id="txtNome"/>
Idade: <input type="text" maxlength="3" name="txtIdade" id="txtIdade"/>
<input type="submit" value="Enviar"/>
</form>
PHP:
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
switch($passo){
case "cadUsr":
cadUsr();
break;
default:
getRetorno();
break;
}
function getRetorno(){
echo "Este texto foi escrito via PHP";
}
function cadUsr(){
require("dbCon.php");
require("mdl_usuario.php");
$usr = $_POST["txtNome"];
$idade = $_POST["txtIdade"];
$resultado = usuario_cadastrar($con,$usr,$idade);
if($resultado){
echo "Cadastro efetuado com sucesso";
} else {
echo "O cadastro falhou";
}
}
?>
OBS: I need to pass the action of the form with the url parameter as cadUsr, so it call the function in php.
AJAX:
window.onload = function(){
var xmlhttp;
var frm = document.querySelector("#frmCadUsr");
var url = frm.getAttribute("action");
var nm = document.querySelector("#txtNome").value;
var idade = document.querySelector("#txtIdade").value;
frm.addEventListener("submit",function(e){
e.preventDefault();
try{
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("POST",url,true);
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
//alert("Deu certo");
console.log(xmlhttp.responseText);
}
}
} catch(err){
alert("Ocorreu um erro.<br />"+ err);
}
});
}
The PHP function to insert the data:
function usuario_cadastrar($conexao,$nome,$idade){
if($nome == "" && $idade == ""){
return false;
}
$sql = sprintf("insert into usuario (nome,idade) values ('%s',%s)",$nome,$idade);
$resultado = mysqli_query($conexao,$sql);
return $resultado;
}
I think the problem is here servico.php?p=cadUsr. You copy the action-attribute from the form with a querystring. If you cut the querystring from it, I think it will work.
The main problem is being called by Hossein:
This :
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
Will not work. You're doing a post, you can't get GET variables.
You call value on value which will result in undefined and that will put no data in your database.
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
So remove value and add the cadUsr variable to the querystring in the send function. Update PHP to:
$passo = (isset($_POST['p'])) ? $_POST['p'] : "";
And it will work!
You can see your callback codes by adding console.log(xmlhttp.responseText); to your readystate success function.
Also you need to set the requestheader content-type to x-www-form-urlencoded when sending post.

How can I return the path of a screenshot capture to a function and return via JSON to javascript?

I have a PHP script that invokes a casperjs script via exec function and this is working fine.
Is it possible to return the path where I saved a screenshot via exec as JSON?
My scripts are below:
PHP code:
// Execute to CasperJS via asynchronous process
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$target = $_POST['target'];
$filename = $_POST['file'];
$retorno = array()
try {
exec("{$casperjs_run} {$script} {$username} {$password} {$filename} 2>&1", $output);
} catch (Exception $e) {
$retorno['error404'] = "Desculpe! Não foi possivel acessar a página solicitada.";
}
// Return Data if success
// Retorna para front-end
if (empty($output)){
$retorno['success'] = $output;
echo json_encode($retorno);
return false;
} else {
$retorno['error'] = $output;
echo json_encode($retorno);
return false;
}
?>
CasperJS code:
casper.thenOpen(minhaoi, function myaccount() {
this.capture('pic2.png');
this.log('Acessando informações da conta, aguarde...');
if (!this.exists(('div.panel-horizontal'))) {
this.log(JSON.stringify("Não foi encontrado um plano colaborador, aguarde..."));
noDetails = this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
} else {
casper.waitForResource("Análise de Conta", function orderDetails(details) {
return details;
}, function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
}
});
// Logout & Exit
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
return noDetails;
} else {
return myDetails;
}).run();
Here my JS code that receive the information from casperjs via JSON.
Javascript Code:
success: function(data) {
if (data.success) {
$('#retorno').html(data.success);
$('#imagem').attr('src', '/details/' + filename);
$('#resultado').show();
}
},
error: function(data) {
// check error
$('#retorno').attr("class='alert alert-danger' role='alert'");
$('#retorno').html(data.error);
}
In my mind filename should be the whole name of the screenshot like this, pi9rxw2fqlh.png plus the complete path too. And display the image in the browser.
What's wrong in my approach?
For this.log to actually print something, you need to set the logLevel to at least debug as it is the default log level. So either increase the log level casper.options.logLevel = 'debug'; or use this.echo instead of this.log.
It looks like you're using waitForResource wrong. Since there can't be resources with spaces in them, you might want to checkout waitForText under the assumption that the loaded resource adds that string to the DOM:
casper.waitForText("Análise de Conta", function onReceive() {
this.log('ScreenShot Begin');
myDetails = this.captureSelector(path_images + filename + '.png', '#content', { quality: 100 } );
this.log(' ScreenShot Done'); });
});
capture as well as captureSelector return the casper instance and not the image details. So you need to pass the filename.
Since you use php's exec with the output array, you can casper.echo the filename in question with a unique beginning string (here #noDetails#):
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
this.echo("#noDetails#" + filename + ".png");
In the client javascript you can then iterate over the data.success or data.error arrays and extract the filename from the match line:
data.success.forEach(function(line){
if (line.indexOf("#noDetails#") === 0) {
var filename = line.split("#noDetails#")[1];
$('#imagem').attr('src', '/details/' + filename);
}
});
With this, you can completely remove the if block from the eachThen callback.
The other option is to set the specific screenshot variable and write the JSON object in the last line.
this.captureSelector(filename + '.png', 'div.panel-horizontal', {quality: 100});
noDetails = filename + ".png";
and at the end:
casper.eachThen(oi_out, function () {
this.capture('pic3.png');
if (noDetails != "") {
this.echo(JSON.stringify({filename:noDetails}));
} else {
this.echo(JSON.stringify({filename:myDetails}));
}
});
On the client side, you would need to only look in the last line of the array:
var obj = JSON.parse(data.success[data.success.length-1]);
$('#imagem').attr('src', '/details/' + obj.filename);

Categories

Resources