Passing custom error code to ajax error function - javascript

I'm trying to pass custom error code to the client-side to ajax error function.
In the server side:
$response = array();
if ( empty($post['parent_id']) ) {
$response = array('error' => true, 'status_code' => -2);
exit();
}
$is_valid_id = RC()->is_valid_id($post['parent_id']);
$row = RC()->get_row_data($post['parent_id']);
if ( ! $is_valid_id ) {
$response = array('error' => true, 'status_code' => -1);
} else if ( ! $row ) {
$response = array('error' => true, 'status_code' => 0);
} else {
$response = json_encode($row);
}
echo $response;
Then I want to check for this status code in my js script, but couldn't find a way to do this (found ways only without trigger the error event).
$.ajax({
url: ajax_url,
data: {
'action': 'rc_parent_sign_in',
'form_data': $('#parent-sign-in-form').serialize(),
'security': security_nonce
},
type: "post",
dataType: "json",
cache: false,
success: function (response) {
var query_vars = $.param(response);
window.location.replace('http://localhost/renecassin/user-registration/?' + query_vars);
},
error: function (response) {
$('.form-control-feedback').addClass('hide');
/* Looking for something like this */
switch ( response.status_code) {
case -2 :
parent_id_form_group.addClass('has-danger').children('#empty-field').
removeClass('hide');
prent_id_input.addClass('form-control-danger');
break;
case -1 :
parent_id_form_group.addClass('has-danger').children('#not-valid-id-feedback').
removeClass('hide');
prent_id_input.addClass('form-control-danger');
break;
default :
parent_id_form_group.addClass('has-danger').children('#id-not-exists-feedback').
removeClass('hide');
prent_id_input.addClass('form-control-danger');
}
}
});
Any help will be appreciate.

It's because the response will go to your response callback, you are successfully returning an object.
The error callback will only be called if the request itself failed (timeout,404 etc..)
You need to handle your internal error codes in your success callback

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:

Not able to display the JSON success output in the view or alert

I am using CodeIgniter, I have a three input field called as name, emp_id,crm_id. I am entering the id value and sending to the controller to get all the information related to that id using AJAX an JSON. Now the issue is, I am getting the correct output in the network tab but not able to display in the view page even alert is also not displaying in the JSON.
Sometimes I am getting below error because of JSON is empty
[Show/hide message details.] SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I think there is some issue with JSON.
Ajax
$("form[name='search_addSalaryrecord']").validate({
// errorElement: 'div',
submitHandler: function(form) {
//alert(baseUrl);
var employee_name = $('#employee_name').val();
var crm_id = $('#crm_id').val();
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_name: employee_name,crm_id:crm_id,employee_id:employee_id},
success: function(response) {
//$('.search_record tbody').html(response);
// var data = JSON.parse(response);
//alert(data.status);
if (response.status === 'error')
{
alert(response.msg);
}
if (response.status === 'success') {
//alert('data avaliable');
alert(response.records);
console.log(response.records);
}
}
//error: function(error) { console.log(error); }
});
}
});
Controller
public function search_addSalaryrecord()
{
$employee_name=trim($this->input->post('employee_name'));
$emp_crmid=trim($this->input->post('crm_id'));
$employee_id=trim($this->input->post('employee_id'));
if((!empty($employee_name)) ||(!empty($emp_crmid)) || (!empty($employee_id))){
$arr_result =$this->Employee_model->get_salary_search_emp_id($employee_name,$emp_crmid,$employee_id);
if (!empty($arr_result)){
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
"employee_id" => $row->employee_id,
"month_year" => $row->month.' '.$row->year
);
}
//print_r($result);
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($arr_result);
exit;
}
Hope this will help you :
Use dataType: "json" in your ajax to avoid further parsing of response and return json_encode data with exit from your controller
Your ajax should be like this :
$("form[name='search_record']").validate({
submitHandler: function(form)
{
var employee_id = $('#employee_id').val();
$.ajax({
url: baseUrl + "/Employee_control/search_addSalaryrecord",
method: "POST",
dataType: "json",
data: {employee_id:employee_id},
success: function(response) {
//alert(data.status);
if (response.status == 'error')
{
alert(response.msg);
$('.personel_info').empty();
}
if (response.status == 'success')
{
alert(response.records);
$('.personel_info').empty();
$('.personel_info').show();
var trHTML = '';
$.each(data.records, function (i, o){
$('#name_emp').text(o.name);
$('#mobileno_emp').text(o.mobileno);
$('#employee_email').text(o.employee_email);
});
}
}
});
}
});
Your controller's method search_addSalaryrecord should be like this :
public function search_addSalaryrecord()
{
$employee_id = trim($this->input->post('employee_id'));
if(!empty($employee_id))
{
$arr_result = $this->Employee_model->get_salary_search_emp_id($employee_id);
if (! empty($arr_result))
{
foreach ($arr_result as $row)
{
$result[] = array(
"name" => $row->firstname.' '.$row->lastname,
"mobileno" => $row->mobileno,
"email_id" => $row->email_id,
);
}
$respnonse['status'] = 'success';
$respnonse['records'] = $result;
}
else
{
$respnonse['status'] = "error";
$respnonse['records'] = "No record found";
}
}
echo json_encode($respnonse);
exit;
}

JQuery Ajax goes in error

My ajax function goes in error after I set the dataType to Json.
That's the code:
Ajax script:
$('#da').on("change",function() {
$.ajax({
url: "callAjaxIndex.php",
type: "POST",
dataType: "json",
data: {
method: 1,
id: $('#da').val(),
},
success: function() {
alert('test');
},
error: function() {
alert('error');
}
});
});
callAjaxIndex.php
<?PHP
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as 'nome_arrivo', tratte.id as 'id_arrivo' FROM tariffe, tratte WHERE id_arrivo = tratte.id AND id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
?>
What's wrong?
Thank you
You can try this
$(document).on('change', '#da', function(){
$.post("callAjaxIndex.php", {'method': 1, 'id': $(this).val()}, function(data){
var d = $.parseJSON(data); //here is the data parsed as JSON
//data is that returned from callAjaxIndex.php file
});
});
<?php
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as nome_arrivo, tratte.id as id_arrivo FROM tariffe INNER JOIN tratte ON id_arrivo = tratte.id WHERE id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
You can find out the error by changing your function to this:
//other code
error: function(data)
{
console.log(data.responseText)
}
//other code
This will tell you why it fails, might be something generic but better than 'error'
Also note:
this was done from a phone so excuse any mistakes
I'd rather this be treated as a comment until I can get to a machine to help more :)

Infinite scroll in Symfony using Ajax

I wanted to show products from db using infinite scroll.
Here is my Controller:
$start=0;
$limit= 6;
$query = $repository->createQueryBuilder('classified')
->join('classified.statusId','status')
->andWhere('status.name=:status')
->setParameter('status','active')
->setFirstResult($start)
->setMaxResults($limit)
->getQuery();
$results = $query->getResult();
if ($request->isXmlHttpRequest()){
$list = $this->renderView('search-result.html.twig', [
'results' => $results
]);
$response = new JsonResponse();
$response->setData(array('classifiedList' => $list));
return $response;
}
Ajax:
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
getmoredata();
}
})
function getmoredata() {
$.ajax({
type: "GET",
url: "{{ path('classified_list', {'type' : 'all'}) }}",
dataType: "json",
cache: false,
success: function (response) {
$('.card-deck').append(response.classifiedList);
$('#spinner').hide();
console.log(response);
},
error: function (response) {
console.log(response);
}
});
}
So now what is happening is the first 6 results is repeatedly showing when the scrolling is triggered. I know this is not correct and I don't expect this to work properly. But what I don't know is what is the next step.
So do I need to add paginator or something?
Any help would be appreciated,Thanks!
You need to track whether your ajax is requesting or not, so it will not do request multiple times when window reach the scroll limit. Also, you need to track the offset and whether you have more data to loads. e.g
window.__isFetching = false;
window.__offset = 0;
window.__hasMoreData = true;
$(window).scroll(function () {
if($(window).scrollTop() + $(window).height()>= $(document).height()){
if(!window.__isFetching && window.__hasMoreData) {
getmoredata();
}
}
})
function getmoredata() {
window.__isFetching = true;
$.ajax({
type: "GET",
// NOTE, you can pass current offset here in url
url: "{{ path('classified_list', {'type' : 'all', }) }}"+"&offset="+window.__offset,
dataType: "json",
cache: false,
success: function (response) {
$('.card-deck').append(response.classifiedList);
$('#spinner').hide();
console.log(response);
// Note that here, server side response must have next offset and hasMoreData attribut.
window.__isFetching = false;
window.__hasMoreData = response.hasMoreData;
window.__offset = response.offset
},
error: function (response) {
console.log(response);
}
});
}
in server side , which is symfony, you might want to do something like:
// Get offset from request query
$start= $request->query->get('offset');
$limit= 6;
$query = $repository->createQueryBuilder('classified')
->join('classified.statusId','status')
->andWhere('status.name=:status')
->setParameter('status','active')
->setFirstResult($start)
->setMaxResults($limit)
->getQuery();
$results = $query->getResult();
if ($request->isXmlHttpRequest()){
$list = $this->renderView('search-result.html.twig', [
'results' => $results
]);
$response = new JsonResponse();
// And add offset and hasMoreData fields in response
$response->setData(array(
'classifiedList' => $list,
'offset' => $start += 1
'hasMoreData' => count($list) < ($limit * &start)
)
);
return $response;

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;

Categories