Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

54
Vistas
Sending plain strings with ajax

I'm trying to send a plain string using an Ajax post request:

jQuery

var user = {
    "name": name,
    "country": country,
};

$.ajax({
    type: 'POST',
    traditional: true,
    url: 'Default.aspx/Submit',
    data: JSON.stringify(user),
    contentType: "application/json; charset=utf-8",
    dataType: "text",
    success: function (msg) {
      alert("Success!");
    },
    error: function () {
      alert("Error!");
    }
});

ASP.NET

[WebMethod]
public static bool Submit(string json)
{
    // do something
    return true;
}

I set:

  • traditional = true to avoid recursive encoding (not sure if needed)
  • data is a string, not an object
  • dataType is text not json

but I still got this error from server:

invalid web service call, missing value for parameter: json

I guess this is because it doesn't find a matching name for the "json" parameter. But I don't understand how I have to name the function parameter if I'm sending a plain string.

8 months ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

This is the code I use to post to a database using AJAX.

// Variable to hold request var request;

// Bind to the submit event of our form $("#form1").submit(function(event){

// Abort any pending request
if (request) {
    request.abort();
}
//local variables
var $form = $(this);

// select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");

// Serialize the data in the form
var serializedData = $form.serialize();

// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);

// Fire off the request to php file
request = $.ajax({
    url: yourdomain-asp-page,
    type: "post",
    data: serializedData
});

// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
    //replace form with feedback text


// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
    // Log the error to the console
    console.error(
        "The following error occurred: "+
        textStatus, errorThrown
    );
});

// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
    // Reenable the inputs
    $inputs.prop("disabled", false);
});

// Prevent default posting of form
event.preventDefault();

});

8 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos