Iḿ trying to instantiate and execute a custom class method from AJAX, but returns a 500 Code Error, here's the ajax:
I want that the ajax call create an array from a given xml, this is working as expected, after that I need to create an array from an SQL query and execute an Insert Statement, and with the data from the SQL array I have to call a class method, Iḿ making the includes but that doesnt working
function BorraEmple(TipoDocu,NumePers)
{
if(confirm("Eliminar Empleado ("+TipoDocu+" "+NumePers+"), Desea Continuar?"))
{
var CodiDocu =$("#CmbCodiDocu").val();
var NumeDocu =$("#TxtNumeDocu").val();
$.ajax({
type: 'POST',
url: 'borraemple.php',
data: "Accion=BorraEmple"+"&TipoDocu="+TipoDocu+"&NumePers="+NumePers+"&CodiDocu="+CodiDocu+"&NumeDocu="+NumeDocu,
dataType: 'text',
async: false,
success: function(data)
{
setTimeout(function(){
location.reload();
}, 2000);
if(/ErrorSQL/.test(data))
alert("Error al consultar el registro, contacte a soporte tecnico");
else
{
if(data!='')
alert(data);
}
alert("El registro ha sido eliminado");
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
}
And here is the php:
<?php
include_once(SIH_PATH.'clases/FES/nominajuste.class.php');
if($_POST[Accion]=='BorraEmple'){
$TipoDocu=$_POST[TipoDocu];
$NumePers=$_POST[NumePers];
$CodiDocu=$_POST[CodiDocu];
$NumeDocu=$_POST[NumeDocu];
if(strlen($MesInve)==1)
$MesInve2='0'.$MesInve;
else
$MesInve2=$MesInve;
$DocuApli=docuapli($CodiDocu);
$Cond='';
if($DocuApli==124){
$EnviNomi = parametros('EnviNomi', 2);
if($EnviNomi==1){
function getArray(){
$doc = new DOMDocument();
$doc->preserveWhiteSpace = true;
$doc->load('NominaIndividualDeAjusteElectronicaXSDV1.0.xsd');
$doc->save('a.xml');
$xmlfile = file_get_contents('a.xml');
$parseObj = str_replace($doc->lastChild->prefix.':',"",$xmlfile);
$doc->doc->textContent;
$ob= simplexml_load_string($parseObj);
$json = json_encode($ob, JSON_PRETTY_PRINT);
$arrayNomiElect = json_decode($json, true);
return $arrayNomiElect;
}
$sqlNumePers = "SELECT CodiDocu, NumeDocu, CodiInst, CodiAno, CodiMes, TipoDocu, NumePers FROM DetaNomi WHERE CodiDocu='$CodiDocu' AND NumeDocu='$NumeDocu' AND NumePers=$NumePers GROUP BY TipoDocu,NumePers";
$resNumePers = query($sqlNumePers,2);
$ManeNoEl = parametros('ManeNoEl');
foreach($resNumePers as $key => $value) {
$datos = array(
'CodiDocu' => $value['CodiDocu'],
'NumeDocu' => $value['NumeDocu'],
'CodiInst' => $value['CodiInst'],
'CodiAno' => $value['CodiAno'],
'CodiMes' => $value['CodiMes'],
'TipoDocu' => $value['TipoDocu'],
'NumePers' => $value['NumePers'],
'arraybase' => getArray()
);
$sqlIns="INSERT INTO NomiElec (CodiDocu, NumeDocu, CodiInst, CodiAno, CodiMes, TipoDocu, NumePers) VALUES ('$datos[CodiDocu]','$datos[NumeDocu]','$datos[CodiInst]','$datos[CodiAno]','$datos[CodiMes]','$datos[TipoDocu]','$datos[NumePers]')";
//echo $sqlIns; exit();
query($sqlIns);
if($ManeNoEl == 1){
$nominaElect = new NominaAjuste($datos);
$nominaElect->getEstructura('E');
}
}
}
else
$retorno='';
echo $retorno;
}
I have tested the functions without ajax and everything works as supossed, I'm not very familiar with ajax, and don't know if I'm doing well..
Thanks.
Related
I'm new to php and stuck in my tracks here, so any help is appreciated. I've written a few functions in a JS file to render and update a gallery view for a WordPress template I made. From the updateGallery() function, I make an AJAX call after pressing a submit button on the page, but am receiving a "parsererror."
Arguments(3) [{…}, "parsererror", SyntaxError: Unexpected token A in JSON at position 0 at parse (<anonymous>)
at Ut (https://…, callee: ƒ, Symbol(Symbol.iterator): ƒ]
I tried the code for the API request directly in my WP template to render a response and it worked as expected, but when I try to incorporate my script I get the error and I can't figure out what's causing it.
JS
function updateGallery() {
var county = $("#county").val();
jQuery(".galleryGrid").fadeOut("fast", function() {
console.log("ajax request");
jQuery(".galleryGrid").html("").hide();
$.ajax({
type : "GET",
dataType : "JSON",
url : ajax.url,
data : {
action: "get_gallery_data",
county_id : county
},
error: function(response, error) {
console.log(arguments);
alert("Failed because: " + error);
},
success : function(response) {
if(response.type === "success") {
console.log("Success")
renderGrid(response.data);
}
}
});
});
}
PHP
add_action("wp_ajax_nopriv_get_gallery_data", "get_gallery_data");
add_action("wp_ajax_get_gallery_data", "get_gallery_data");
function get_gallery_data() {
$county_id = $_REQUEST[county_id];
$base_api_url = "https://some.api.com/";
$filters = array(
"field" => "field_153",
"operator" =>"is",
"value" => $county_id
);
$filters_url = rawurlencode(json_encode($filters));
$api_url = $base_api_url."?filters=".$filters_url;
$request = wp_remote_get($api_url, array(
"headers" => array(
"Application-Id" => "5xxxxxx",
"REST-API-KEY" => "0xxxxxx",
),
));
$body = wp_remote_retrieve_body($request);
$output = json_decode($body, true);
echo $output;
die();
};
$output = json_decode($body, true);
//Change
$output = json_encode($body, true);
I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}
I'm trying to send some values through ajax and after being treated in the test.php, send the data back to be used.
The database part is correct. My problem is in the re-sending of the data:
The Json coding part does not give error, but when I try to check the data, many of them do not appear.
I think this can be caused by:
The way I am resending the data;
The way I encode Json.
My code.
ajax main.php:
$('#filtro_limit1').val(num_Limite_rows);
$.ajax({
url: teste.php,
type:'post',
data:
{
limite: num_Limite_rows,
tipologia: tipologia_val,
ordenar_por: ordenar_por_val
},
success: function(data, num_rows, num_actual_rows, mensagem_erro)
{
}
});
PHP teste.php:
if(pg_num_rows($result1) > 0)
{
$data = array[];
$data = $result1;
$out = array_values($data);
echo json_encode($out);
echo pg_num_rows($result1);
echo $filtro_limit;
echo "Não existem erros";
}
else
{
$data = array[];
echo json_encode($data);
$numero_rows = 0;
echo $total_rows;
echo $filtro_limit;
echo "Não existem valores a serem mostrados";
}
Please some help needed. Thank you for the future help.
Your success function is wrong. The parameter data will contain all the output of your php script. You can't automatically split the output by using different parameters in the function definition.
function success(data, textStatus, jgXHR) {
console.log(data);
}
Check your console and you'll see your data.
You'll probably want to change your php code:
$result = [
'out' => json_encode($out),
'result1' => pg_num_rows($result1),
'filtro_limit' => $filtro_limit,
'message' => "Não existem erros",
]
echo json_encode($result);
exit;
and
$result = [
'total_rows' => $total_rows,
'filtro_limit' => $filtro_limit,
'message' => "Não existem valores a serem mostrados",
];
echo json_encode($result);
exit;
That way, you'll have a much easier time to parse the data in JavaScript. For example:
function success(data, textStatus, jgXHR) {
var message = data.message;
}
you have to return all data in one statement in php like this :
echo json_encode(array(
'out'=>$out,
'num_rows'=>pg_num_rows($result1),
'filtro_limit'=>$filtro_limit,
'msg'=>"Não existem valores a serem mostrados"
));
and ajax code like this:
$('#filtro_limit1').val(num_Limite_rows);
$.ajax({
url: 'teste.php',
type:'post',
dataType: 'json',
data:
{
limite: num_Limite_rows,
tipologia: tipologia_val,
ordenar_por: ordenar_por_val
},
success: function(data)
{
$num_rows=data['num_rows'];
}
});
I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.
I'm new to jQuery, and have not been able to debug this ajax call in Firebug:
This is my ajax call:
var styndx = $('#studylist option:selected').val();
var studyname = $('#edit_field').val();
$.post("saveStudyName.php", {'type': 'update', 'studyname':studyname, 'styndx':styndx},
function(resultmsg) {
$('#edit_field').val('');
$('#savebtn').attr('disabled',true);
refresh_studynames();
});
And this is the function refresh_studynames:
function refresh_studynames()
{
$.ajax({
url: 'getStudyNames.php',
data: "",
dataType: 'json',
error: function() {
alert('Refresh of study names failed.');
},
success: function(data)
{
$data.each(data, function(val, sname) {
$('#studylist').append( $('<option></option>').val(val).html(sname) )
});
}
});
}
Finally, this is the php script getStudyNames.php ($dbname,$dbconnect, $hostname are all populated, and $dbconnect works; the backend database is Postgres, and pg_fetch_all is a Postgres function in PHP that returns result as an array):
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
if (!$dbconnect) {
showerror(0,"Failed to connect to database",'saveStudyName',30,"username=".$dbuser.", dbname=".$dbname);
exit;
}
$sql = "SELECT ST.studyindex,ST.studyabrv AS studyname
FROM ibg_studies ST
ORDER BY studyname";
$fetchresult = pg_exec($dbconnect, $sql);
if ($fetchresult) {
$array = pg_fetch_all($fetchresult);
echo json_encode($array);
} else {
$msg = "Failure! SQL="+$sql;
echo $msg;
}
Any help much appreciated....
The line
$('#studylist').append( $('<option></option>').val(val).html(sname) );
looks wrong.
I'm not too sure but you could try :
var $studylist = $('#studylist').empty();
$data.each(data, function(i, record) {
$studylist.append( $('<option/>').html(record.sname) );
});