Hi i am using the following code to send an ajax request in my mobile application
var button = new Ext.Toolbar({
cls: "top_tool_bar2",
height: 35,
items: [this.text,
{xtype: 'spacer'},
{html: new Ext.XTemplate('<img style="width:.5em;height:.5em;" src="resources/imgs/down_arrow.png" />').apply({name: 'down_arrow'}),
handler: function () {
Ext.Ajax.request({
url: '/RadMobApp/api',
params:{
action:'invokeService',
serviceName: 'prescriptionService',
methodName: 'sampleClinicalInfo',
username: 'superuser',
password: 'superuser'
},
success: function(xhr) {
var response = Ext.decode(xhr.responseText);
// alert(response.diagnosis);
}
});
}}
]
});
I am getting an JSON response as like this
[{"systemReviewInfoMapListSize":1,"diagnosis":"Impaired hearing\nEarache \nEar noise","isClinicalSummaryAvail":"false","isSymptom":"true","isDiagnosis":"true","symptom":"Impaired hearing\nEarache \nEar noise","isSystemReviewInfo":"true"}]
how can i read this in my application... Thanks in advance.
You can try the following:
var data = Ext.JSON.decode(response.responseText.trim());
Assuming your response comes in as such: "id":123, "name": "Mac Arthur" then you should be able to access them like so:
alert("ID: " + data.id + "; Name:" + data.name);
Hope this helps
Related
I have an issue with ajax calling. It works correct except one thing, when I try to get data with the same option more than one times returns the new response but also still return the data of the previous response.
I think that there is something that I've missed.
ajax script
$('#search').on('click', function () {
var date = $("#date").val();
$.ajax({
type: 'GET',
url: '{{Route("dashboard.status")}}',
data: {
date: date
},
dataType: "JSon",
success: function(response){
console.log(response.manager_hourlog);
// Employee report script
var colors = ["#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"];
#if ($auth->user_type != 1)
// manager report script
var managerchartbar = {
labels: response.manager_projects,
datasets:
[{
label: response.users,
backgroundColor: colors[Math.floor(Math.random() * colors.length)],
data: response.totals
},]
};
var ctx = document.getElementById('manager').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: managerchartbar,
options: {
title: {
display: true,
text: 'Project Report chart'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
#endif
},
error: function(xhr){
console.log(xhr.responseText);
}});
});
});
</script>
You should change your method to POST for json request/response API, will be more secure and avoid laravel cache view it.
type: 'POST',
Try to change method to POST (do same for your api server and route).
If not work, please show your laravel API code.
you should set cache property to false or append "_={timestamp}" to the GET parameter
so add cache to your request:
cache:false
or append timestamp to your url:
url: '{{Route("dashboard.status")}}'+'_='+ + new Date().getTime(),
Hello I have one registration form of users as soon as user register in next browser tab i will get that registered user details without page refresh for this i got code from github project and tested that which is working perfectly and I have loaded jquery,socket.js file in both pages (data post,retrieving page)as they mentioned in that still i am not getting latest registered users without page refresh ,so please tell me where the code need to be correct.below is my code
code to post data(register users)
$("#submit").click(function(event){
event.preventDefault();
var dataString = {
name : $("#name").val(),
email : $("#wickets").val()
};
$.ajax({
url: "<?= base_url('User/register') ?>",
type: "POST",
data: dataString,
dataType: "json",
cache : false,
success: function (data) {
if (data.success == true) {
var socket = io.connect( 'http://'+window.location.hostname +':3000' );
socket.emit('registered_users', {
name: data.name,
email: data.email
});
}
}, error: function (xhr, status, error) {
alert(error);
},
});
});
code to get name and email of user who have just register by socket
html div tags to print user name and email
<div id="user_name"></div>
<div id="user_email"></div>
script for socket
var socket = io.connect( 'http://'+window.location.hostname+':3000' );
socket.on( 'registered_users', function( data ) {
$( "#user_name" ).prepend( data.name );
$( "#user_email" ).prepend( data.email );
});
We are new to angular js.
We tried http request using $http.get it is working fine. But in post request it is creating an issue, it comes to success and show bad parameter error code 103.
Same we have tried in ajax request using $.ajax({}), and it is working fine.
I have also paste my code.
Can anyone help us out?
mainApp.controller('registrationCtrl', function($scope, $location, $http) {
$scope.registration = function() {
console.log("registration called");
var ws_url = "http://apparelinindia.com/selfiestandoff/WebServices/register";
var request = $http({
method: "post",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
dataType: 'json',
headers: {
'Content-Type': 'application/json'
}
});
request.success(function(data) {
console.log("Success" + data);
});
request.error(function(error) {
console.log("Success" + JSON.stringify(error));
});
};
});
You can use http Post in following way:
var request = $http.post(ws_url, {
user_email: $scope.email,
user_password: $scope.password
});
The name of the http method should be written in uppercase. Also, the property datatype is not awaited by $http, you should remove it:
var request = $http({
method: "POST",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
headers: {
'Content-Type': 'application/json'
}
});
Note, in the above call to $http you are setting the header 'Content-Type': 'application/json'. But this header is automatically injected by $http (see $http documentation), therefore you can remove it, and use the short syntax:
var request = $http.post(ws_url, data);
with data equals to:
{
user_email: $scope.email,
user_password: $scope.password
}
Are You Getting this error ??
{"status":false,"error":{"code":"103","message":"Required Parameters not found"}}
If Yes, Its Not your Problem Contact the Web service provider.
Ask him to give the valid parameter
RESOLVED! see solution at bottom of this post...I have been stuck on this problem for about 2 days now and it's starting to get to me. I am trying to POST a Json array to my node server (cross-domain) and insert it to a cloudant db. This question is more about just getting the json over in the correct format. Here is my client side json and ajax:
function stress(){
var start = new Date().getTime();
$.ajax({
type: 'POST',
url: 'url/',
crossDomain: true,
data: JSON.stringify(products),
dataType: 'json',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function(responseData, textStatus, jqXHR) {
var end = new Date().getTime();
var millis = (end - start);
var duration = (millis/1000);
alert(responseData.msg +'Duration(seconds): ' + duration);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
}
});
}
var products = [
{
name: 'War Room Table',
year: '2005',
color: 'tan',
country: 'USA',
description: 'A Beautiful War Room table. Includes all 4 legs!',
usaDollarPrice: 150
},
{
name: 'Power Strip',
year: '2000',
color: 'white',
country: 'USA',
description: 'A very old power strip, may or may not protect against power surges.',
usaDollarPrice: 16
}];
My Node.js server side:
exports.create = function(req, res) {
var data = req.body;
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Content-Type', 'application/json');
//var parsed = JSON.parse(data);
var msg = {};
for(product in data){
db.insert(data[product], function (err, body, headers) {
if (!err) {
msg.msg = 'success!';
console.log(JSON.stringify(msg);
}
else {
msg.msg = 'Error on insert, maybe the item already exists: ' + err
console.log(JSON.stringify(msg);
}
});
}
}
I have tried a multitude of different things. What I basically want is a object on the server side that I can iterate through and insert to the cloudant database, each as a separate doc. I have tried many combinations of JSON.stringify and JSON.parse. using parse has given no luck as I get an error saying SyntaxError: Unexpected token o which I read that means it is already an object, but I cannot access data in any way ( data[0], data.name, data[0].name, nothing on the server side). I have also tried sending the json from the client side in different ways (in ajax - data: JSON.stringify({prod:products}) and still no luck.
Having the json on the server side (same as products above) inserts the docs in the correct order, the problem is when I sent that same json over a ajax post and to a cross-domain server. I cannot get that json out. Any idea or help would be very appreciated, thanks
Solution:
I ended up putting the object into another array and using that to be sent to the server. Here is the working ajax in the client side, notice the data:{data:products} that's what did it for me. Also below is the products json and also how to access it on the nodejs server side.
$.ajax({
type: 'POST',
url: 'url/',
crossDomain: true,
data: {data:products},
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
var end = new Date().getTime();
var millis = (end - start);
var duration = (millis/1000);
alert(responseData.msg +'Duration(seconds): ' + duration);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed. ' + JSON.stringify(responseData) + " status: " + textStatus + " Error: " + errorThrown);
}
});
var products = [
{
name: 'War Room Table',
year: '2005',
color: 'tan',
country: 'USA',
description: 'A Beautiful War Room table. Includes all 4 legs!',
usaDollarPrice: 150
},
{
name: 'Power Strip',
year: '2000',
color: 'white',
country: 'USA',
description: 'A very old power strip, may or may not protect against power surges.',
usaDollarPrice: 16
}];
Here is how to access it on the server side. Keep in mind this is all for cross-domain Post, but should work otherwise.
exports.create = function(req, res) {
var body = req.body;
//body.data[0] will get you the first object in the json, in this case it will be the war room table.
//If you use console.log to see it make sure you JSON.stringify(body.data[0]) or else you wil see [Object] [Object]
Also very important to include this in your server/app.js The extended: true part is important. Example
app.use(bodyParser.urlencoded({ extended: true }));
You are stringifying the json data before sending it to the node server, try only
data:products You will also need the node module body-parser using it you will be able to access POSTed data through ajax, see this answer also
I am new to ajax. Please check if this helps. I think I had a similar problem which is solved now.
Please see the answer posted by me
How to send array of arrays as data in $.ajax()?
We are building an application using Sencha Touch 1.1 and PhoneGap 1.3.0 for deployment to iOS.
Our app makes several AJAX requests to authenticate a user and retrieve data from the server. All of our requests execute correctly with the exception of attempting to authenticate using invalid credentials.
I am using Weinre to debug the app running in the iOS simulator.
In the Network pane the request hangs on "Pending", and in the console I receive the following error:
error occurred: undefined:[unknown lineno]: ReferenceError: Can't find variable: request
this error appears when the timeout value has been reached.
Here's the code for my controller:
Ext.regController('Login', {
login: function(options)
{
var loader = this.application.viewport.query('#loader')[0];
loader.show();
var string = options.user + ":" + options.pass;
var encodedString = Ext.util.Base64.encode(string) + "==";
Ext.Ajax.defaultHeaders = { Authorization: "Basic " + encodedString};
Ext.Ajax.request({
url: 'http://test.com/login.do',
method: 'POST',
timeout: 5000,
scope: this,
callback: function (options, success, response) {
if (success){
buildingStore.load({
callback: function (){
Ext.redirect('Main/loggedIn');
loader.hide();
}
});
Ext.redirect('Main/loggedIn');
}
else {
alert("failed");
console.log(response.status);
loader.hide();
var loginFailure = new Ext.Panel ({
floating: true,
centered: true,
floating: true,
modal: true,
layout: 'fit',
cls: 'loginError',
html: '<h12>Login was unsuccessful.<br>Please try again.</h12>',
});
loginFailure.show();
}
}
});
Ext.Ajax.on({
requesterror: function(conn, response, options, e){
alert("error");
},
requestexception: function(conn, response, options, e){
alert("exception");
}
});
},
});
and a screenshot of Weinre:
Thanks for your help!
Kevin
Upgrading to sencha touch 1.1 fixes this issue. Credit to #kev_additct. Just putting it in an answer rather than a comment where it already is