Mostrando entradas con la etiqueta json. Mostrar todas las entradas
Mostrando entradas con la etiqueta json. Mostrar todas las entradas

Enviar model y parametros adicionales en llamado ajax

Javascript

            var datos = $('form').serializeArray();
            var usuarioSup = {
                name: "usuarioSupervisor",
                value: "abc"
            };
            var passwordSup = {
                name: "passwordSupervisor",
                value: "xxx"
            };
            datos.push(usuarioSup);
            datos.push(passwordSup);

            jqxhr2 = $.ajax({
                type: "POST",
                data: datos,
                dataType: "json",
                url: "@Url.Action(@Model.Accion, @Model.Controlador)",
                beforeSend: function () {
                }
            }).fail(function (jqXHR, textStatus) {
                $.unblockUI();
                $("#mensaje").html("Error: " + "Status: " + jqXHR.status + " detalle: " + textStatus + " detalle: " + jqXHR.responseText);
            }).success(function (data) {
                $.unblockUI();
                $("#mensaje").html(data.Mensaje);

                if (data.Codigo != "err_sup") {
                    $("#div_supervision").hide();
                    $("#@ViewBag.boton").removeProp("disabled");
                }
            });


MVC

[HttpPost]
public ActionResult Ejecutar(ConsultaViewModel modelo, string usuarioSupervisor, string passwordSupervisor)
        {
            return null;
        }

Utilizar Ajax en C# [Funciona!]

Importar esta librería:

       using System.Web.Script.Serialization;

Crear la clase DTO:

        public class PersonaDTO
        {
            public string Nombre { get; set; }
            public string Apellido { get; set; }
        }

Crear el ActionResult:

        [HttpGet]
        public ActionResult Buscar(int param)
        {
            var x = new Persona();

            x.Nombre = "Juana";
            x.Apellido = "Perez";

            return Json(x, JsonRequestBehavior.AllowGet);
        }

Agregar el código javascript en la vista:

<script>
    $(function () {       
        $.ajax({
            data: { 'param': 123 },
            url: "@Url.Action("Buscar", "Prueba")",
            type: 'GET',
            cache: false,
            success: function (response) {
                alert(response.Nombre);
            },
            error: function (a, b) {
                alert("error fatal");
                alert(a.responseText);
            }
        });
    });
</script>

Ejemplo simple Autocomplete y JSON

data.json

[{
"label": "C++",
"value": "C++"
}, {
"label": "Java",
"value": "Java"
}]



prueba.html:

$('#campo").autocomplete({
     source: "/url_del_servidor/data.json"
});


CS0103: The name 'Json' does not exist in the current context

Dentro del tag <compilation> agregar lo siguiente:

<assemblies>
            <add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>




Enviar datos desde javascript hacia un controller con AJAX en MVC

Método #1: Enviar form como JSON y otros parametros

Llamado Ajax

            var f = $("#form_refin").serializeFormJSON();
            var send = { param1: "111", param2: "222", datos: JSON.stringify(f) };
            
            jqxhr2 = $.ajax({
                type: "POST",                
                data: send,
                dataType: "json",
                url: "@Url.Action("Supervision2", "RefinanciacionArrendamiento")",
                beforeSend: function () {
                    //l.start();
                }
            }).fail(function (jqXHR, textStatus) {
                //l.stop();
                alert("Error: " + "Status: " + jqXHR.status + " detalle: " + textStatus + " detalle: " + jqXHR.responseText);
            }).success(function (data) {
                $("#HashSup").val(data);
            });


    (function ($) {
        $.fn.serializeFormJSON = function () {

            var o = {};
            var a = this.serializeArray();
            $.each(a, function () {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };
    })(jQuery);




Controller

using Newtonsoft.Json;
...
...
...

[HttpPost]
public ActionResult Supervision2(string param1, string param2, string datos)
{            

 var refin = JsonConvert.DeserializeObject<RefinanciacionArrendamientoVM>(datos);
}


Método #2: Definir el objeto que se va a enviar manualmente

Llamado Ajax

$("#Modificar").click(function() {
var user = {
Documento: $("#txtDocumento").val(),
Email: $("#txtCorreo").val(),
Nombre: $("#txtNombre").val(),
TipoDoc: $("#drpTipoDoc option:selected").val()
}

jqxhr2 = $.ajax({

type: "POST",
async: false,
data: user,
dataType: "json",
url: "@Url.Action("ModificarUsuarioCreado", "Usuario")",
beforeSend: function () {}
})
.fail(function (jqXHR, textStatus) {})
.success(function (data) {}
);
});


Controller

[HttpPost]
public ActionResult ModificarUsuarioCreado(Usuario user) { ... }


public class Usuario

{
    public string Documento { get; set; }
    public string Email { get; set; }
    public string Nombre { get; set; }
    public string TipoDoc { get; set; }
}


Método #3: Enviar el Modelo completo

De esta forma se puede enviar el modelo desde la vista hacia un controller, cualquiera sea su estructura y complejidad.
Funciona con POST y GET, en este ejemplo se utiliza POST.
*** Tener en cuenta que utilizando este método NO se envían los datos modificados manualmente en el formulario o los datos cargados mediante javascript. Para poder hacer esto, utilizar el método 3 ***

Código en la View

Formulario:

@using Creditos.ViewModels.Liquidaciones
@model RefinanciacionArrendamientoVM
...
...
...    

Llamado Ajax

var model = JSON.parse('@Html.Raw(Json.Encode(Model))');

jqxhr2 = $.ajax({
                type: "POST",
                data: model,
                dataType: "json",
                url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")" 
            }).fail(function (jqXHR, textStatus) {
                $("#arrendContent").html(jqXHR.responseText);
            }).success(function (data) {
                $("#div_mensaje").html(data.MsgError);
            });



Controller

[HttpPost]
public ActionResult Contabilizar(RefinanciacionArrendamientoVM refin) 
...
...
...


Método #4: Enviar el form serializado
De esta forma se pasan todos los datos del formulario (no del modelo, aunque si no se modifican los campos del form, son los mismos)
Este método permite pasar los cambios que se hagan en el formulario (cosa que el método #2 no puede hacer)

Llamado Ajax


jqxhr2 = $.ajax({
        }).fail(function (jqXHR, textStatus) {
            if (data.MsgError == "Refinanciación contabilizada correctamente.") {

    type: "GET",
    data: $('form').serialize(),
    dataType: "json",
    url: "@Url.Action("Contabilizar", "RefinanciacionArrendamiento")", 
    beforeSend: function () {                    
                  $.blockUI({
                      message: 'Espere por favor...',
                      css: {
                          border: 'none',
                          padding: '15px',
                          backgroundColor: '#000',
                          '-webkit-border-radius': '10px',
                          '-moz-border-radius': '10px',
                          opacity: 0.5,
                          color: '#fff'
                      }
                  });
               }

            $.unblockUI();

            $("#arrendContent").html(jqXHR.responseText);
        }).success(function (data) {
            $.unblockUI();
            $("#div_mensaje").html(data.MsgError);

                $("#btn_contabilizar").attr("disabled", "disabled");

                $("#btn_calcular").attr("disabled", "disabled");
            }                
        });







Databind de json a elementos select y table con jQuery

jQuery AJAX desde PHP con jsonwrapper

Codigo del webservice:
prueba1.php

<?php
   $receive=file_get_contents('php://input');
   $p = json_decode($receive);

   $pp[0]["prueba0"] = $p["parametro1"];
   $pp[0]["prueba1"] = "abc";
   $pp[0]["ss"] = "zzz";
   $p = json_encode($pp);

   echo $p;
?>

Codigo JS:

function invocarAjax(url_ws, param_ws, funcion_ws, async_ws)
{  
 if(async_ws===undefined)
  async_ws = false;
   
 jQuery.ajax({
  type: "POST",
  timeout: 5000,
  url: url_ws + "?" + "random=" + Math.floor(Math.random()*9999999999),
  data: param_ws,
  contentType: "application/json; charset=utf-8",
  dataType: "json", 
  cache: false,
  async: async_ws,
  success: function(response) {
   window[funcion_ws](response, null);
  },
  error: function(xhr, ajaxOptions, thrownError) {
   window[funcion_ws](null, xhr.responseText );
  }
  }); 
}
function getJSON(data_obj)
 {
  if (data_obj.d)
    data_ok = data_obj.d;
  else
   data_ok = data_obj;
   evalJson = eval("var varJSON = " + data_ok + ";");
  return varJSON; 
 }

Código que invoca al webservice:

<script>
$(document).ready(function() {
 $("#setear").click(function() {
  url_ws = "prueba1.php"; 
  param_ws = '{"parametro1": "5555", "enviar_todos": "S"}';
     
  invocarAjax(url_ws, param_ws, "callbackConfigEmails", true);
 });
});
function callbackConfigEmails(v, err)
{   
 if (err == null)
 {     
   if (v[0].prueba1 != "")
  {  
   alert("prueba0: " + v[0].prueba0);
   alert("prueba1: " + v[0].prueba1);
  }
     
 } else
  alert("ERROR: " + err); 
}
</script>

OJO!!!!!
El codigo json_decode de jsonwrapper NO funciona, en su lugar, utilizar este:

function json_decode($json)

 $comment = false; 
 $out = '$x=';    
 for ($i=0; $i<strlen($json); $i++) 
 {  
  if (!$comment)  
  {   
   if (($json[$i] == '{') || ($json[$i] == '['))      
    $out .= ' array(';   
   else if (($json[$i] == '}') || ($json[$i] == ']'))  
    $out .= ')';   
   else if ($json[$i] == ':')   
    $out .= '=>';   
   else                        
    $out .= $json[$i];           
  } else
   $out .= $json[$i];  
   if ($json[$i] == '"' && $json[($i-1)]!="\\")   
    $comment = !$comment; 
 }   

 eval($out . ';'); 

 return $x;
}

WebService y JSON con jQuery, con Visual Studio 2008 que corre en Visual Studio 2005

1. Crear un web service con visual studio 2008
2. Luego de comprobar que funciona, crear un WebService vacio en Visual Studio 2005 e incorporar los archivos del paso1 (web.config, .asmx, .vb, etc)

Codigo que funciona en VS2005:

web.config


<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.

            Visual Basic options:
            Set strict="true" to disallow all data type conversions
            where data loss can occur.
            Set explicit="true" to force declaration of all variables.
        -->
<compilation debug="true" strict="false" explicit="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<pages>
<namespaces>
<clear/>
<add namespace="System"/>
<add namespace="System.Collections"/>
<add namespace="System.Collections.Generic"/>
<add namespace="System.Collections.Specialized"/>
<add namespace="System.Configuration"/>
<add namespace="System.Text"/>
<add namespace="System.Text.RegularExpressions"/>
<add namespace="System.Linq"/>
<add namespace="System.Xml.Linq"/>
<add namespace="System.Web"/>
<add namespace="System.Web.Caching"/>
<add namespace="System.Web.SessionState"/>
<add namespace="System.Web.Security"/>
<add namespace="System.Web.Profile"/>
<add namespace="System.Web.UI"/>
<add namespace="System.Web.UI.WebControls"/>
<add namespace="System.Web.UI.WebControls.WebParts"/>
<add namespace="System.Web.UI.HtmlControls"/>
</namespaces>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
<authentication mode="Windows"/>
<!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
<!--
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ScriptModule"/>
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<remove name="ScriptHandlerFactory"/>
<remove name="ScriptHandlerFactoryAppServices"/>
<remove name="ScriptResource"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>


Prueba.asmx


Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports LibX.X

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function Consulta1(param1 As String, param2 As String) As String

        Return "{ 'datos': [ {'nombre': 'Juan', 'direccion': 'Colonia 1212'}, {'nombre': 'Pedro', 'direccion': 'Mercedes 1111'} ] }"

    End Function
End Class

Llamado desde javascript con jquery:

var url_ws
url_ws = "http://" + window.self.location.hostname + "/wsTEST/Prueba.asmx/Consulta1";
jQuery.ajax({
type: "POST",
url: url_ws,
data: "{'param1': '4', 'param2': '10'}",
contentType:"application/json; charset=utf-8",
dataType:"json",
async: false,
cache: false,
success: function(response) {
var v = getJSON(response);
if (v.datos[0].nombre != "")
$("#"+div_display).html("&nbsp;&nbsp" + v.datos[0].nombre);
else
$("#"+div_display).html("Cliente no existe");
},
error: function(xhr, ajaxOptions, thrownError) {
//$("#"+div_display).html("Error al obtener el nombre del cliente");
}
});

         function getJSON(data_obj)
        {
                if (data_obj.d)
                      data_ok = data_obj.d;
               else
                      data_ok = data_obj;

               evalJson = eval("var varJSON = " + data_ok + ";"); 

               return varJSON;  
         }




Ejecutar un webservice JSON con jQuery [Funciona!]

Este ejemplo asume que existe un webservice llamado wsX que retorna el siguiente string:

{ 'datos': [ {'nombre': 'Juan', 'direccion': 'Colonia 1212'}, {'nombre': 'Pedro', 'direccion': 'Mercedes 1111'} ] }


jQuery.ajax({
   type: "POST",
   url: http://X14/wsX/wsX.asmx/HelloWorld,
   data: "{}",
   contentType:"text",
   dataType:"text",
   cache: false,
   success: function(response) {
      var v = getJSON(response);
      alert("Resultado: " + v.datos[0].nombre);
   }
});
 
function getJSON(data)
{
   var s;

   s = data.substring(data.indexOf("{"));
   s = s.substring(0, s.lastIndexOf("}") + 1);
   return eval('(' + s + ')');
}
 

Utilizar eval para transformar texto a JSON

var data = "{ 'prueba': [ {'foo': 'The quick brown fox jumps over the lazy dog.' } ] }";


var v = eval('(' + data + ')');

alert("RESULTADO: " + v.prueba[0].foo);