I have an ASP.NET MVC3 app and when the user clicks on my anchor tag, I want to send 3 pieces of data to an action:
<a onclick='editDescription(<#= DocID,FileName,Description #>)'></a>
This is the javascript to call my action:
function editDescription(docId,fileName,description) {
var url = "#Url.Content("~/OrderDetail/_EditDescription/")" + docId+'/'+
fileName + '/' + description;
//do the rest}
My action:
public ActionResult _EditDescription(string id,string filename, string descritpion)
The pieces im concerned about are FileName and Description because these can be loooooong and i dont want a url to appear like so:
http://localhost/OrderDetail/_EditDescription/123/some long filename.pdf/this is a long description for the name
How can i send across my data to my action without having to send it like a query string? Thanks
You can use the jQuery $.ajax method:
<div id="what-I-want-updated">
<input id="whatever-the-id-is" type="text" value="#Model.ID" />
<br />
<input id="whatever-the-filename" type="text" value="#Model.Filename" />
<br />
<input id="whatever-the-description" type="text" value="#Model.Description" />
<br />
<button id="whatIsClicked">Update!</button>
</div> <!-- /#what-I-want-updated -->
<script>
// You're probably clicking something to initiate update
var $whatIsClicked = $('#whatIsClicked');
// .live persists on the page even after other ajax calls
// So when the thing is clicked
$whatIsClicked.live('click', function() {
// Grab the information needed to update
var theId = $('#whatever-the-id-is').val(); //Or it could be .text()
var theFilename = $('#whatever-the-filename').val();
var theDescript = $('#whatever-the-description').val();
// Let's edit the description!
$.ajax({
type: "POST",
url: "OrderDetail/_EditDescription", // the method we are calling
contentType: "application/json; charset=utf-8",
data: {id: theId, filename: theFilename, description: theDescript},
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function (result) {
alert('Oh no :(');
}
});
});
</script>
Even though it will still work, make sure you change your Controller method to:
[HttpPost]
public ActionResult _EditDescription(string id, string filename, string descritpion)
You can do a full post of the form if you like either through ajax $.post or by having an action with [HttpPost] attribute.
Declare your action as a POST
[HttpPost]
public ActionResult _EditDescription(string docId, string filename, string description)
Create an invisible HTML form:
<form action="#Url.Content("~/OrderDetail/_EditDescription/")" method="post" name="editDescriptionForm">
<input type="hidden" name="docId" />
<input type="hidden" name="fileName" />
<input type="hidden" name="description" />
</form>
Fill out the form and submit it with JS:
function editDescription(docId, fileName, description) {
document.editDescriptionForm.docId = docId;
...
document.editDescriptionForm.submit();
}
Related
I've been trying to develop a site which has a login system.
As part of that I want to make an AJAX call to the server to handle the login system with the username and password.
When I make the call, it goes through well but i recieve the entire web page in return and I don't know why
Ajax call(JS):
function AJAXfunc(username, password) {
var parameter = JSON.stringify({ "username": username, "password": password })
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: '/Login?handler=LoginFunc',
data: parameter,
dataType: 'json',
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
success: function (data) {
onsuccess(data)
},
error: function (data, success, error) {
alert("Error: " + error + " - " + data + " - " + success + " - " + data.value)
}
})
}
Server side code(C#):
public class LoginModel : PageModel
{
public async Task<IActionResult> OnPostLoginFuncAsync(HttpContext http, JsonDocument json)
{
return new JsonResult("success");
}
}
Any help would be much appreciated
Thanks
Edit: here is the code that calls the ajax function
function onLoginLoad() {
const formLogin = document.getElementById("login");
formLogin.addEventListener("submit", function (event) {
const userName = formLogin.getElementsByClassName("username")[0].value;
const password = formLogin.getElementsByClassName("password")[0].value;
// stop form submission
event.preventDefault();
AJAXfunc(userName,password);
});
}
here is the HTML code
<form id = "login" action = "/LoginFunc" method = "post">
<h1>Login</h1>
<small></small>
<div class = "field">
<label for = "username" class="loginpg" style="top:45%;left:45%;position:fixed;color:white; width:10%;">Username</label>
<input type="text" class="username" name="username" id="username" style="top:48%;left:45%;position:fixed;width:10%;" placeholder = "Username"><br><br>
</div>
<div class = "field">
<label for = "password" class="loginpg" style="top:51%;left:45%;position:fixed;color:white;width:10%;">Password</label>
<input type= "password" class="password" id="password" name="password"style="top:54%;left:45%;position:fixed;width:10%;" placeholder = "Password"><br><br>
</div>
<input type="submit" value="Submit" class = "loginpg" style="top:57%;left:45%;position:fixed;width:10%;">
</form>
This is the exact error: 'Unexpected token '<', "\r\n\r\n<!DOCTYPE "... is not valid JSON'
yes, as a general rule if you client side js code is a big pile of a mess?
Then hitting the web page will OFTEN just choke, and simple return the whole page. When this occurs, it means your code is all wrong.
When you build/make a ajax call, you can pass values in the URL. This is what we call a REST call.
However, in most cases, we all "very much dislike" having to use those messy URL parmaters, so when we use .ajax calls, we perfer to use the .data option of the jQuery .ajax call.
Your code looks to have BOTH - and that's not going to work.
next up:
Remember those .ajax calls are NOT a post-back, and that means in code behind for that page class, such code does NOT have use of an "instance" of the page class (that code for example can't see/use/enjoy/change controls on the page).
So, that "method" of the page class MUST be static - since no "instance" of the page class will exist (since there is no page post-back).
So, dump the parmtaers in the URL - use ONE or the other (data, or URL based parmaters).
next up, if you NOT createing a seperatet asmx page with page methods, then if you choose to place the web methods in the existing page? (and I much like this choice, since then code and web methods are in the same place?
Then that web method must be MARKED as a web method, and also must be a static member of that page.
So, your code would/should look like this:
So, say client side markup and js code:
<h3>Enter user</h3>
<asp:TextBox ID="txtUser" runat="server" ClientIDMode="Static">
</asp:TextBox>
<h3>Enter password</h3>
<asp:TextBox ID="txtPass" runat="server" ClientIDMode="Static">
</asp:TextBox>
<br />
<asp:Button ID="cmdLogIn" runat="server" Text="Login"
OnClientClick="mylogin();return false;"
/>
<script>
function mylogin() {
sUser = $('#txtUser').val()
sPass = $('#txtPass').val()
AJAXfunc(sUser,sPass)
}
function AJAXfunc(username, password) {
var parameter = JSON.stringify({ "username": username, "password": password })
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: 'WebCalltest.aspx/LoginFunc',
data: parameter,
dataType: 'json',
success: function (mydatastuff) {
alert('return value = ' + mydatastuff.d)
// onsuccess(mydatastuff.d)
},
error: function (data, success, error) {
alert("Error: " + error + " - " + data + " - " + success + " - " + data.value)
}
})
}
</script>
And code behind (assuming same page), then is this:
[WebMethod]
public static string LoginFunc(string username, string password)
{
// do whatever
return "this is the string return result";
}
So, now when we run above, we get/see this:
So, above is the "basic" layout and "pattern" as to how this works.
Now in above example, the web method in the page is on/placed in the same page - hence the URL change I used in above. You of course will have to change the url to your current page. And be careful, the page URL is relative to your current page - the "/" does not mean root in js code.
Also note close, the return value is a .d attribute. This is a .net quirk, and thus you don't use data, but use data.d, or in my example mydatastuff.d
So, don't forget/leave out the .d to get the return result from that web method.
sorry if this has been asked many times but I can't get it to work.
I'm trying to build a restful website, I have a simple form:
<form action="/my/path" method="post" id="myformid">
Name <input type="text" name="name">
<input type="submit" value="Test">
</form>
I convert the data the user inputs using Javascript and I send them to my php file using Ajax:
function postData() {
$('#myformid').on('submit', function(event) {
event.preventDefault();
const json = JSON.stringify($("#myformid").serializeArray());
$.ajax({
type: "POST",
url: "/my/path",
data: json,
success: function(){},
dataType: "json",
contentType : "application/json"
});
});
}
And I tried reading the data on php like:
$data = json_decode(file_get_contents('php://input'), true);
$name = $data["name"];
The code works perfectly if I send a JSON in the request body using a tool like Postman, but from what I tested using Ajax the json data arrives as POST data, and I can read it using $_POST["name"], but non with the 'php://input' as I did.
How can I fix it so the JSON gets accepted even sent via Javascript?
Hi you can try like this:
First I use an id attribute for each input i dont really like to serialize stuff but thats me you can do it your way here are the files.
your index.php:
<form method="post" id="myformid">
Name :<input type="text" id="name" name="name">
<input type="submit" value="Test">
</form>
<br>
<div id="myDiv">
</div>
your javascript:
//ajax function return a deferred object
function _ajax(action,data){
return $.ajax({
url: 'request.php',
type: 'POST',
dataType: 'JSON',
data: {action: action, data: data}
})
}
//your form submit event
$("#myformid").on('submit', function(event) {
//prevent post
event.preventDefault();
//validate that name is not empty
if ($("name").val() != "") {
//parameters INS is insert data is the array of data yous end to the server
var action = 'INS';
var data = {
name: $("#name").val()
};
console.log(data);
//run the function and done handle the function
_ajax(action,data)
.done(function(response){
console.log(response);
//anppend name to the div
$("#myDiv").append("<p>"+response.name+"</p>");
});
}
});
your request.php file:
<?php
//includes and session start here
//validate that request parameters are set
if (isset($_POST["action"]) && isset($_POST["data"])) {
//getters
$action = $_POST["action"];
$data = $_POST["data"];
//switch to handle the action to perfom maybe you want to update with the form too ?
switch ($action) {
case 'INS':
// database insert here..
//return a json object
echo json_encode(array("name"=>$data["name"]));
break;
}
}
?>
Results:
Hope it helps =)
From the documentation of .serializeArray().
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string.
And in the example given in the same page, it is clear that you will get an array in php,
to access an element, you should try-
`$data[0]['name']`
Also, have you tried print_r($data), is it NULL??
Change your ajax codes
$('#btnSubmit').on('click', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/new.php",
data: $("#myformid").serialize(),
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
Also you need some changes in form
<form action="new.php" method="post" id="myformid">
Name <input type="text" name="name">
<input id="btnSubmit" type="button" value="Test">
And you can get POST data in php file like $_POST['name']
You can set directly form serialize in ajax request to send params
function postData() {
$('#myformid').on('submit', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/my/path",
data: $("#myformid").serialize(),
success: function(){},
dataType: "json",
contentType : "application/json"
});
});
}
And you can get POST in your PHP using $_POST
print_r($_POST);
I want to send an image and a number when the user perform an upload.
My Javascript
form.append('file', $(uploader).get(0).files[0]);
var id= $("#id").val();
form.append("id", id);
$.ajax({
method: 'POST',
url: '/images/send',
data: form,
form: false,
processData: false
});
In my action what should I do?
With this I only receive the image.
[HttpPost]
public string send(IFormFile file) // What argument should I use
{
How do I get the number and file?
}
You can add a new parameter of type int to your action method. The parameter name should match with the formdata item name you are sending (id)
[HttpPost]
public string send(IFormFile file,int id)
{
// to do : return something.
}
You need to have the contentType property on your $.ajax method set to false
This should work.
var form = new FormData();
form.append('file', $('#File').get(0).files[0]);
var id= $("#id").val();
form.append("id", id);
var urlToPost ="/images/send";
$.ajax({
method: 'POST',
url: urlToPost ,
data: form,
processData: false,
contentType: false
}).done(function(result) {
// do something with the result now
console.log(result);
}).fail(function(a, b, c) {
alert("error");
});
If you want to send multiple input values with the file input, i suggest you create a view model and use that as explained in this post.
Also it might be a good idea to keep your form elements inside a form and set it's action value to the url you want to send and read that in your javascript code that hard coding it there.
<form asp-action="send" asp-controller="images" method="post">
<input type="file" name="File" id="File" />
<input type="text" id="id" value="0" />
<input type="submit" />
</form>
Now in your javascript you can read it from the form. For example, if you are wiring up the submit event of the form
$(function () {
$("form").submit(function (e) {
e.preventDefault();
var urlToPost = $(this).attr("action");
//your existing code for ajax call
});
});
Im working in a MVC .NET application. I assign a value to an element ID like this:
document.getElementById("latbox").value = event.latLng.lat();
and I retrieve it to show it like this:
<p>Latitud: <input size="20" type="text" id="latbox" name="lat" ></p>
The thing is, how can I find this value in my controller? Thanks.
In your view, you can use a <input type='hidden' name='lat'/> that you assign the value you need. Note that it must match the name of your controller parameter
#using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
<p>Latitud: <input size="20" type="text" id="latbox" name="lat"></p>
<input type="hidden" name="lat" id="latbox-hidden" />
<input type="submit" value="submit" />
}
<script type="text/javascript">
var lat = document.getElementById("latbox");
lat.value = "foo";
document.getElementById("latbox-hidden").value = lat.value;
alert(document.getElementById("latbox-hidden").value);
</script>
And your controller:
[HttpPost]
public ActionResult Action(string id, string lat) //same name to bind
{
//do your thing
}
HTML fields are posted using the name attribute, which in your case is "lat". On the controller you could have a parameter like this:
string lat
It would get the value of the HTML input element.
You can also use ajax call to send data to action
<head runat="server">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/AjaxTest/FirstAjax'; // give path of your action
var param = document.getElementById("latbox");
$.ajax({
type: "POST",
url: serviceURL,
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
I followed a tutorial to adapt the code. Here I am trying trying to auto-populate my form fields with AJAX when an 'ID' value is provided. I am new to Jquery and can't get to work this code.
Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request.
HTML form
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
I tried changing Jquery code but still I couldn't get it to work. I think Jquery is creating a problem here. But I am unable to find the error or buggy code. Please it would be be very helpful if you put me in right direction.
Edit 2 : I tried using
return false;
instead of
event.preventDefault();
to prevent the form from submitting but still it isn't working. Any idea what I am doing wrong here ?
Jquery
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
Ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}
I don't see where you're parsing your json response into a javascript object (hash). This jQuery method should help. It also looks like you're not posting your form using jquery, but rather trying to make a get request. To properly submit the form using jquery, use something like this:
$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );
Also, have you tried adding id attributes to your form elements?
<input type="text" id="name" name="name"/>
It would be easier to later reach them with
var element = $('#'+element_id);
If this is not a solution, can you post the json that is coming back from your request?
Replace the submit input with button:
<button type="button" id="submit">
Note the type="button".
It's mandatory to prevent form submition
Javascript:
$(document).ready(function() {
$("#submit").on("click", function(e) {
$.ajax({type:"get",
url: "ajax.php",
data: $("#form-ajax").serialize(),
dataType: "json",
success: process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
});
});