here is my function sending ajax request for checking email duplication while getting response from my php file , not falling on failure function it returns only in success function , for this i have checked result.responseText == to "false" and with else condition now in this condition it shows the error popup message too but donot abort the request continuoues its execution and saves the data
function email_check(userType) {
//alert(userType);
var extmail= Ext.Ajax.request({
url: '<?= Extjs_renderer::ajaxurl();; ?>ajax/emailcheck',
success: function ( result, request ) {
if(result.responseText=='false'){
//Ext.Ajax.abort(extmail); tried
Ext.MessageBox.alert('Error', "email already exist");
// return false;
//Ext.getCmp('email').setValue(''); works
}else {
return true;
}
},
failure: function(response, options) {
Ext.MessageBox.alert('Error', "email already exist fail");
},
params: {merc_mem_tab:userType }
});
}
here is my ajax.php code
function emailcheck(){
$get_email=$this->db->query("select * from customers where email='".$_REQUEST['merc_mem_tab']."'");
if($get_email->num_rows==0){
echo "true";
return true;
}else{
echo "false";
// echo "{success: true}";
return false;
}
}
while on my panel handler i am also trying to check the response but could not succeeded
if('<?= $this->controller->name; ?>'=="customers"){
//alert(Ext.getCmp('email'))
if(email_check(Ext.getCmp('email').getValue()) == false){
return false;
}
}
You can't return from an ajax request, It is asyncron, and this bit of code if(email_check(Ext.getCmp('email').getValue()) == false) won't wait for the answer.
Also the failure is as Imad said, just for http failures not for false responses. your code to check for response false was correct but i suggest you call a saving method on the success function.Like:
function email_check(userType) {
//alert(userType);
var extmail= Ext.Ajax.request({
url: '<?= Extjs_renderer::ajaxurl();; ?>ajax/emailcheck',
scope: this,
success: function ( result, request ) {
if(result.responseText=='false'){
Ext.MessageBox.alert('Error', "email already exist");
//do nothing else
}else {
this.saveData();
}
},
failure: function(response, options) {
Ext.MessageBox.alert('Error', "Communication failed");
},
params: {merc_mem_tab:userType }
});
}
The choice of success or failure callback is based on the HTTP response code. So, if you want to reach the failure function, you'll have to do some :
function emailcheck(){
$get_email=$this->db->query("select * from customers where email='".$_REQUEST['merc_mem_tab']."'");
if($get_email->num_rows==0){
echo "true";
return true;
}else{
throw new Exception("Error : Email Already Exists !");
}
}
It should provoke an error 500 (exception unhandled) and ExtJS will identify it as a failure response.
Related
I have a project in Cakephp 3.6 in which 3 actions in MessageController are called by Ajax. I have a problem, however, when I send a request to one of the action, XHR returns to me this:
{
"message": "CSRF token mismatch.",
"url": "\/messages\/changepriority\/8",
"code": 403,
"file": "D:\\xampp\\htdocs\\myapp\\vendor\\cakephp\\cakephp\\src\\Http\\Middleware\\CsrfProtectionMiddleware.php",
"line": 195
}
This is one of the action what I try to call from Ajax:
public function changepriority($id=null)
{
$this->autoRender = false;
$message = $this->Messages->get($id);
$message->priority = ($message->priority === false) ? true : false;
if ($this->Messages->save($message)) {
echo json_encode($message);
}
}
And this is my ajax:
$(".email-star").click(function(){
var idmessage = this.id;
$.ajax({
headers : {
'X-CSRF-Token': $('[name="_csrfToken"]').val()
},
dataType: "json",
type: "POST",
evalScripts: true,
async:true,
url: '<?php echo Router::url(array('controller'=>'Messages','action'=>'changepriority'));?>' +'/'+idmessage,
success: function(data){
if(data['priority'] === false) {
$("#imp_" + idmessage).removeClass("fas").removeClass('full-star').addClass( "far" );
}
else {
$("#imp_" + idmessage).removeClass("far").addClass( "fas" ).addClass("full-star");
}
}
});
});
I have read the documentation about Cross Site Request Forgery, and I tried to turn off the Csrf for these action first with:
public function beforeFilter(Event $event)
{
$this->getEventManager()->off($this->Csrf);
}
and then with:
public function beforeFilter(Event $event)
{
$this->Security->setConfig('unlockedActions', ['index', 'changepriority']);
}
But nothing. The Xhr return always the CSRF token mismatch.
What can I do ?
Edit:
I change the action in this way:
public function changepriority($id=null)
{
$this->autoRender = false;
$message = $this->Messages->get($id);
$message->priority = ($message->priority === false) ? true : false;
if ($this->Messages->save($message)) {
$content = json_encode($message);
$this->response->getBody()->write($content);
$this->response = $this->response->withType('json');
return $this->response;
}
}
In that way the action works. Can it be like that?
First check your $('[name="_csrfToken"]').val() output.
If you didn't get any output, need to check csrfToken hidden field is exist or not. Just right click in your page and click View Page Source
If not exist, you don't follow proper way when you create Form. Basically, when forms are created with the Cake\View\Helper\FormHelper, a hidden field is added containing the CSRF token.
If everything is correct, add the following line inside your ajax call after header
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
},
Ps. Disabling the CSRF is not recommended by cakePHP and most of the developer aware of this. Hope this help.
beforeSend: function (xhr) {
xhr.setRequestHeader('X-CSRF-Token', <?= json_encode($this->request->getAttribute('csrfToken')) ?>);
},
I am following this solution to implement a timeout in a http call to a remote server.
This is the calling function; if the request returns null then the alert will be put into view:
this.service.getAll().subscribe(response => {
console.log("home.page: calling servuce for data...data returned is : " + response);
if (response != null ){
this.tests = response;
this.searching = false; //Turn spinner off
}else{
//http timeout after 2000ms
this.alertCtrl.create({
header: "Connection Timeout",
message: "Check your internet connection!",
buttons: [
{
text: "Ok"
}
]
}).then(alert => alert.present());
This is the http service; if the http call times out after 10s (1000ms) null will be returned to the caller (above):
import { timeout, catchError } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
getAll(){
//return this.http.get<[Student]>(this.url);
console.log("student.service-59- GET ALL called..etunr null if times out after 10000ms");
return this.http.get<[Test]>(this.url)
.pipe(
timeout(10000),
catchError(e => {
console.log("student service GET ALL timed out, retunr null, error = ");
return of(null);
})
)
}
However when I test with the internet connection off the alert / prompt appears immediately and does not appear to wait 10seconds as defined in the timeout argument.
Any idea why this is the case?
I want to get value of an array from JSON code in internet. from this URL : http://olympics.clearlytech.com/api/v1/medals/
after that, I want to display that array of my script without rewrite that JSON code on this URL http://olympics.clearlytech.com/api/v1/medals/
so, what code (script) that I can use?
for example, I want to display value from this array
var JSONs = {
example:['one','two','three']
};
the code is
document.write(JSONs.example[0]);
but if I want get the array value from the internet, what code/script that I can use?
Using jQuery, here is an example. In the success event, turn the resulting json text into a json object. You could also set the content type as json so you wouldn't have to call the JSON.parse().
$.ajax({
url: "http://olympics.clearlytech.com/api/v1/medals/",
success: function(data) {
var json = JSON.parse(data);
}
});
This is another way of doing the same i hope you asked how to parse through each value just try this in jsfiddle
$(document).ready(function(){
alert("here");
$.getJSON("http://olympics.clearlytech.com/api/v1/medals/",function(data){
$.each(data,function(key,value){
alert(data[key].country_name);
alert(data[key].rank);
console.log(data[key].rank));
});
});
});
public void handleResponse(String response)
{
// display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
jso = new JSONObject(response);
String status = jso.getString("status");
int valid=jso.getInt("valid");
// display("Welcome : "+UName);
if(valid>0)
{
if( status.equalsIgnoreCase("") || status==null || status.equalsIgnoreCase("Failed"))
{
invalid.setText("Invalid password");
//reset();
pwd.setText("");
}
else
{
//display(status);
intObj=new Intent(MainActivity.this,Design_Activity.class);
intObj.putExtra("Username", mUname);
startActivity(intObj);
MainActivity.this.finish();
}
}
else
{
invalid.setText("Invalid userid");
uname.setText("");
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}
Althought you want us to do everything, thats why your question went negative. Anyhow this is how you can do it in plain ajax
function getData(){
// Initialize the Ajax request
var xhr=new XMLHttpRequest();
xhr.open('get', 'http://olympics.clearlytech.com/api/v1/medals/');
// Track the state changes of the request
xhr.onreadystatechange=function(){
// Ready state 4 means the request is done
if(xhr.readyState === 4){
// 200 is a successful return
if(xhr.status === 200){
alert(xhr.responseText); // 'This is the returned text.'
}else{
alert('Error: '+xhr.status); // An error occurred during the request
}
}
}
// Send the request to send-ajax-data.php
xhr.send(null);
}
I've the following code:
eventResourcesCall = $http.jsonp('https://apicall/to/serverA');
eventsDetailsCall = $http.get('https://apicall/to/serverB');
$q.all([eventResourcesCall, eventsDetailsCall]).then(function(values){
//process data manipulation and merging
});
The problem is that serverA and ServerB might not be available sometimes, and when one of those are unavailable, the data processing code stops and I get an error similar to the one described below:
GET https://apicall/to/serverA?jsonp=angular.callbacks._0 404 (Not Found)
Can any one point me to a documentation or describe on the answer how to properly deal with unavailable URL requested by $http and executed by $q.all()?
What I would like to be able to do is to get an indication that the URL is not accessible and then avoid the data processing code abortion.
Thanks!
I would use indirect promises:
var d1 = $q.defer(), d2 = $q.defer();
function NetworkError(reason) { this.reason = reason; }
eventResourcesCall = $http.jsonp('https://apicall/to/serverA').then(
function(response) {
d1.resolve(response);
},
function(err) {
d1.resolve(new NetworkError(err));
}
);
eventsDetailsCall = $http.get('https://apicall/to/serverB').then(
function(response) {
d2.resolve(response);
},
function(err) {
d2.resolve(new NetworkError(err));
}
);
$q.all([d1, d2]).then(function(values){
var eventResources = values[0], eventsDetails = values[1];
if( eventResources instanceof NetworkError ) {
// handle error
}
else {
// eventResources is good, use it
}
// and so on...
});
So the indirect promises are allways resolved and the all() succeeds. But the resolution value may be of the special NetworkError class which signals the actual error in this request.
This is definitely bulky, but could be improved with some utility methods, e.g.:
function makeIndirectPromise(httpPromise) {
var ret = $q.defer();
httpPromise.then(
function(response) {
ret.resolve(response);
},
function(err) {
ret.resolve(new NetworkError(err));
}
);
return ret.promise;
}
And the code above changes to:
function NetworkError(reason) { this.reason = reason; }
function makeIndirectPromise(httpPromise) { /* see above */ }
eventResourcesCall = makeIndirectPromise($http.jsonp('https://apicall/to/serverA'));
eventsDetailsCall = makeIndirectPromise($http.get('https://apicall/to/serverB'));
$q.all([eventResourcesCall, eventsDetailsCall]).then(function(values){
var eventResources = values[0], eventsDetails = values[1];
if( eventResources instanceof NetworkError ) {
// handle error
}
else {
// eventResources is good, use it
}
// and so on...
});
From Angular doc to $q: as $http returns a promise, you can catch promise rejection using either:
$q.all([eventResourcesCall, eventsDetailsCall]).then(function(values){
//process data manipulation and merging on Success
}).catch(function(errors){
//Deal with your $http errors
}).finally(function(data){
});
or
$q.all([eventResourcesCall, eventsDetailsCall]).then(function(values){
//process data manipulation and merging on Success
}, function(errors){
//Deal with your $http errors
});
I have a success callback function which returns the following always :
{"ss":0,"me":"Invalid Username or Password"}
success :function(result){
console.log("RESULT : "+result.ss);
}
But this always ends up as undefined.. If i print the result, i get the above array. If i return result.ss or result.me i get undefined.
I think there is a very silly reason for why this is happening, but i cannot get my head around.
Backbone View(removing other codes) :
this.model.save({un : username,pd : password, ky : ky}, {
success :function(result){
console.log("RESULT : "+result.ss);
return false;
if(result.ss==1){
$("#login_message").addClass('alert-success');
var userType = result.pp.ut;
if(userType=="T"){
window.location.href="trainer/index.html";
}else if(userType=="C"){
window.location.href="clients/index.html";
}else if(userType=="A"){
window.location.href="admin/index.html";
}else{
return false;
}
return false;
}
if(result.ss==0){
console.log(result);
$("#login_message").addClass('alert-error');
console.info("Failed to Log In.");
}
return false;
},
error: function(res){
console.log(res);
return false;
}
});
return false;
Backbone success function has the result parameter after model parmeter, you are using model instead of result.
success:function(model, response){}