Get variable from Sencha Touch Ext.data.JSONP.request response - html

I'm trying to get a boolean (success) and a HTML string (result) from the response to an Ext.data.JsonP.request, but I can't fgure out how. Here's the code I have so far:
Ext.data.JsonP.request({
url: 'http://wereani.ml/shorten-app.php',
callbackKey: 'callback',
params: {
data: Ext.encode(values)
},
success: function(response) {
console.log(response);
console.log(JSON.stringify(values));
console.log('Link Shortened');
if(response.responseText['success'] == true) {
Ext.Msg.alert('Link Shortened', response.responseText, Ext.emptyFn);
} else {
Ext.Msg.alert('Error', response.responseText, Ext.emptyFn);
}
form.reset();
},
failure: function(response) {
console.log(response);
console.log(JSON.stringify(values));
console.log('Error');
Ext.Msg.alert('Error', 'Please try again.', Ext.emptyFn);
}
});
Some sample JSON-P:
callback({"success":false,"result":"<div class=\"error\">Please enter a valid link to shorten!<\/div>"})
The error I'm currently getting is Uncaught TypeError: Cannot read property 'success' of undefined.
Thanks in advance for the help!
EDIT: It seems that while response is Object {success: false, result: "<div class="error">Please enter a valid link to shorten!</div>"}, response.responseText is undefined. Am I using the wrong variable? I couldn't find any documentation on response.
EDIT 2: It seems that the reason Console.log(response.responseText) was returning undefined is because it.... was. The JsonP-encoded variables (success and result) that I passed were parsed automatically into the object, and response.responseText was never created (though I think it was supposed to be). The solution was to just read response.success and response.result directly!
ANSWER: Here's the code that worked. Thanks to Viswa for the help!
Ext.data.JsonP.request({
url: 'http://wereani.ml/shorten-app.php',
callbackKey: 'callback',
params: {
data: Ext.encode(values)
},
success: function(response) {
if(response.success === true) {
Ext.Msg.alert('Link Shortened', response.result, Ext.emptyFn);
} else {
Ext.Msg.alert('Error', response.result, Ext.emptyFn);
}
form.reset();
},
failure: function(response) {
console.log('Error');
Ext.Msg.alert('Error', '<div class="error">Please try again.</div>', Ext.emptyFn);
}
});

Try like this
Ext.data.JsonP.request({
url: 'http://example.com/script.php',
callbackKey: 'callback',
params: {
data: Ext.encode(values)
},
success : function(response) {
console.log("Spiffing, everything worked");
// success property
console.log(response.success);
// result property
console.log(response.result);
},
failure: function(response) {
console.log(response);
Ext.Msg.alert('Error', 'Please try again.', Ext.emptyFn);
}
});

Related

History.go(-1) does not work in chrome extension

I am creating a chrome extension that goes back to a certain site. But history.go(-1);The syntax is not working Why?
chrome.tabs.executeScript({
code: 'document.URL;'
}, function (domain) {
var google = 'https://www.google.co.kr/';
if (domain == google) {
history.go(-1);
}
else
alert('not google')
$.ajax({
type: 'GET',
url: 'http://www.mhwdb.kr/main/apis/monsters',
// data: {
// url: domain
// },
// dataType: 'json',
success: function(success){
document.getElementById('url').innerHTML = success;
},
error: function(error) {
console.log(error);
}
})
})

prevent AJAX success result to download file or open

I have this jquery to make a post request:
$('#btnAdd').click(function (e) {
$('#modal_processing').modal('show');
$('#modal_body_process').html("Please wait while we are processing your request. This message will automatically close when request successfully completed.");
$('#modal_title_process').html("Processing...");
$.ajax({
url: '#Url.Action("AddNew", "Home")',
type: 'POST',
data: {
Name: $('#txtEmail').val(),
Project: $('#cbProject').val(),
Gender: $('#cbGender').val(),
Level: $('#cbLevel').val(),
ShiftStart: $('#txtShiftStart').val(),
ShiftEnd: $('#txtShiftEnd').val(),
GeoId: $('#cbGeo').val(),
TowerId: $('#cbTower').val(),
ProcessId: $('#cbProcess').val(),
PrimaryTeamId: $('#cbPrimaryTeam').val(),
RegionId: $('#cbRegion').val(),
WBSId: $('#cbWBS').val(),
},
dataType: "json",
success: function (response) {
$('#modal_body_process').html("New user has been successfuly added.");
$('#modal_title_process').html("Successful!");
setTimeout(function () {
$('#modal_processing').modal('hide');
}, 3000);
},
error: function (resp) {
$('#modal_body_process').html("Please fill out all required fields.");
$('#modal_title_process').html("Error");
setTimeout(function () {
$('#modal_processing').modal('hide');
}, 3000);
alert("Error");
}
});
});
in my controller, i have this:
if (result.IsSuccessStatusCode)
{
ModelState.Clear();
return Json(result.StatusCode, JsonRequestBehavior.AllowGet);
}
return View(model);
my problem is, everytime the result is success, it always prompting me to download the json file (IE 11) and for mozilla, it opens the json file.
how can i prevent this?

“Invalid JSON primitive” in Ajax processing MVC

I have some problems with an ajax call.
Here is the function:
function jsFunction(value) {
var selectedCompany = document.getElementById("CompanyId");
var selectedCompanyId = selectedCompany.options[selectedCompany.selectedIndex].value;
$.ajax({
type: "POST",
data: { companyId: selectedCompanyId, supplierId: value },
url: "#Url.Action("CheckContract", "PaidWork")",
dataType: 'json',
traditional: true,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response) {
if (response != null && response.success) {
document.getElementById("errorMessage").style.display = 'hidden';
alert(response.responseText);
} else {
// DoSomethingElse()
document.getElementById("errorMessage").style.display = 'visible';
alert(response.responseText);
}
},
error: function (response) {
alert("error!"); //
}
});
}
This is the div for the message
<div id="errorMessage" style="display:none"><strong class="alert-danger">#ViewBag.MessageContractNotExist</strong></div>
In my view I have a message which I want to display or not, depends on what response Json send me from controller.
This is the method in controller:
public ActionResult CheckContract(int companyId, int supplierId)
{
bool result = true;
if (!spService.ContractExists(companyId, supplierId, ContractType.SupplierSilviPrio))
{
result = false;
}
if(!result)
{
ViewBag.MessageContractNotExist = "Not exist!!!";
return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
}
The problem is that I keep getting this error: invalid json primitive object
Can you please help me what I miss here? Thanks

no display fail message from controller

I need validate user's nickname when the gonna registre in my proyect:
My Controller
$inputData = Input::get('nickname');
parse_str($inputData);
$informacion = array('nickname' => $inputData);
$regla = array('nickname'=>'required|unique:usuarios|alpha_num|min:6|max:15');
if($request->ajax()){
$usuarios = Usuarios::Usuarios();
$validar = Validator::make($informacion,$regla);
if($validar->fails()){
return Response()->json(array(
'fail' => true,
'errors' => $validar->getMessageBag()->toArray()));
}
else{
return Response()->json(array('success' => true, "message" => "Nombre de Usuario Disponible"));
}
}
My Script
$( "#validar" ).click(function( event ) {
var dato = $('#nickname').val();
var route = $('#form-sign-up').attr('action');
var tipo = $('#form-sign-up').attr('method');
var token = $('#form-sign-up #token').val();
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{nickname: dato},})
.fail(function(data){
$('#nickname-msj').html(data.errors);
$('#nickname-msj').fadeIn();
})
.done(function(data) {
$('#nickname-msj').html(data.message);
$('#nickname-msj').fadeIn();
});
});
.done works, but .fails not, and i need display that information to my user, because so they can know what is the problem, if someone can help me will be great.
I am using Laravel 5.2
Thank you.
The fails function of Ajax is triggered with a code different from 200. So you can return
if($validar->fails()) {
return response()->json($arrayHere, 400); //HTTP 400 error for bad request
}
So, just basically add 400 after your array, inside of json() function. When you don't specify the code, it defaults to 200.
Maybe also change your ajax request ? Or not
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{
nickname: dato
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});

How do get jquery fullcalendar to pass additional parameters to my json feed script

My code is as follows
jQuery('#calendar').fullCalendar({
weekMode: 'liquid',
events: themeforce.events,
eventRender: function (event, element) {
element.find('span.fc-event-title').html(element.find('span.fc-event-title').text());
}
});
where themeforce.events is a variable containing an encoded url of the json feed a php file - all works well.
I tried replacing events: themeforce.events, with
events: {
url: themeforce.events,
type: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
However now the calendar fails to load.
What can I do?
I wanted the start and end times for a post ajax request and it took me a bit of time to work it out.
This might help you:
events: function(start, end, timezone, callback) {
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: {
start: start.format(),
end: end.format(),
custom_param1: 'value 1',
custom_param2: 'value 2',
},
error: function () {
alert('there was an error while fetching events!');
},
success: function(doc) {
var events = [];
$.each(doc,function (index, e) {
events.push(e);
});
callback(events);
}
});
}
You should use extraParams as explained in doc : https://fullcalendar.io/docs/events-json-feed
var calendar = new Calendar(calendarEl, {
eventSources: [
// your event source
{
url: '/myfeed.php',
method: 'POST',
extraParams: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
]
});
Also be sure your feed's url return raw json data array !
Just put "data" instead of "extraParams" in "events"
events: {
url: 'service.php',
method: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function() {
alert('there was an error while fetching events!');
},
}