How can I enter data from clintside using webservice in asp.net? - javascript

I am trying this :
this my javascript code :
function insertVisitor() {
var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>'
$.ajax({
type: "POST",
url: pageUrl + "/insert_Visitor",
data: "{'name':'" + $("#txtName").val() + "','phoneno':'" +
$("#txtPhone").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall,
error: OnErrorCall
});
return false();
}
function OnSuccessCall(response) {
window.open("about.html");
}
function OnErrorCall(response) {
alert(response.status + " " + response.statusText);
}
</script>
this the html :
<form action="" method="post">
<table>
<tr>
<th>
<label>
please enter your Name :
</label>
</th>
<td>
<input id="txtName" type="text" value="" placeholder="Name" />
</td>
</tr>
<tr>
<th>
please enter your Phone No :
</th>
<td>
<input id="txtPhone" type="text" value="" placeholder="Phone No" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<!--<input id="btnEnter" type="button" style="background-image:~/images/pop_up/enter.png; height:40px; width:120px" />-->
<!--<input type="submit" name="button" id="button" value="enter" onClick="window.location='about.html'" />-->
<!--<a href="about.html" style="display: block">-->
<img src="images/pop_up/enter.png" width="120" height="40" alt="img" style="width: 120px;
height: 40px; position: relative; right: 0;" onclick="return insertVisitor()" />
<!--</a>-->
</td>
</tr>
</table>
</form>
and this is the webservice code :
[WebMethod]
public string insert_Visitor(string name, string phoneno)
{
string returnvalue = "";
if (name != "" && phoneno != "")
{
cmd.Parameters.Clear();
cmd.Connection = connection;
cmd.CommandText = "Insert_Into_VisitorLog";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Name", name);
cmd.Parameters.AddWithValue("#Phone", phoneno);
Object obj = cmd.ExecuteScalar();
if (obj != "0" || obj != "Unexpected error occurred!!")
{
returnvalue = Convert.ToString(obj);
}
else
{
returnvalue = Convert.ToString(obj);
}
}
return returnvalue;
}
the problem that i am facing is getting an error like this
400 Bad Request
how to solve this please help

The data part in jQuery is wrong
data: "{'name':'" + $("#txtName").val() + "','phoneno':'" +
$("#txtPhone").val() + "'}",
it should be
data: {'name': $("#txtName").val() ,'phoneno': $("#txtPhone").val() },
Edit 1
Also as you are returning string from you service so dataType is also wrong in you jquery call.
Differences between contentType and dataType in jQuery ajax function
Edit 2
var pageUrl = '<%=ResolveUrl("~/QuizEntry.asmx")%>'+"/insert_Visitor?name="+ $("#txtName").val()+"&phoneno="+ $("#txtPhone").val() ;
$.ajax({
type: "POST",
url: pageUrl,
success: OnSuccessCall,
error: OnErrorCall
});
Edit 3
Get more about error detail use the following
function OnErrorCall(xhr, ajaxOptions, thrownError)
{
alert(xhr.responseText);
}

Related

onchange function is working in a initial textbox but not working in the another textbox

When I do edit function in the text box the onchange function is working initially,But then i edit the next box filed the onchange function is not working,in some textbox i have give default values when i edit the textbox using onchange null values is displayed instead of default values.
overall Initial onchange function is called to every textbox present in the forms.
JavaScript:
$(document).ready(function () {
$("input#btnEditExperience").click(function () {
var id = $(this).attr("name");
var hospitalname = $("#<%=txtHospitalName.ClientID%>").val();
var department = $("#<%=txtDepartment.ClientID%>").val();
var designation = $("#<%=txtDesignation.ClientID%>").val();
var Fromdate = $("#<%=txtFromDate.ClientID%>").val();
var Todate = $("#<%=txtToDate.ClientID%>").val();
var Workdescription = $("#<%=txtWorkDescription.ClientID%>").val();
var Statusval = $("#<%=hdnExperienceID.ClientID%>").val();
if (Statusval == '') {
$('.errorEditTitle').html('Status required!');
Statusval.className += ' errors-text';
return false;
}
//$("div.preloader").show();
$.ajax({
type: 'POST',
url: pageUrl + "/UpdateExperience",
data: '{ExperienceID: "' + id + '",HospitalName:"' + hospitalname + '",Department:"' + department + '",Designation:"' + designation + '",FromDate:"' + Fromdate + '",ToDate:"' + Todate + '",WorkDescription: "' + Workdescription + '" }',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: OndocumentSuccess,
failure: function (response) {
alert(response.d);
}
});
});
});
function OndocumentSuccess(response) {
//$("div.preloader").fadeOut();
//$("#backgroundPopup").fadeOut("normal");
$("#<%=hdnExperienceID.ClientID%>").val('')
location.reload();
}
$(document).ready(function () {
$("a.Editview").click(function () {
$("#<%=hdnExperienceID.ClientID%>").val('');
});
});
function Editvalue(Edit) {
$("#<%=txtHospitalName.ClientID%>").val(Edit.value);
$("#<%=txtDepartment.ClientID%>").val(Edit.value);
$("#<%=txtDesignation.ClientID%>").val(Edit.value);
$("#<%=txtFromDate.ClientID%>").val(Edit.value);
$("#<%=txtToDate.ClientID%>").val(Edit.value);
$("#<%=txtWorkDescription.ClientID%>").val(Edit.value);
$("#<%=hdnExperienceID.ClientID%>").val(Edit.value);
}
Asp Page:
<a id='<%#Eval("ExperienceID")%>' data-toggle="modal" data-target="#Experienceedit<%#Eval("ExperienceID")%>" href="" class="edit-me Editview"><i class="tg-edit fa fa-pencil"></i></a>
Modal Popup:
<div class="modal fade bs-example-modal-lg" id='Experienceedit<%#Eval("ExperienceID")%>' tabindex="-1"
role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="background-color:black;">
<div class="modal-header" style="background-color:white;">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×</button>
<h4 id="myModalLabel">
Edit Experience
</h4>
</div>
<div class="modal-body" style="background-color:white;">
<div class="errorEditTitle">
</div>
<table class="index-table">
<tr>
<td>
<label>
Hospital Name<sub>*</sub></label>
</td>
<td>
<asp:TextBox ID="txtHospitalName" runat="server" class="span11 " MaxLength="100" onchange="javascript:Editvalue(this);" Text='<%#Eval("HospitalName")%>'
></asp:TextBox>
</td>
</tr>
<tr>
<td>
<label>
Department<sub>*</sub></label>
</td>
<td>
<asp:TextBox ID="txtDepartment" runat="server" class="span5 " onchange="javascript:Editvalue(this);" Text='<%#Eval("Department")%>'
></asp:TextBox>
</td>
</tr>
<tr>
<td>
<label>
Designation<sub>*</sub></label>
</td>
<td>
<asp:TextBox ID="txtDesignation" runat="server" class="span5" onchange="javascript:Editvalue(this);" Text='<%#Eval("Designation")%>'
></asp:TextBox>
</td>
</tr>
<tr>
<td>
<label>
From Date<sub>*</sub></label>
</td>
<td>
<asp:TextBox ID="txtFromDate" ReadOnly="true" runat="server" Class="form-control " onchange="javascript:Editvalue(this);" Text='<%#Eval("FromDate")%>'></asp:TextBox>
</td>
</tr>
<tr>
<td>
<label>
To Date<sub>*</sub></label>
</td>
<td>
<asp:TextBox ID="txtToDate" runat="server" ReadOnly="true" Class="form-control " onchange="javascript:Editvalue(this);" Text='<%#Eval("ToDate")%>'></asp:TextBox>
</td>
</tr>
<tr>
<td>
<label>
Work Description<sub>*</sub></label>
</td>
<td>
<asp:TextBox ID="txtWorkDescription" TextMode="MultiLine" runat="server" Class="form-control " onchange="javascript:Editvalue(this);" Text='<%#Eval("WorkDescription")%>'></asp:TextBox>
</td>
</tr>
</table>
</div>
<div class="modal-footer" style="background-color:white;">
<input type="button" class="btn btn-success" id="btnEditExperience"
value="Update" name="<%#Eval("ExperienceID")%>" />
<button class="btn btn-danger" data-dismiss="modal" aria-hidden="true">
Cancel</button>
</div>
</div>
If you are using jQuery I would recommend to bind events on document ready.
$(document).ready(function () {
$("input#btnEditExperience").click(function () {
var id = $(this).attr("name");
var hospitalname = $("#<%=txtHospitalName.ClientID%>").val();
var department = $("#<%=txtDepartment.ClientID%>").val();
var designation = $("#<%=txtDesignation.ClientID%>").val();
var Fromdate = $("#<%=txtFromDate.ClientID%>").val();
var Todate = $("#<%=txtToDate.ClientID%>").val();
var Workdescription = $("#<%=txtWorkDescription.ClientID%>").val();
var Statusval = $("#<%=hdnExperienceID.ClientID%>").val();
if (Statusval == '') {
$('.errorEditTitle').html('Status required!');
Statusval.className += ' errors-text';
return false;
}
//$("div.preloader").show();
$.ajax({
type: 'POST',
url: pageUrl + "/UpdateExperience",
data: '{ExperienceID: "' + id + '",HospitalName:"' + hospitalname + '",Department:"' + department + '",Designation:"' + designation + '",FromDate:"' + Fromdate + '",ToDate:"' + Todate + '",WorkDescription: "' + Workdescription + '" }',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: OndocumentSuccess,
failure: function (response) {
alert(response.d);
}
});
});
});
function OndocumentSuccess(response) {
//$("div.preloader").fadeOut();
//$("#backgroundPopup").fadeOut("normal");
$("#<%=hdnExperienceID.ClientID%>").val('')
location.reload();
}
$(document).ready(function () {
$("a.Editview").click(function () {
$("#<%=hdnExperienceID.ClientID%>").val('');
});
$('input[type="textbox"]').on('click', Editvalue);
});
function Editvalue(Edit) {
$("#<%=txtHospitalName.ClientID%>").val(Edit.value);
$("#<%=txtDepartment.ClientID%>").val(Edit.value);
$("#<%=txtDesignation.ClientID%>").val(Edit.value);
$("#<%=txtFromDate.ClientID%>").val(Edit.value);
$("#<%=txtToDate.ClientID%>").val(Edit.value);
$("#<%=txtWorkDescription.ClientID%>").val(Edit.value);
$("#<%=hdnExperienceID.ClientID%>").val(Edit.value);
}
And remove onchange attributes.
Try to change to another way to handle change event
$(document).on('change', '#txtFromDate', function() {
//
});

How can i get into the value inside of an html <tr> object

So i have this code. I want to send the data inside of my html inputs to the controllers parameters. In my jquery i have a line that looks like this
var currentRow = $(this).closest("tr");
But i have no clue how to get into the values of each input inside the currentRow Object how can i do that or do you maybe know a better way to do this?
// my html
#foreach (var discount in Model.DiscountList)
{
<tr>
<td>#Html.TextBox("codeTextBox", discount.Code) </td>
<td><input type="checkbox" name="freeShippingCheckBox" id="freeShippingCheckBox" checked="#discount.FreeShipping" /> </td>
#if (discount.isTwoForThree == true)
{
<td><input type="tel" value="Ta 3 betala för 2" readonly /></td>
}
else
{
<td><input type="number" value="#discount.PercentOffPrice"/></td>
}
<td><input type="checkbox" id="activeCheckBox" name="activeCheckBox" checked="#discount.Active" /></td>
<td><input type="datetime" value="#discount.CreatedDate" readonly /></td>
<td>
<input type="button" value="Radera" class="fa fa-remove" data-url="#Url.Action("DeleteDiscountCode","Discount",new { id= discount.Id})" />
<input type="button" value="Uppdatera" class="fa fa-update" data-url="#Url.Action("UpdateDiscount","Discount",new { id= discount.Id, })" />
<input type="button" value="Produkter" class="fa fa-products" />
</td>
<input id="#discount.Id.ToString()" type="hidden" value="#discount.Id" />
</tr>
}
//my jquery
$(".fa-update").on("click", function () {
var currentRow = $(this).closest("tr");
console.log(currentRow.children("#freeShippingCheckBox").val());
if (confirm("Are you sure you want to edit this discount code?"))
{
$.post($(this).data("url"), function (data) {
$.ajax({
url: '#Url.Action("DeleteUser","Discount")',
type: "POST",
data: "freeShipping=..........???????????",
success: function (data) {
if (data) {
}
location.reload();
}
});
location.reload();
alert("Deleted");
})
}
});
//my controller
[HttpPost]
public void UpdateDiscount(int id, bool freeShipping, int percentOfPrice, bool active)
{
Service.DiscountService.UpdateDiscount(id, freeShipping, percentOfPrice, active);
}
My proposal is:
$(function () {
$(".fa-update").on("click", function (e) {
var data = {};
var currentRowParams = $(this).closest("tr").find('input').each(function(index, element) {
var name = element.name ? element.name : 'undefined' + index;
data[name] = element.value || '';
});
var x = JSON.stringify(data);
console.log(x);
//
// If instead you want the params in a traditional GET
//
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<table>
<tbody>
<tr>
<td>#Html.TextBox("codeTextBox", discount.Code) </td>
<td><input type="checkbox" name="freeShippingCheckBox" id="freeShippingCheckBox" checked="#discount.FreeShipping" /> </td>
<td><input type="tel" value="Ta 3 betala for 2" readonly /></td>
<td><input type="checkbox" id="activeCheckBox" name="activeCheckBox" checked="#discount.Active" /></td>
<td><input type="datetime" value="#discount.CreatedDate" readonly /></td>
<td>
<input type="button" value="Radera" class="fa fa-remove" data-url="#Url.Action("DeleteDiscountCode","Discount",new { id= discount.Id})" />
<input type="button" value="Uppdatera" class="fa fa-update" data-url="#Url.Action("UpdateDiscount","Discount",new { id= discount.Id, })" />
<input type="button" value="Produkter" class="fa fa-products" />
</td>
<input id="#discount.Id.ToString()" type="hidden" value="#discount.Id" />
</tr>
</tbody>
</table>
You can access a value via .html(). As Vijai said, you can use serialize to make it a POST array like (&=, etc) format assuming you have a structured form. Or, to stay similar to your original code, you can just pass as usual JSON. like
data:{shippingInfo: "value", moreInfo: "blahblah"}
It is recommended to use a <form id="formID" ...> tag around yours inputs and use $("#formID").serialize() in the Ajax method if you are not doing processing of the input value in the View. Refer this sample link : Submit form using AJAX and jQuery
$.post($(this).data("url"), function (data) {
$.ajax({
url: '#Url.Action("DeleteUser","Discount")',
type: "POST",
data: $("#formID").serialize(),
success: function (data) {
if (data) {
}
location.reload();
}
});

Jquery .post() not calling script

I am trying to pass the data from a form to an insertion script without having the form data cleared. I am using this function to act on the press of the submit button but I get nothing. It is even set to throw an error if the form is missing data but it doesn't even get that far. I can only assume I am not calling it properly.
$(function() {
$(".submit").click(function() {
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity=' + facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
if (facility == '' || riskclient == '' || riskdate == '') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "insertriskass.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
<div class="body">
<div align='center'>
<div class="tablebackground">
<form method ="post" name= "form" id="form">
<table border='1' >
<tr>
<td>Facility</>
<td><input type="text" name= "riskFacility" id="facility"></td>
<td rowspan='4'><input type="submit" name="submit" value="New Client" class="submit"/</td>
</tr>
<tr>
<td>Client</td>
<td><input required type="text" name="riskClientId" id="riskclient" value="<?php echo htmlspecialchars($_POST['riskClientId']); ?>"></td>
</tr>
<tr>
<td>Audit Date</td><td> <input required type="text" id="datepicker" name="riskauddate" id="riskdate"></td>
</tr>
</table>
</form>
It is definitely not passing anything to the insertion script. So again, I think I am calling it incorrectly.
I see your html tags are not closed properly
<div class="body">
<form method="post" name="form" id="form">
<table border='1'>
<tr>
<td>Facility</td>
<td>
<input type="text" name="riskFacility" id="facility">
</td>
<td rowspan='4'>
<input type="submit" name="submit" value="New Client" class="submit" /> </td>
</tr>
<tr>
<td>Client</td>
<td>
<input required type="text" name="riskClientId" id="riskclient" value="">
</td>
</tr>
<tr>
<td>Audit Date</td>
<td>
<input required type="text" id="datepicker" name="riskauddate" id="riskdate">
</td>
</tr>
</table>
</form>
and check if it comes to error call back
I think it's useful..
$(document).ready(function () {
$('#submit').on('click', function (event) {
event.preventDefault();
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity='+ facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
or
// var datastring = $("#form").serialize();
if(facility=='' || riskclient=='' || riskdate=='' )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "insertriskass.php",
data: dataString,
success: function (msg) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
})
event.preventDefault used to stop submit and page reload.
datastring = $("#form").serialize(); used to submit all data values so no need to take each and every variable assign value.
You can refactor a little the code like this, revise your html tags. You have a double id property in an input, and missing clousure tags.
$(document).ready(function() {
$(".submit").click(function(event) {
event.PreventDefault();
var facility = $("#facility").val();
var riskclient = $("#riskclient").val();
var riskdate = $("#riskdate").val();
var dataString = 'facitlity=' + facility + '&riskclient=' + riskclient + '&riskdate=' + riskdate;
if (!facility || !riskclient || !riskdate) {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
//send ajax post
}
});
});

How to assign data from HTML form(in JSON format) to variable?

In my abc.html I have the following code which will covert the form data(hard coded for now) to JSON format:
<body>
<form enctype='application/json' method="POST" name="myForm">
<p><label>Company:</label>
<input name='Company' value='TESTCOMPANY'> </p>
<p><label>User Id:</label>
<input name='User' value='TESTUSER'></p>
<p><label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345' ></p>
<p><label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>
<p><label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>
From the code above I get *
{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}*
Now I need to assign the Json String formed by this data to variable 'FormData' so that FormData is like:
FormData = '{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}'
How do I do this assignment of data ?
The further code in abc.html will use this variable FormData in the following way:
function sendAjax() {
$.ajax({
url : "myurl",
type : 'POST',
dataType : 'json',
data : FormData,
contentType : 'application/json',
mimeType : 'application/json',
success : function(data) {
alert(data.uuid);
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
If you are not handling this in backend you can retrieve the data in Javascript in a variable then just appned it as JSON to your data using JSON.stringify().
This is a working snippet:
function submitform() {
var FormData = {
Company: myForm.Company.value,
User: myForm.User.value,
parameterMap: {
p1: myForm.p1.value,
p2: myForm.p2.value,
p3: myForm.p3.value
}
};
console.log(FormData);
$.ajax({
url: "myurl",
type: 'POST',
dataType: 'json',
data: JSON.stringify(FormData),
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert(data.uuid);
},
error: function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype='application/json' method="POST" name="myForm">
<p>
<label>Company:</label>
<input name='Company' value='TESTCOMPANY'>
</p>
<p>
<label>User Id:</label>
<input name='User' value='TESTUSER'>
</p>
<p>
<label>Division:</label>
<input type="text" name='p1' value='12345'>
</p>
<p>
<label>From:</label>
<input type="text" name='p2' value='20-MAR-2016'>
</p>
<p>
<label>To:</label>
<input type="text" name='p3' value='22-MAR-2016'>
</p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
Notes:
Use Javascript naming conventions, for example FormData will better be formData.
Using the provided HTML structure you could get the data into the format using:
function submitform(){
var form = document.querySelector('form');
var result = {};
var input = form.getElementsByTagName('input');
for(var i = 0; i < input.length; i ++) {
var row = input[i];
var rowName = ((row.name || '').match(/(\w+)(\[(\w+)\])?/) || []);
var rowIndex = rowName[3];
rowName = rowName[1];
if(rowName) {
var typeOfRowIndex = typeof rowIndex;
var rowValue = row.value;
if(typeof result[rowName] === 'undefined') {
var rowToAdd = {};
rowToAdd[rowIndex] = rowValue;
result[rowName] = typeOfRowIndex === 'undefined' ? rowValue : rowToAdd;
} else if(typeOfRowIndex !== 'undefined') {
result[rowName][rowIndex] = rowValue;
}
}
}
document.getElementById('output').innerHTML = JSON.stringify(result)
console.log(result);
return false;
}
<body>
<form enctype='application/json' method="POST" name="myForm">
<p>
<label>Company:</label>
<input name='Company' value='TESTCOMPANY'>
</p>
<p>
<label>User Id:</label>
<input name='User' value='TESTUSER'>
</p>
<p>
<label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345'>
</p>
<p>
<label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'>
</p>
<p>
<label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'>
</p>
<input value="Submit" type="submit" onclick="return submitform()">
</form>
<p>JSON Output (after clicking submit button):</p>
<div id="output"></div>
<p>Can also check console to see JSON object (after clicking submit button)</p>
</body>
var FormData = $('form[name=myForm]').serializeArray();
FormData = JSON.stringify(FormData);
I don't like jQuery, but:
var $inputs = $('form[name="myForm"]').find('input');
var res = {};
Array.prototype.forEach.call($inputs, function($item, index) {
res[ $item.getAttribute('name') ] = $item.value;
});
var FormData = JSON.stringify(res);
alert(FormData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form enctype='application/json' method="POST" name="myForm">
<p><label>Company:</label>
<input name='Company' value='TESTCOMPANY'> </p>
<p><label>User Id:</label>
<input name='User' value='TESTUSER'></p>
<p><label>Division:</label>
<input type="text" name='parameterMap[p1]' value='12345' ></p>
<p><label>From:</label>
<input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>
<p><label>To:</label>
<input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>

How can I use 'onkeydown' and 'onclick' with jquery?

I have this code in my php page:
<div id="chatarea">
<div id="jqarea">
<div class="chatboxcontent"></div>
</div>
</div>
<div class="chatbox">
<p>
<input type="text" name="digit" id="digit" size="50" onkeydown="javascript:checkChatBoxInputKey(event,document.getElementById('digit').value,'<?php echo $cuser ?>')" />
</p>
<p>
<button class="btn" title="send" type="button" onclick="filltxtarea(document.getElementById('digit').value,'<?php echo $cuser ?>')">
<span>Send</span>
</button>
</p>
</div>
In my javascript file I have this function:
function filltxtarea(desctext, uchat) {
$(".chatboxcontent").append('<div class=chatboxmessage><span class="chatboxmessagefrom">' + uchat + ': </span><span class="chatboxmessagecontent">' + desctext + '</span></div>');
$('#digit').val('');
$('#digit').focus();
alert("ok2");
jQuery.ajax({
type: 'POST',
url: 'chat.php',
dataType: 'json',
data: {
"newrow": "desctext"
},
success: function(response) {
alert(response);
}
})
}
function checkChatBoxInputKey(event, desctext, uchat) {
if (event.keyCode == 13 && event.shiftKey == 0) {
alert("ok1");
filltxtarea(desctext, uchat);
}
}
The code works for onclick but I have a problem with the onkeypressdown. When I use the Enter key it writes in the chat area, but when complete the filltxtarea function deletes the chatboxcontent text. Why is that happening?
This solution below was tested and it works fine.
First:
Remove onkeydown event of digit. It should be like this:
<input type="text" name="digit" id="digit" size="50" />
Remove onclick event of the button and set the id property.
<button class="btn" id="btnClick" title="send" type="button" >
create a input hidden in your html to store $cuser php var
<input type="hidden" name="cuser" id="cuser" val="<?php echo $cuser ?>" />
Replace your javascript to the following:
$(document).ready(function(){
$("#digit").keydown(function(event){
if (event.keyCode == 13 && event.shiftKey == 0) {
alert("ok1");
filltxtarea($("#digit").val());
}
});
$("#btnClick").click(function(){
filltxtarea($("#digit").val());
});
function filltxtarea(desctext) {
var uchat = $("#cuser").val();
$(".chatboxcontent").append('<div class=chatboxmessage><span class="chatboxmessagefrom">' + uchat + ': </span><span class="chatboxmessagecontent">' + desctext + '</span></div>');
$('#digit').val('');
$('#digit').focus();
alert("ok2");
jQuery.ajax({
type: 'POST',
url: 'chat.php',
dataType: 'json',
data: {
"newrow": "desctext"
},
success: function(response) {
alert(response);
}
})
}
});
Any doubts please let me know.
Hope it help.

Categories