No response data after call a function - javascript

I have a file called login.php, in this file there is the box to fill from send the login data to the server. Now when the user press the login button, this code is fired:
var postUrl = GlobalVariables.baseUrl + 'application/controllers/user.php/ajax_check_login';
var postData =
{
'username': $('#username').val(),
'password': $('#password').val()
};
$.post(postUrl, postData, function(response)
{
// Some stuff..
}, 'json');
the postUrl is valorized correctly by:
http://localhost/App_Name/application/controllers/user.php/ajax_check_login
now I have a list of my own controller that allow me to manage the web app. One of this controller is user.php, how you can see I call the ajax_check_login function. This function check if the data passed from this request exists in the database and if are correct. This is the content:
public function ajax_check_login()
{
echo "Test?";
try
{
if(!isset($_POST['username']) || !isset($_POST['password']))
{
throw new Exception('Bad credentials!');
}
$this->check_login($_POST['username'], $_POST['password']);
if($user_data)
{
$output[] = array(
"some content..."
echo json_encode($output);
}
else
{
echo json_encode(AJAX_FAILURE);
}
}
catch(Exception $exc)
{
echo json_encode(array(
'Exception ' => array(exceptionToJavaScript($exc))
));
}
}
Now, at the top of all I inserted an echo, just to test if is printed. But nothing. In the Chrome console I get:
This request has no response data available.
I don't know what is wrong, someone could enlighten me?

First, you'd like to check what's the return from server, say HTTP200 without contents? or Error 500. Why I'm saying this because your snippet tells there are few variables/functions missing. Check my comments:
public function ajax_check_login()
{
echo "Test?";
try
{
if(!isset($_POST['username']) || !isset($_POST['password']))
{
throw new Exception('Bad credentials!');
}
$this->check_login($_POST['username'], $_POST['password']);
if($user_data) // $user_data is never defined in this function, and it's not a global variable
{
$output[] = array(
"some content..." // syntax error; here missing end parenthesis
echo json_encode($output);
}
else
{
echo json_encode(AJAX_FAILURE);
}
}
catch(Exception $exc)
{
echo json_encode(array(
'Exception ' => array(exceptionToJavaScript($exc)) // unknown function exceptionToJavaScript(); it could encounter fatal error
));
}
}
Second, I will suggest you send header to define you're sending JSON encoded content, and exit() after echo. See example:
header('Content-type: application/json');
echo json_encode(/** return **/);
exit();

Related

Calling API | JavaScript to php | How to know if Response != 200, Print Error

Good day!
What I want to achieve is when user clicks the link, it will pass the parameter to javascript, which then using ajax to call the php file where my API is. The API will process the parameter and return a json result.
My code works when the parameter values are given correctly. However I'm stuck at the part where the values are incorrect/invalid and I need to catch the error.
The API document says that if the RESPONSE is 200, then it's a success. Else there is error. My issue is I have no idea how to get this "RESPONSE == 200". Any advise is appreciated!
function callMS_API(addr, cur)
{
$.ajax({
type:'POST',
url:'merklescienceAPI.php',
data:{
WalAddr:addr,
CryCur:cur,
wrapper:"testing"
},
success: function(res)
{
if(res!=200)
{
alert("Invalid Wallet Address!");
}
else
{
alert(res);
}
}
});// ajax
} //end callMS_API
merklescienceAPI.php
<?php
$addr=$_POST['WalAddr']; //Wallet Addr
$cur=$_POST['CryCur']; //Cryptocurrency
$cur_code;
$result = "";
switch ($cur) {
case "Bitcoin":
$cur_code = 0;
break;
case "Ethereum":
$cur_code = 1;
break;
case "LiteCoin":
$cur_code = 2;
break;
case "Tether USD":
$cur_code = 10;
break;
}
require_once('../vendor/autoload.php');
$client = new \GuzzleHttp\Client();
$response = $client->post('https://api.merklescience.com/api/v3/addresses/', [
'body' => '{"identifier":"'.$addr.'","currency":"'.$cur_code.'"}',
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'X-API-KEY' => '<API KEY>',
],
]);
$data = json_decode($response->getBody());
$result = "SCREENING: " . $data->identifier . "\n\nAddress Risk Level : " . $data->risk_level_verbose;
//Whatever you echo will go to javascript success: function(res), and you can do alert(res)
echo $result;
?>
====================================================================
Edit + Solution
I read and tested further on the Guzzle thingy, and came across this thread. I implemented the Try Catch in the API.php and got my result.
Javascript function
function callMS_API(addr, cur)
{
$.ajax({
type:'POST',
url:'merklescienceAPI.php',
data:{
WalAddr:addr,
CryCur:cur,
wrapper:"testing"
},
success: function(res)
{
alert(res);
}
});//ajax
} //end callMS_API
API.php
try{
$client = new \GuzzleHttp\Client();
$response = $client->post('https://api.merklescience.com/api/v3/addresses/', [
'body' => '{"identifier":"'.$addr.'","currency":"'.$cur_code.'"}',
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'X-API-KEY' => '<API KEY>',
],
]);
}catch(Exception $e){
$error = true;
}
if($error == false)
{
$data = json_decode($response->getBody());
$result = "SCREENING: " . $data->identifier . "\n\nRisk Level : " . $data->risk_level . " - " . $data->risk_level_verbose;
}else
{
$result = "Invalid Wallet Address!";
}
echo $result;
Thank you everyone for your help!
If you mean status code or HTTP status code 200 you could try add this line to your ajax option:
...
$.ajax({
...
statusCode: {
200: function() {
alert( "200 reaced" );
},
error: function(response) {
if(response.status != 200)
alert(" status code is " + response.status);
}
...
in Ajax
$.ajax({type:'POST',
url:'somefile.php',
data:{
a name:"a value"
} ,
success: <<THIS EXECUTES WITH A 200 RESPONSE>>,
error: <<THIS EXECUTES IF IT GOES BAD>>
});
The success: runs ONLY if the response is 200. for everything else you capture it with error:

AJAX request is not sending with certain Database

I have a page where I do different requests via AJAX, also I have the developer DB and the production DB but the JS is the same. In certain module, if I open it using the developer DB it shows me the response but if I use the production database it shows nothing but not error is displayed. If I use the production DB in any other module it works perfectly. I already checked in the network console and it says that in both cases the request is sent. Here is the JS code:
function consultaAdministradores(id, tipo, btn){
var datos = {
'id': id,
'tipo': tipo
}
console.log("DATOSSSS");
console.log(datos);
$.ajax({
url: '../send/get_AdminEmpresas.php',
type: 'POST',
data: datos,
dataType: 'JSON',
success: function(res) {
console.log(" res --------- ");
console.log(res);
imprimeAdmins(res);
}
});
console.log("Se pasó el AJAX");
And in the PHP file I have this:
$res = $con->consulta($sql);
if ($res->num_rows > 0 ) {
$i = 0;
while ($dato = $res->fetch_assoc()) {
$administradores[$i] = $dato;
$i++;
}
if ($tipo_page == 'prev') {
array_multisort($administradores);
}
$array = array('status' => "Success", 'administradores' => $administradores, 'id' => $id_page, 'tipo' => $tipo_page);
}
else
{
$array = array('status' => "Fail", 'message' => 'Sin resultados');
}
$json = json_encode($array);
echo $json;
The problem wasn't the JS or the PHP files, the problem was the codification of the DB, I inserted some data in UTF-8 codification and later I converted to UTF-8 codification giving me as a result some weird characters.

Unable to parse response using ajax

So I have a js file that posts a JSON object using $.ajax, and then my php script takes that JSON object and does stuff to it, however, i can't get a json response back from the php script (the success callback function never runs).
register_script.js:
$.ajax({
method: "post",
dataType: "json",
url: "http://localhost/login/webservices/register2.php",
data: {
reg_username: username,
email: email,
reg_password: password,
confirm_password: confirm_pass
},
success: function (data) {
alert("hello?");
//alert(data.status);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log("Post error: " + errorThrown);
});
register2.php:
if (isset($_POST['reg_username'], $_POST['email'], $_POST['reg_password'], $_POST['confirm_password'])) {
$username = $_POST['reg_username']; //$_POST['from html']
$email = $_POST['email'];
$password = hash('md5', ($_POST['reg_password']));
$confirm_password2 = hash('md5', ($_POST['confirm_password']));
$sql = "INSERT INTO users (username, email, password) VALUES ('$username','$email','$password')";
if ($password == $confirm_password2) {
$response = sqlsrv_query($conn, $sql);
if ($response) {
$data = array(
"username" => $username,
"email" => $email,
"password" => $password,
"confirmPass" => $confirm_password2,
"status" => "Registered",
);
echo "Registered \n";
}
}
}
//...
//some other validations
//...
echo json_encode($data);
I have a feeling the way i am handling the json object is incorrect. any help would be really appreciated.
you should not
echo
anything other than json_encode when working with ajax dataType : json you have
echo "Registered \n";
before
echo json_encode
remove that and it should work
EDIT:
when you set the dataType : "json" in your ajax call then the response is expected to be in json when the call is finished, and any text other than json encoded string in response will result in an error. if you still need to debug and see what route the script is taking, you can add another index in $data (i assume that $data is an array), so it would be like
if($registered){
$data['debug_logs'] .='Registration successfull----';
}
if($emailSent){
$data['debug_logs'].='Email sent for registration-----';
}
echo json_encode($data);
and then in your ajax success function you can use it like
success:function(data){
console.log(data.debug_logs);
}
hope it clears your confusion.
Please remove echo "Registered \n"; the line from your code when you echo "Register"; the Ajax request return this back to the browser, and your actual data echo json_encode($data); never return back to the browser.

Ajax Alert Response from PHP

Hopefully an easy question here. I actually used an example I found on SO but can't figure out why its not working. No errors in console or anything.
I have an ajax Post function I am using to pass data to a php script.
Its passing the data correct, but the response each time is coming back as an error alert. I can confirm that server side is getting the data and processing it correctly, just can't figure out why its never returning a success response.
Here is the Ajax:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
</script>
And in my php script I used this:
<?php
$success = true;
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => 'YAY'));
} else {
$output = json_encode(array('type'=>'error', 'message' => 'WHOOPS'));
}
die($output);
?>
The problem is that datatype: 'json' should be dataType: 'json'. Javascript is case-sensitive.
The error is because you received the returned data as json but the content type is a simple string (text/html) so you need to JSON.parse() the received data first like so:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
response = JSON.parse(response);
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
The second option is to send json headers from php itself thus removing the need of parsing JSON in javascript. You can do that by using the following line of code BEFORE ECHOING OR PRINTING ANYTHING ELSE FROM THE PHP SCRIPT:
header('Content-Type: application/json');
and then
echo $output;
If you are working with JSON responses, you need to set the header so your browser and your JavaScript could interpret it correctly:
<?php
$success = true;
if ($success == true) {
$output = json_encode(array(
'type' => 'success',
'message' => 'YAY'
));
} else {
$output = json_encode(array(
'type' => 'error',
'message' => 'WHOOPS'
));
}
header('Content-Type: application/json');
echo $output;

how do get correct error message using ajax json

Here i'm storing span values into a database. It's working fine. I'm now facing a problem with ajax return error message. For example in my save.php code i changed my database table name sample to simple (i don't have a simple database table). In the mainpage I want to get the error message like "this simple database table name doesn't exists". But it always shows Data saved succesfully.
I've searched on some other sites. Some people say I should use json to get the proper error message. But, I don't how to do that. How do I get the correct error message using json and ajax? I think this is very simple. But, I'm new to ajax.
save.php
<?php
include('config.php');
$get = $_POST['content'];
try
{
$stmt = $conn->prepare("INSERT INTO sample (divvalue) VALUES (?)");
$conn->errorInfo();
$stmt->bindParam('1', $get, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Error : ' .$e->getMessage();
}
if($stmt)
{
echo 1;
}
?>
ajax.js
$(document).ready(function() {
$("#save").click(function (e) {
var span_contents = $('#ele').html();
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: span_contents
},
success: function(data){
if(data == '1')
{
$('#status')
.addClass('return')
.html('Data saved succesfully')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
}
else
{
$('#status')
.addClass('error')
.html('Error occured')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
}
}
});
});
});
mainpage.php
<span id="ele" class="ele" contenteditable >element</span>
<input type="button" id="save" value="save" />
<br />
<div id="status"></div>
In your code i think every time it returns one. In your catch block you need to return another value like 0.
try
{
if($stmt){
echo "1";
}
}
catch(PDOException $e)
{
echo 'Error : ' .$e->getMessage();
}
Also you can add an error handler in ajax function like ,
$.ajax({
success: function(data){
if(data == '1')
{
$('#status')
.addClass('return')
.html('Data saved succesfully')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
}
else
{
$('#status')
.addClass('error')
.html('Error occured')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
}
},
//another handlers and properties
error:function(error){
$('#status')
.addClass('error')
.html('Error occured')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
}
});
Please update your code. It was ur PHP, which needs to echo on error too.
<?php
include('config.php');
$get = $_POST['content'];
try
{
$stmt = $conn->prepare("INSERT INTO sample (divvalue) VALUES (?)");
$conn->errorInfo();
$stmt->bindParam('1', $get, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
echo 'Error : ' .$e->getMessage();
}
if($stmt)
{
echo 1;
}
?>
And in your JavaScript too.
$(function() {
$("#save").click(function (e) {
var span_contents = $('#ele').html();
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: span_contents
},
error: function(data){//callback option is invoked, if the request fails.
$('#status')
.addClass('error')
.html('Error occured')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
},
success: function(data){//callback option is invoked, if the request succeeds.
$('#status')
.addClass('return')
.html('Data saved succesfully')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
});
});
});
You can do it as follows using json data
PHP :
<?php
include('config.php');
$get = $_POST['content'];
try
{
$stmt = $conn->prepare("INSERT INTO sample (divvalue) VALUES (?)");
$conn->errorInfo();
$stmt->bindParam('1', $get, PDO::PARAM_STR);
$stmt->execute();
if($stmt)
{
echo '{"status":1}';
}
}
catch(PDOException $e)
{
echo '{"status":0,"Error" : "' .$e->getMessage().'"}';
}
?>
JQUERY :
success: function(data){
$('#status')
.addClass('return')
.html(data.status?'Data saved succesfully':'Error'+data.Error)
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
},
dataType:'json'
I think
if($stmt)
{
echo 1;
}
Always evalute to true, try (for test) to do echo "2" without modify anything else.
Try also adding an echo in the catch block.
Also you can check with the devTools in the network tab what does the response return.
Please use the following syntax for your ajax call:
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: span_contents
},
success: function(data){
if(data == '1')
{
$('#status')
.addClass('return')
.html('Data saved succesfully')
.fadeIn('fast')
.delay(3000)
.fadeOut('slow')
},
error: function(data){
alert('Your error message here');
}
});
When ever you get an error, the error callback of the jquery ajax call will be fired
A Good standard way is to use JSON as below
catch
{
echo {"status":"failure","message":"The Error message goes here"};
}
if($stmt)
{
echo {"status":"success","message":"Data saved successfully"};
}
and in your ajax success function check like this
dataType:'json',
success: function(data){
if(data.status == 'success')
{
// do the required
}
else{
// do the required
}
}
You can add more variables as required like status and message in the return string

Categories