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'];
}
});
Related
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.
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);
}
});
}
Alright, this is probably super simple but I've been breaking my head over this all day and I cannot get it to work.
I have a page that displays a list of users from a mysql query. On this page it should also be possible to add users. To do this, I'm sending an AJAX call to process.php which does some validation and sends an error if there is one. If there is no error, I want AJAX to update the page.
The problem is, that if there are no errors (a user has been added), I want to return the updated userlist. This means storing the output of my getUsers(); function in an array, which isn't possible.
How can I achieve this?
p.s. I realise this is crappy code and I should be using OOP/PDO, but this isn't for a production environment and it works. So I'll leave it like this for the time being.
users.php
<article>
<ul>
<?php getUsers(); ?>
</ul>
</article>
<form id="addUserForm">
...
<input type="hidden" name="addUser">
</form>
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if (response.success) {
$("article ul).html(response.data);
} else {
$(".errorMessage).html("<p>" + response.error + </p>");
}
}
});
});
functions.php
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
function addUser($email, $password)
{
global $db;
$result = mysqli_query($db, "INSERT INTO users ... ");
return $result
}
process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}
}
Your getUsers() function is printing and not returning the data to json connstructor
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
while($row = mysqli_fetch_assoc($query))
{
echo "<li>" . $row["user_firstname"] . "</li>";
}
}
it has to be something like this
function getUsers()
{
global $db;
$query = mysqli_query($db, "SELECT * FROM users");
$list = "";
while($row = mysqli_fetch_assoc($query))
{
$list. = "<li>" . $row["user_firstname"] . "</li>";
}
return $list;
}
And there is a syntax error in the following line
if (addUser($email, $password)
close it with ")"
You can capture the output of the getUsers function without changing the current behavior if that's what you're after. In the success output change
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
to
ob_start();
getUsers();
$usersList = ob_get_clean();
$responseArray = ["success" => true, "data" => $usersList];
echo json_encode($responseArray)
What this does is captures the output and stores it into a varable $usersList which you can then return as a string.
You'd be better off returning the users as an array and dealing with generating the markup on the client side IMO, but that's up to you. This is just another way to get what you have working.
More information about php's output buffer here
Are you trying to get the error returned by ajax or you want to have custom error? (e.g. string returned by your php script). If you're referring to ajax error you should have this:
EDIT: Since you mentioned you want a custom error returned by process.php
Process.php
if (isset($_POST["addUser"]))
{
... // Serialize data
if (empty ...)
{
$responseArray = ["success" => false, "error" => "Fields cannot be empty"];
echo json_encode($responseArray);
}
// If user is successfully added to database, send updated userlist to AJAX
if (addUser($email, $password))
{
$responseArray = ["success" => true, "data" => getUsers();];
echo json_encode($responseArray)
}else{
echo 1;
}
//I added else echo 1;
}
Your ajax will be:
$("#addUserForm").on("submit",function() {
event.preventDefault();
var data = $("#addUserForm").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: data,
dataType: "json",
success: function(response) {
if(response != 1){
$("article ul").html(response.data);
}else{
alert('Custom error!');
}
},
error: function(jqXhr, textStatus, errorThrown){
console.log(errorThrown);
}
});
});
BTW you're missing ) in your posted code if (addUser($email, $password))
This is how I do:
try{dataObj = eval("("+response+")");}
catch(e){return;}
alert(dataObj->example_key);
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.
my problem is that I
can not solve this problem
If I call the php script, all I get is an undefined error
this is the code I use for testing AND
this is the original code from the creator that is giving me a headache
function startJsonSession(){
$.ajax({ url: "jsontest.php?action=startjson",
cache: false,
dataType: "json",
complete: function(data) {
username = data.username;
alert(username);
}
});
}
//phpscript
if ($_GET['action'] == "startjson") { startJson(); }
function startJson() {
header('Content-type: application/json');
$items = '';
echo json_encode(array(
"username" => "bob",
"items" => array( "item1" => "sandwich",
"item2" => "applejuice"
)
));
}
thanks, Richard
edited my question because:
this function returns the json data in a different way
and therefore the solution presented below, does not have the same outcome.
function startChatSession() {
$items = '';
if (!empty($_SESSION['openChatBoxes'])) {
foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
$items .= chatBoxSession($chatbox);
}
}
if ($items != '') {
$items = substr($items, 0, -1);
}
header('Content-type: application/json');
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}
<?php
exit(0);
}
I recreated with your code and figured it out. The object being returned is of type XMLHttpRequest. Its got a property called responseText holding a json string with the data.
so this works..
var decodedData = eval("(" + data.responseText + ")");
username = decodedData.username;
alert(username);
A bit messy but it does the trick :-)
p.s If it helps, I figured it out using firebug in firefox and sticking a breakpoint in the js code
Edited below:
Without wanting to do the eval, you could use this and it works:
$.getJSON("json.php?action=startjson",
function(data) {
username = data.username;
alert(username);
}
);
Edited to show what I did with the success function:
$.ajax({
url: "json.php?action=startjson",
cache: false,
dataType: "json",
success: function(data) {
username = data.username;
alert(username);
}
});
Is username a global variable?
If not you should prepend the "var" keyword.
username = data.username -> var username = data.username;
At the end I got it working.
I installed firebug and saw that the php script was returning html headers instead off json.
All off the sudden it started working, I really would like to know what the problem was, but I can't tell you.
Anyway, thanks for sticking so long, David
also what I don't understand is that it breaks out off php mode, instead of echoing it back like it's done with xml
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}
<?php
is this the same as above (object array containing literal array)?
echo json_encode(array(
"username" => "bob",
"items" => $items
)
));
}