Click here to Skip to main content
15,918,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
the prob is when submit button click two method executed...first one by controller that send the notification to android. second one by onclcik javascript function in which by ajax we are calling method that shows us latitude and longitude and showing them on google map.
now its executed first javascript function then send push notification. then reload the full page. so map came and gone as page loaded after javascript function executed.

What I have tried:

in controler:

public ActionResult getcurrentlocation()
{

return View();
}


[HttpPost]

public ActionResult getcurrentlocation(FormCollection fc)
{
string eid = fc["EmployeeCode"];
string empid = geteid(eid);
SendNotification(empid, "Get Current Location");

return View();
}
public void SendNotification(string deviceId, string message)
{
//API Key created in Google project
string GoogleAppID = "AIzaSyDBhaDX8sCD9gZOgBA_3vZS4apA1oax_rg";
//Project ID created in Google project
var SENDER_ID = '';
//Registration Id created by Android App i.e. DeviceId
string regID = deviceId.Trim();
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback
(
delegate { return true; }
);
WebRequest webRequest;
webRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
webRequest.Method = "post";
webRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
webRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
webRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = string.Format("collapse_key=score_update&time_to_live=108&delay_while_idle=0&data.message={0} &data.time={1} &registration_id={2}", message, DateTime.UtcNow, regID, "default");
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
webRequest.ContentLength = byteArray.Length;
Stream dataStream = webRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse webResponse = webRequest.GetResponse();


dataStream = webResponse.GetResponseStream();
using (StreamReader streamReader = new StreamReader(dataStream))
{
String sResponseFromServer = streamReader.ReadToEnd();
streamReader.Close();
dataStream.Close();
webResponse.Close();
}
}

in view:
HTML
<style>#map_canvas { height: 100% }</style>
  <script language="javascript" type="text/javascript">
    
    </script>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    <script src="jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="../Scripting/UIBlocker.js"></script>
    <script src="../Scripting/spin.js"></script>
  <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false"></script>
  <header class="head">              
                        <h3>Employee Location</h3>                
                    </header>
<div class="row" id="rr">
 
    <div class="col-lg-6">

       @using (Html.BeginForm("getcurrentlocation", "Setup", FormMethod.Post, new { @class = "form-horizontal"}))
        {   
           @Html.HiddenFor(m=>m.Id)
       
    
           <div class="form-group">
                @Html.Label("Employee Code", new { @class = "control-label col-lg-4", })               
                <div class="col-lg-8">  
                @Html.TextBoxFor(m => m.EmployeeCode, new { @class = "form-control",@name = "eid",@id = "emp" , @placeholder = "Enter Employee Code." })
              </div>
                @Html.ValidationMessageFor(m => m.EmployeeCode)
                </div>
         
              
            <div class="col-lg-8">
                <input type="submit" id="Add" value="send request" name="Command"  class="btn btn-metis-6 btn-sm" />

                  
            </div>
           
            <br />         
              
        } </div></div>
 <div class="col-lg-8">
                <input type="submit" id="kk" value="Get current location" name="Command"  onclick="GetEngineerLocation()" class="btn btn-metis-6 btn-sm" />

                  
            </div>

      <div id="map_canvas" style="width: 500px; height: 400px;"></div>
                    <div id="foo">
                    </div>
 



  <div class="col-lg-12">
      
 
</div>

JavaScript
function GetEngineerLocation() {

    //var empId = document.getElementById('ddlEmployeelist').value;
   var callId = document.getElementById('emp').value;

    if (callId == undefined || callId == '') {

        callId = -1;
    }
    if (callId != '') {

        $.ajax({

            type: "Post",
            url: "/MobileApp/Setup/currentlocation",
            dataType: 'json',
            data: JSON.stringify({ callId: callId }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
          success: GetEngineerCurrentLocationSuccess,
           
            error: GetEngineerCurrentLocationFail
        });
    }
    else {
        alert("Please select employeee")
    }
}

function GetEngineerCurrentLocationSuccess(result) {

    var lat = result.Latitude;
    var lon = result.Longitude;
    var time = result.LocationTime;

    var myLatlng = new google.maps.LatLng(lat, lon) // This is used to center the map to show our markers
    var mapOptions = {
        center: myLatlng,
        zoom: 6,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        marker: true
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    var marker = new google.maps.Marker({
        position: myLatlng,
        title: "lat: " + lat + " long: " + lon + " Time: " + time
    });
    marker.setMap(map);
    var infowindow = new google.maps.InfoWindow({ content: "<b>User Address</b><br/> Latitude:" + lat + "<br /> Longitude:" + lon + "" });
    infowindow.open(map, marker);


}

function GetEngineerCurrentLocationFail() {
    alert("fail");

}
Posted
Updated 2-Dec-16 5:07am

1 solution

You forgot to cancel the form submission when you click the "get current location" button:
HTML
<input type="submit" id="kk" value="Get current location" name="Command"  onclick="GetEngineerLocation();return false;" class="btn btn-metis-6 btn-sm" />

Adding return false; after the call to GetEngineerLocation(); prevents the form from being submitted.
 
Share this answer
 
Comments
Member 12300036 4-Dec-16 23:49pm    
thanku so much sir...
but i am facing one more problem. when i click on submit button controller action method executed. in which we send the push notification to android and get location.
bt getting the location it takes min 5 second. so java script fuction execute fast and its shows the last location on map from database.
can we delay the javascript function to execute after some second or any other solution for this??
Member 12300036 5-Dec-16 0:18am    
and after adding a return false to javascript function....controller method not executing. so how i send the notification dear
Richard Deeming 5-Dec-16 7:29am    
Either you submit the form, in which case the entire page is reloaded, or you run some Javascript. You can't do both.

If you need to execute Javascript and execute some code on the server, then you'll need to use an AJAX request instead of submitting the form.
Member 12300036 5-Dec-16 23:17pm    
ok thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900