Reputation: 39
I'm trying to confirm the insert to a DB and return a Json if success, and if it fails catch the error and send the exception message.
The PHP inserts the info in to the data base but for some reason the javascript is returning an error even when the data is inserted correctly.
In the response text when the info is inserted I receive a NULL value = "" but when it fails ib the insertion it works fine and catch the error. and always receive this error: "Error. Parsing JSON Request failed."
Here is the PHP:
<?php
//Cargar coneccion a BD:
require_once '../db/db_config.php';
//Validacion de Datos:
if (is_ajax()) {
if (isset($_POST["param1"]) && !empty($_POST["param1"])) { //verificar si param1 existe y tiene valor
$tipo = $_POST["param1"];
if (isset($_POST["param2"]) && !empty($_POST["param2"])) { //verificar si param2 existe y tiene valor
$lista = $_POST["param2"];
insertarUsr($tipo,$handler,$lista);
}
}
}
//Funcion para verifica si el request en un tipo Ajax rquest
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function insertarUsr($tipo, $h, $lista){
$nomre =$lista[0];
$apellido =$lista[1];
$email =$lista[2];
$password =$lista[3];
try {
$sql = "CALL proc_create_user(:tipo, :nomre, :apellido, :email, :password)";
$handler = $h;
$stm = $handler->prepare($sql); // preparar statments
$stm->bindParam(':tipo', $tipo, PDO::PARAM_INT);
$stm->bindParam(':nomre', $nomre, PDO::PARAM_STR, 4000);
$stm->bindParam(':apellido', $apellido, PDO::PARAM_STR, 4000);
$stm->bindParam(':email', $email, PDO::PARAM_STR, 4000);
$stm->bindParam(':password', $password, PDO::PARAM_STR, 4000);
if($stm -> execute()){
header('Content-type: application/json');
echo json_encode(array(
'Status' => 'Success'
));}
} catch (Exception $e) {
//echo "Error occurred:" . $pe->getMessage();
die( "Ocurrio un Error:" . "'".(string)$e->getMessage()."'");
}
}
?>
This is the JS
function addNewUsr(tipo, arreglo){
var datos = {param1: tipo, param2: arreglo};
$.ajax({
url: "resources/includes/control/create_user.php",
type: "POST",
data: datos,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "json",
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
console.log(e);
console.log(x);
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
}).done(function(data, textStatus, jqXHR) {
alert('Yey it worked!!')
clearChildren(document.getElementById('frmUser'));
})
.fail(function(jqXHR, textStatus, errorThrown) {
jqXHR.errorThrown = errorThrown;
var message = jqXHR.responseText
message = message.replace("Error occurred:'SQLSTATE[45000]: <<Unknown error>>", 'Error')
alert('Ocurrio un Error\n\n'+message);
})
.always(function() {
});
return 1;
}
Edit: this is the Headers I see from google Crhome Dev Tools:
Remote Address:XXX.XXX.XXX.XXX
Request URL:http://someserver/vek/resources/includes/control/create_user.php
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate
Accept-Language:en-US,en;q=0.8,es;q=0.6
Cache-Control:no-cache
Connection:keep-alive
Content-Length:102
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost
Origin:http://someserver
Pragma:no-cache
Referer:http://someserver/vek/keyuser.php
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
param1:2
param2[]:asd
param2[]:f
param2[]:[email protected]
param2[]:sdfvdzfv_sfd
Response Headersview source
Connection:Keep-Alive
Content-Length:0
Content-Type:text/html
Date:Fri, 09 Jan 2015 23:09:41 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.4 (Win64) PHP/5.4.12
X-Powered-By:PHP/5.4.12
Upvotes: 0
Views: 803
Reputation: 39
I was able to resolve this by placing the header at the top of the PHP file:
<?php
header('Content-type: application/json');
//
// rest of the code...
This returned the query result and echoed a correctly formatted Json
Upvotes: 1