Ajax send image to server - javascript

I am working phonegap application. I want to send data image to server but i can not sent it.
function addSiteToServer() {
var cId = localStorage.getItem("cId");
var sname = $('#sitename').val();
var slat = $('#lat').val();
var slng = $('#lng').val();
var storedFieldId = JSON.parse(localStorage["field_id_arr"]);
var p = {};
for (var i = 0; i < storedFieldId.length; i++) {
var each_field = storedFieldId[i];
var val_each_field = $('#' + each_field).val();
p[each_field] = val_each_field;
console.log("p" + p);
}
var online = navigator.onLine;
if (online) {
var data = {
site: {
collection_id: cId,
name: sname,
lat: slat,
lng: slng,
properties: p
}
};
//function sending to server
$.ajax({
url: App.URL_SITE + cId + "/sites?auth_token=" + storeToken(),
type: "POST",
data: data,
enctype: 'multipart/form-data',
crossDomain: true,
datatype: 'json',
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("data: " + data);
alert("successfully.");
},
}

Looks like you are using the normal method to send data/image to server which is not recommended by Phonegap/Cordova Framework.
I request you to replace your code with the following method which works as you expected,I also used local storage functionality to send values to server,
function sendDataToServer(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = {};
params.some_text = localStorage.getItem("some_text");
params.some_id = localStorage.getItem("some_id");
params.someother_id = localStorage.getItem("someother_id");
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://example.co.uk/phonegap/receiveData.php"), win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode+"Response = " + r.response+"Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
function saveData(){
sendDataToServer(globalvariable.imageURI);
alert("Data Saved Successfully");
}
Hope this helps.

Related

How to get data from a JavaScript to controller and store it in the database

I want to get the location from this JavaScript to the controller and store it in the database:
var currPosition;
navigator.geolocation.getCurrentPosition(function(position) {
updatePosition(position);
setInterval(function() {
var lat = currPosition.coords.latitude;
var lng = currPosition.coords.longitude;
jQuery.ajax({
type: "POST",
url: "myURL/location.php",
data: 'x=' + lat + '&y=' + lng,
cache: false
});
}, 1000);
}, errorCallback);
var watchID = navigator.geolocation.watchPosition(function(position) {
updatePosition(position);
});
function updatePosition(position) {
currPosition = position;
}
function errorCallback(error) {
var msg = "Can't get your location. Error = ";
if (error.code == 1)
msg += "PERMISSION_DENIED";
else if (error.code == 2)
msg += "POSITION_UNAVAILABLE";
else if (error.code == 3)
msg += "TIMEOUT";
msg += ", msg = " + error.message;
alert(msg);
}
To send post with .ajax():
// ....
let formData = new FormData();
const lat = currPosition.coords.latitude;
const lng = currPosition.coords.longitude;
formData.append("x", lat);
formData.append("y", y lng;
$.ajax({
url: "myURL/location.php", // update this with you url
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'POST',
success: function(data){
const response = jQuery.parseJSON(data);
}
});
//....
To receive post data in codeigniter :
$x = $this->input->post('x');
$y = $this->input->post('y');
you just need to change uri parameter to codeginter route that you have
setInterval(function(){
....
url: "change this to codeigniter route url",
....
}, 1000);
then in the controller you just need to save those parameter,
class X extends CI_Controller{
function update_position(){
$x = $this->input->post('x');
$y = $this->input->post('y');
// then save it using model or query.
$this->model_name->insert([...])
}
}

Post restful method java error

Can anyone tell me why this error?
Server Log:
StandardWrapperValve[ws_site.ApplicationConfig]: Servlet.service() for servlet ws_site.ApplicationConfig threw exception
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 5
at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
at com.google.gson.Gson.fromJson(Gson.java:791)
Javascript function, responsible for capturing the data of the filled form and sending to the server:
function save()
{
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name}';
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: obj
}).done(function (data)
{
alert(data);
});
}
Restful Java method:
#POST
#Path("data")
#Produces(MediaType.TEXT_PLAIN)
#Consumes({MediaType.APPLICATION_JSON})
public String registerUser(Gson json)
{
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
u.setAddress(a);
userDAO.save(u);
return "Saved successfully!";
}
Save userDAO method:
public void save(User u) {
EntityManager em = JPAUtil.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (u.getId_User() == null) {
em.persist(u);
} else {
em.merge(u);
}
tx.commit();
} catch (Exception ex) {
ex.printStackTrace();
if (tx != null && tx.isActive()) {
tx.rollback();
}
} finally {
em.close();
}
}
Using Gson to convert json into an object
You're not sending an object to the server, you're just sending a string:
var obj = '...';
Instead, send an object:
var objdata = {
"email_user": str_email,
"name_user": str_name
};
var objlocation = {
"country": str_country,
"state": str_state,
"city": str_city,
"neighborhood": str_neighborhood,
"street": str_street,
"number": str_number,
"zipcode": str_zipcode
};
var obj = {
"user": [objdata],
"endereco": [objlocation]
};
A string that looks like an object is still a string.
objdata was not populating correctly as valid json. Try with this:
function save() {
var str_name = $("#name").val();
var str_email = $("#email").val();
var str_country = $("#country").val();
var str_state = $("#state").val();
var str_city = $("#city").val();
var str_zipcode = $("#zipcode").val();
var str_neighborhood = $("#neighborhood").val();
var str_street = $("#street").val();
var str_number = $("#number").val();
var objdata = '{"email_user":"' + str_email + '","name_user":"' + str_name + '"}';
console.log(objdata);
var objlocation = '{"country":"' + str_country + '","state":"' + str_state + '","city":"' + str_city + '","neighborhood":"' + str_neighborhood + '","street":"' + str_street + '","number":"' + str_number + '","zipcode":"' + str_zipcode + '"}';
console.log(objlocation);
var obj = '{"user":[' + objdata + '],"endereco":[' + objlocation + ']}';
console.log(obj);
$.ajax({
headers: {'content-type': 'application/json'},
dataType: 'json',
method: "POST",
url: "http://localhost:8080/SystemExample/webservice/Save/data",
data: JSON.parse(obj)
}).done(function (data) {
alert(data);
});
}
In your server side you are trying bind JSON data.
User u = json.fromJson("user", User.class);
Address a = json.fromJson("endereco", Address.class);
It mean user and endereco should be a JSON objects like below.
{
"user":{
"email_user":"str_mail","name_user":"nameeee"
},
"endereco":{
"country":"str_country","state":"str_state","city":"str_city","neighborhood":"str_neighborhood","street":"str_street","number":"str_number","zipcode":"str_zipcode"
}
}
But in your case user and endereco are actually a JSONArray's(See the square brackets.).
{
"user":[
{
"email_user":"str_mail",
"name_user":"nameeee"
}
],
"endereco":[
{
"country":"str_country",
"state":"str_state",
"city":"str_city",
"neighborhood":"str_neighborhood",
"street":"str_street",
"number":"str_number",
"zipcode":"str_zipcode"
}
]
}
So change below line
var obj = '{"user":['+objdata+'],"endereco":['+objlocation+']}';
to
var obj = '{"user":'+objdata+',"endereco":'+objlocation+'}';

How to stop redirect "Authorized redirect URIs" on Deny while log in with google authentication

I am using Google Authentication in Web Application and while log in with Google..if user click on "Deny" option..It still redirect to "Authorized redirect URIs" which i mentioned in Console Developers of google.
<script type="text/javascript">
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = // My Client Id;
var REDIRECT = 'http://localhost:49234/Account/GoogleSign';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
$(document).ready(function () {
login();
});
function login() {
debugger;
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function () {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch (e) {
}
}, 5000);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function (responseText) {
//alert("Call")
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function (resp) {
user = resp;
// console.log(user);
IsAuthenicated(user.id, user);
$('#txtFirstName').val(user.name);
$('#txtEmail').val(user.email);
},
dataType: "jsonp"
});
}
function gup(url, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\#&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if (results == null)
return "";
else
return results[1];
}
function IsAuthenicated(GoogleId, user) { //This function call on text change.
$.ajax({
type: "POST",
url: "http://localhost:49233/AutoComplete.asmx/IsGoogleAuthenicated", // this for calling the web method function in cs code.
data: '{GoogleId: "' + GoogleId + '" }',// user name or email value
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
}
});
}
// function OnSuccess
function OnSuccess(response) {
//alert('s ' + response.d);
debugger;
var retval = response.d;
if (retval == '0') {
$('#txtFirstName').val(user.name);
$('#txtEmail').val(user.email);
$('#hdgmailId').val(user.id);
$('#hgverified').val(user.verified_email);
$('#hglocale').val(user.locale);
$('#hdgiven_name').val(user.given_name);
}
else {
window.open("http://localhost:49233/Dashboard.aspx?Id=1&number=" + response.d, "_self");
}
}
</script>
Can someone suggest better approach how to handle Deny option? And also if i have opened 2 gmail account in same browser then also it is not redirecting me to my application after click on "Allow" access.

Chart js line with asp.net

i'm trying to do a line chart with chart js in ASP.NET but this don't work, before I tried with a pie chart and this working fine, but with line chart doesn't work, I think the response is incorrect because in the console displays "uncaught SyntaxError: unexpected token : ".
This is the code c# :
[WebMethod]
public static string GetChart(string country)
{
StringBuilder sb = new StringBuilder();
sb.Append("{");
sb.Append("labels:[\"January\",\"February\",\"March\",\"April\",\"May\",\"June\"],");
sb.Append("datasets:[");
System.Threading.Thread.Sleep(50);
string color = "rgba(220,220,220,0.2)";
//
sb.Append("{");
sb.Append(string.Format("fillColor:\"{0}\", strokeColor:\"{1}\", pointColor:\"{2}\", pointStrokeColor:\"{3}\", data:{4}", color, "#ACC26D", "#fff", "#9DB86D", "[203,156,99,251,305,247]"));
//
sb.Append("}");
sb.Append("]");
sb.Append("};");
return sb.ToString();
}
And this is the Javascript:
<script type="text/javascript">
function LoadChart() {
var chartType = parseInt($("[id*=rblChartType] input:checked").val());
$.ajax({
type: "POST",
url: "inicioCliente.aspx/GetChart",
data: "{country: '" + $("[id*=ddlCountries]").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$("#dvChart").html("");
$("#dvLegend").html("");
var data = eval((r.d));
var el = document.createElement('canvas');
$("#dvChart")[0].appendChild(el);
var ctx = el.getContext('2d');
var userStrengthsChart;
switch (chartType) {
case 1:
userStrengthsChart = new Chart(ctx).Line(data);
break;
case 2:
userStrengthsChart = new Chart(ctx).Doughnut(data);
break;
}
for (var i = 0; i < data.length; i++) {
var div = $("<div />");
div.css("margin-bottom", "10px");
div.html("<span style = 'display:inline-block;height:10px;width:10px;background-color:" + data[i].color + "'></span> " + data[i].text);
$("#dvLegend").append(div);
}
},
failure: function (response) {
alert('There was an error.');
}
});
}
$(function () {
LoadChart();
$("[id*=ddlCountries]").bind("change", function () {
LoadChart();
});
$("[id*=rblChartType] input").bind("click", function () {
LoadChart();
});
});
</script>
after some time I found the solution, the problem was in the eval method, I need add "()"
var data = (eval("(" + r.d + ")"));
Thanks

After submit a reply by Ajax Its display a blank data space

After submit a reply without 1st post Its display a blank data space and after refresh page its show reply.
What is problem here please.
..............................................................................
This is my script
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputReplycom = $(".replycom");
var inputImg = $("#img");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var replyList = $("#replynext");
function updateReplybox() {
var tutid = inputTutid.attr("value");
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid=" + tutid,
complete: function (data) {
replyList.append(data.responseText);
replyList.fadeIn(2000);
}
});
}
$(".repfrm").click(function () {
error.fadeOut();
if (checkForm()) {
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$('.reply_here').hide();
$("#loader").fadeIn(400).html('<br><img src="loaders.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
//send the post to submit.php
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&author=" + author + "&replycom=" + replycom + "&url=" + url + "&img=" + img + "&parent_id=" + parent_id + "&tutid=" + tutid,
complete: function (data) {
error.fadeOut();
$("#loader").hide();
replyList.append(data.responseText);
updateReplybox();
$("#repfrm").each(function () {
this.reset();
});
}
});
} else //alert("Please fill all fields!");
error_message();
});
Probably all this code should be inside a $(document).ready({ ... });
To debug: Open chrome inspector and put a brakepoint at this line: var tutid = inputTutid.attr("value"); and check for what is inside inputTutid variable.
Also you can try
inputTutid.val();
instead of
inputTutid.attr("value");

Categories

Resources