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.
Related
I have text box(for live search) and whenever i enter more than 3 characters then
result is showing (from database) via ajax response as checkboxes with name, I just want whenever user
select any checkbox so this checkbox should display in div so user can search multiple data and can see
selected checkboxes,How can i do this ?
Right now Here is my html code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form action="/">
<h1>Newsletter Form</h1>
<p class="question">Newsletter Type?</p>
<div class="question-answer">
<label><input type="radio" value="Delas" name="DealType" /> Deals</label>
<label><input type="radio" value="PremiumDeals" name="DealType" /> Premium Deals</label>
</div>
<div id="deals-section" style="display:none;">
<p class="question">Add Merchant Name</p>
<div class="question-answer">
<input type="text" name="merchantname" id="merchantname" value="">
</div>
<div id="suggestions">
<div id="suggestionslist">
</div>
</div>
<img id="loading-image" src="<?php echo base_url(); ?>/assets/images/ajax-loader.gif" style="display:none;"/>
<table id="fees_table">
</table>
<div class="form-group">
<label class="control-label col-xs-3"></label>
<div class="col-xs-8">
<ul id="sparepartList" style="list-style-type: none; padding: 0;"></ul>
</div>
</div>
<div class="btn-block" id="send" >
<button type="submit" href="/">Send</button>
</div>
</div>
</form>
Here is my script which showing "MerchantName"(data from database) with "checkbox",i just want whenever we click on any
checkbox this "Merchant Data" should display in seprate div/belowcheckbox, How can i do this ?
<script>
$('#merchantname').keyup(function() {
var merchantname = $(this).val();
if(merchantname.length>= 3){
$.ajax({
type: 'POST',
url: "<?php echo base_url('Newsletter/GetMerchantName');?>",
cache : false,
data: {'merchantname': merchantname},
dataType: "json",
async: false,
beforeSend: function() {
$("#loading-image").show();
},
success: function(response) {
$('#sparepartList').empty();
$.each(response, function(key,value)
{
let li = $('<li><input type="checkbox" name="merchantName[]" value="' + value.merchantName + '" />' +
'<input type="text" name="sparepart" value="' + value.merchantName + '" /></li>');
$('#sparepartList').append(li);
});
$("#loading-image").hide();
},
error: function(response) {
console.log(response);
}
})
return false;
}
});
</script>
You can get the checkbox value on checked with jquery.
$('input[type=checkbox]').on('change', function() {
var val = this.checked ? this.value : '';
$('#showDiv').html(val);
});
jquery:
$("document").ready(function(){
alert('This is working');
$(".add_new").click(function() {
$(".table").hide();
$("#frm").show();
});
$(".insert_form").submit(function(){
var sending_data = {
"action": "insert"
};
sending_data = $(this).serialize() + "&" + $.param(sending_data);
$.ajax({
type: "POST",
url: "test.php", //Relative or absolute path to response.php file
data: sending_data,
success: function(return_data) {
alert(return_data); //This is not working.
}
});
});
});
test.php
<?php
echo $_POST['action'];
?>
HTML:
<form method="post" id="frm" style="display:none;" class="insert_form">
<input type="text" value="" required="required" placeholder="Enter your Name" name="user_name" />
<input type="submit" value="Submit" />
<input type="reset" value="clear" />
</form>
After submitting i have to display message. I am just testing using alert() but the alert box is appearing.Please Help.
I can't execute this jquery function properly. When I click on submit's form, only shows the two first alerts and then the page reloads. So I click again on the form's submit with the page reloaded and then shows the rest of the alerts (beginning by the third one) and then the function works fine.
In conclusion: I need to click on the form's submit two times instead of one to execute the function.
Any idea? Thank you.
JS Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
alert("enters script");
$(function () {
alert("enters jquery function");
$(".submit").click(function () {
alert("enters click submit function");
var name = $("#name").val();
var date = $("#date").val();
var dataString = 'name=' + name + '&date=' + date;
alert("saved variables");
if (name == '' || date == '') {
alert("enters if");
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
alert("enters else");
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function () {
alert("enters success");
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
refresh();
}
});
}
return false;
});
});
</script>
HTML Code:
<form method="post" name="form">
<ul>
<li>
Name <input id="name" name="name" type="text" />
</li>
<li>
Date <input id="date" name="date" type="date" />
</li>
</ul>
<div >
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
use the event.preventdefault to stop the submission of the page
http://api.jquery.com/event.preventdefault/
Your problem is using submit buttons, they have some default behaviors other than what you add as a event to it.
replaced this:
<input type="submit" value="Submit" class="submit" />
with:
<input type="button" value="Submit" class="submit" />
this you working DEMO
other than changing the submit button to a regular button, you can fix your code by disabling that default behaviors, adding onsubmit to your form node:
<form method="post" name="form" onsubmit="return false;">
<!--your stuff-->
</form>
Try this:
<script type="text/javascript">
$( document ).ready(function() {
$(".submit").click(function(){
alert("entra en la funcion del clic del submit");
var nombre = $("#nombre").val();
var fecha = $("#fecha").val();
var dataString = 'nombre='+ nombre + '&fecha=' + fecha;
alert("variables guardadas");
if(nombre=='' || fecha=='')
{
alert("entra en el if");
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
alert("entra en el else");
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function()
{
alert("entra en el success");
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
refresca();
}
});
}
return false;
});
});
First of all, thank you to everybody for your help.
Finally the main problem comes from other part of the code. I was using pjax (https://github.com/thybag/PJAX-Standalone) to replace the form with other html document (in this case page1.html) after doing the mysql insert through "join.php". And I'm not calling the jquery function properly.
Explanation: You begin in page1.html, then click on "Go To Page 2" (This replace the div "content" with the body of page2.html). Then complete the form and submit it. When you click on submit, activates the jquery function (join.php mysql insert inside) and finally replace again the div "content".
Solution (this works):
page1.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="pjax-standalone.js"></script>
<script type="text/javascript">
pjax.connect({
'container': 'content',
'beforeSend': function(){console.log("before send");},
'complete': function(){console.log("done!");
if($("#button_pg_2").length)
{
$( document ).ready(function()
{
$(".submit").click(function()
{
var nombre = $("#name").val();
var fecha = $("#date").val();
var dataString = 'name='+ name + '&date=' + date;
if(name=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax(
{
type: "POST",
url: "join.php",
data: dataString,
success: function()
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
replace();
}
});
}
return false;
});
});
}
}
});
</script>
<script type="text/javascript">
function replace()
{
pjax.invoke('page1.html', 'content');
}
</script>
</head>
<body>
<div id="header">
This div never changes
</div>
<div id="content">
Go To Page 2
</div>
</body>
</html>
page2.html
<html>
<body>
<form method="post" name="form">
<ul>
<li>
Name <input id="name" name="name" type="text" />
</li>
<li>
Date <input id="date" name="date" type="date" />
</li>
</ul>
<div >
<input type="button" id="button_pg_2" value="submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
</body>
</html>
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);
}
Here's a form that I have:
<form class="form-horizontal" id="login-form">
<input name="email" id="email" type="email" size="30" class="span4" placeholder="Email" style="margin-top:20px; margin-left:20px; width: 270px;"/>
<br>
<input name="passwd" id="passwd" type="password" class="span4" placeholder="Password" style="margin-top:10px; margin-left:20px; width: 270px;"/>
<br><br>
<input type="button" id="login" name="login" value="Go" class="btn btn-custom" style="width:30%; margin-left:30px; margin-top:20px"/>
<br>
<br>
</form>
Here a ajax call I make using JavaScript to submit the data on clicking the button:
$('#login').click(function(){
$.ajax({
url:"script.php",
type:'POST',
dataType:"json",
data: $("#login-form").serialize()
}).done(function(data){
//do domething
});
});
How can I submit the data both by pressing the enter key and clicking on the submit button?
I have updated code. Create a function and call it on both textbox keypress event and identify submit button then call function and on click event of button.
function submitLogin() {
$.ajax({
url:"script.php",
type:'POST',
dataType:"json",
data: $("#login-form").serialize()
}).done(function(data){
//do domething
});
}
$('#email').keypress(function(e) {
if (e.which == '13') {
submitLogin();
}
});
$('#passwd').keypress(function(e) {
if (e.which == '13') {
submitLogin();
}
});
$('#login').click(function(){
submitLogin();
});
How about to change input type to "submit" and input click event into form submit?
<input type="submit" id="login" name="login" value="Go" class="btn btn-custom" style="width:30%; margin-left:30px; margin-top:20px"/>
JQuery
$('#login-form').submit(function(){
$.ajax({
url:"script.php",
type:'POST',
dataType:"json",
data: $("#login-form").serialize()
}).done(function(data){
//do domething
});
});
You should be able to add keypress function on both email and password fields.
$('#email').keypress(function(e){
if (e.keyCode == 13) {
$('#login-form').submit(/*...*/);
}
}
I gave you example for one field.
Use On method to work on Entering and clicking
$('#element').on('click keypress', function(event) {
var check = 1; // Default for Click
if (e.keyCode == 13) //When Enter Key is pressed
{
var check = 1;
}
else
{
var check = 0; // other keys pressed
}
if (check == 1)
{
$.ajax({
url:"script.php",
type:'POST',
dataType:"json",
data: $("#login-form").serialize()
}).done(function(data){
//do domething
});
}
});
this is the idea:
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
runAjax();
// or
// runSubmit();
}
});
$('#login').click(function(){
runAjax();
//or
//runSubmit();
});
function runAjax(){
$.ajax({
url:"script.php",
type:'POST',
dataType:"json",
data: $("#login-form").serialize()
}).done(function(data){
//do domething
});
}
function runSubmit(){
$("form").submit();
}