Why doesn't jquery submit work properly? - javascript

This code works fine in its current state where im using a click event on a button. But if i use a form tag around the input tags in my html code and use jquery's submit method it doesnt give any results. why is that happening? i have to use the form element because i want to be able to search with an enter key insted of clicking on a button
Html:
<body>
Title: <input type="text" id="title"><br/>
<input type="submit" value="Submit" id="btn">
<p id="results"></p>
<body>
jQuery:
$(document).ready(function(){
$("#btn").on("click", function(){
var textval = $('#title').val();
var playListURL = 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + textval + '&format=json&callback=?';
$.ajax({
type: "GET",
url: playListURL,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
for (var i = 0; i < 10; i++)
{
var url = "https://en.wikipedia.org/wiki/" + data.query.search[i].title;
$("#results").append("<b> <a href='" + url + "' > " + data.query.search[i].title + "</a></b></br> ");
//console.log(url);
}
},
error: function (errorMessage) {
}
});
//alert($('#title').val());
});
});

Try to change this line
$("#btn").on("click", function(){
to this:
$("#btn").on("click", function(e){
e.preventDefault();
Then the form will not submit default way on click

Related

How to access id of the modal globally using JavaScript Laravel Laravel

I'm have an html table with modal column (see image below for your reference)
Upon click the Order modal, I can access the its ID using onclick event in JavaScript
(var customer_id = $(this).val();)
I wanted to access and used it in my Add function using ajax but I'm having an error of "customer_id is not defined" when I tried to use it. Is there a way to fix it or do it properly.
This is my script
<script>
$(document).ready(function () {
// START OPEN CART MODAL FUNCTION
$(document).on('click', '.viewCart', function (e) {
e.preventDefault();
var customer_id = 0;
var customer_id = $(this).val();
console.log(customer_id);
$.ajax({
type: "GET",
url: "/get-cart/"+customer_id,
dataType: "json",
success: function (response) {
if (response.data != null) {
console.log(response);
$('.OrderTbody').html("");
$.each(response.data, function (key, item) {
$('.OrderTbody').append('<tr>\
<td>' + item.p_name + '</td>\
<td>' + item.c_qty + '</td>\
<td class="total">' + item.p_amt + '</td>\
<td><button type="button" value="' + item.c_id + '" class="btn btn-danger deleteListBtn btn-sm">Delete</button></td>\
\</tr>');
});
}
}
});
});
// END OPEN CART MODAL FUNCTION
// START ADD DATA FUNCTION
$(document).on('click', '.addToCart', function (e) {
e.preventDefault();
var data = {
'store': $('.sel_store').val(),
'product': $('.sel_product').val(),
'quantity': $('.sel_qty').val(),
// HOW TO INPUT Customer ID here, I tried this but im having an error of
// customer_id is not defined
'customer_id': customer_id,
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/cart-list",
data: data,
dataType: "json",
success: function (response) {
}
});
});
// END ADD DATA FUNCTION
});
</script>

Clear textbox after selection of different radio button in jQuery

I'm adding Radio button dynamically
function RadioButton() {
$.ajax({
type: "POST",
url: "VPATransaction.aspx/SetRadioButton",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (result) {
var jsonData = eval(result.d);
$.each(result.d.Table, function (index, value) {
$('#rb').append("<ul><li><input type='radio' name='radio' id='rbs_' value=" + value.PurposeTransid + " style><span id='tf' name='TextFiled'>" + value.Purpose_trans_name + " </span></li></ul>");
$("#rbs_").click(function () {
$("#tf0").val("");
});
});
}
})
}
**TextBox is also adding dynamically**
function Textbox() {
$("#add")
.append($(" <div class='col-md-12'>")
.append($(" <input type='text' name='TextField' id='TF" + Tcount + "'class='col-sm-12 col-md-12 col-xs-12' />")
.append($("</div>")
)
)
);
Tcount++;
}
because on button click I'm adding more textBox
Goal is to clear value of textbox when i click on other radio button
I have used .val and .attr but nothing happend
Here you did not use the click function while using the textbox dynamic function. So you can use like following method,
$(document).ready(RadioButton(){
$('#btnClear').click(RadioButton(){
if(confirm("Want to clear?")){
$('#form1 input[type="text"]').val('');
$('#form1 #txtAddress').val('');
Here when you click the Radio button the function will automatically clear the text box after you click yes on the dialog box appears.

Submit form with two diffrent submit button inside the form by jquery-ajax

I looked for many answers here but couldn't resolve this. I'm trying to submit form with two different submit button in the form but in the result it is like asking for method and action for the form. Though i have used e.preventDefault()
for preventing default form submission. thanks
Here is my form
<form class='detail-button'>
<input type='hidden' id='sell_id' value='$pro_id' />
<input type='hidden' id='sell_name' value='$pro_name' />
<input type='hidden' id='sell_vd' value='$vendor' />
<input type='submit' id='sell_add' class='btn' value='ADD TO CART'/>
<input type='submit' id='sell_buy' value='BUY NOW'/>
</form>
And here is script used
$(document).ready(function() {
$('#sell_add').on('click', function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
$.ajax({
type: "POST",
url: "add_to_cart.php",
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click=cart',
beforeSend: function() {
$("#add_status").hide();
},
success: function(data) {
var result = jQuery.parseJSON(data);
$("#add_status").show();
$("#add_status").html(result.stat);
$(".cartqty").html(result.qty);
}
});
});
});
$(document).ready(function() {
$('#sell_buy').on('click', function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
$.ajax({
type: "POST",
url: "add_to_cart.php",
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click=buy',
success: function(data) {
window.location.href = data;
}
});
});
});
PLease Use :
detail-button is Your Form Class
$('.detail-button').on('submit',function(event){
// Write Your AJAX Code Here
}
Change Your submit button type. It will work because you have set event on button click by using its id.
<input type='button' id='sell_add' class='btn' value='ADD TO CART'/>
<input type='button' id='sell_buy' value='BUY NOW'/>
and submit through JS
$(".detail-button").submit();
I propose to use the submit event for submitting the form and a click event for adding to cart. Furthermore change the submit type for "add to cart" to button
You can use this script:
$('#sell_add, #sell_buy').on('click', function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
var click = this.id == "sell_add" ? "cart" : "buy"; // <---check if clicked button is "sell_add"
$.ajax({
type: "POST",
url: "add_to_cart.php",
context:this, // <----------add context to get the clicked button
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click='+click ,
beforeSend: function() {
$("#add_status").hide();
},
success: function(data) {
if(this.id == "sell_id"){ // <--------------execute for sell_add
var result = jQuery.parseJSON(data);
$("#add_status").show();
$("#add_status").html(result.stat);
$(".cartqty").html(result.qty);
} else { // <----------execute for buy.
window.location.href = data;
}
}
});
});
or a better one is to use data-* attribute to store specific information:
<input type='submit' data-click='cart' id='sell_add' class='btn' value='ADD TO CART'/>
<input type='submit' data-click='buy' id='sell_buy' value='BUY NOW'/>
use this script below:
$('#sell_add, #sell_buy').on('click', function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
var click = $(this).data('click'); //<------get the data-click here
$.ajax({
type: "POST",
url: "add_to_cart.php",
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click='+click,
beforeSend: function() {
$("#add_status").hide();
},
success: function(data) {
if(click == "cart"){ // <--------------execute for data-click="cart"
var result = jQuery.parseJSON(data);
$("#add_status").show();
$("#add_status").html(result.stat);
$(".cartqty").html(result.qty);
} else { // <----------execute for data-click="buy".
window.location.href = data;
}
}
});
});
See the updated code i have added here.
usually e.preventDefault() work but if u added return false at the end of event then it help much.
see the code snippet might be it will help you
$(document).ready(function() {
$(document).on("click","#sell_add",function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
$.ajax({
type: "POST",
url: "add_to_cart.php",
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click=cart',
beforeSend: function() {
$("#add_status").hide();
},
success: function(data) {
var result = jQuery.parseJSON(data);
$("#add_status").show();
$("#add_status").html(result.stat);
$(".cartqty").html(result.qty);
}
});
return false;
});
$(document).on("click","#sell_buy",function(event) {
event.preventDefault();
var id = $("#sell_id").val();
var name = $("#sell_name").val();
var vendor = $("#sell_vd").val();
$.ajax({
type: "POST",
url: "add_to_cart.php",
data: 'id=' + id + '&name=' + name + '&vendor=' + vendor + '&click=buy',
success: function(data) {
window.location.href = data;
}
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='detail-button'>
<input type='hidden' id='sell_id' value='$pro_id' />
<input type='hidden' id='sell_name' value='$pro_name' />
<input type='hidden' id='sell_vd' value='$vendor' />
<input type='submit' id='sell_add' class='btn' value='ADD TO CART' />
<input type='submit' id='sell_buy' value='BUY NOW' />
</form>

jQuery .hide() and .show() not working

I have this code generate dynamically using php code:-
<div class="mailList" id="M_6">
<div class="mailListHeader" id="H_6">
<img style="float:right; display:none;" class="loaderIMG" id="LOADER_6" src="images/preloader.gif">
Sent by <strong>Admin</strong> on <strong>Oct 03 2013 02:53 PM</strong> to <strong>Received Response</strong> for Quarter <strong>3</strong> Year <strong>2013</strong>.<br>
Subject: <strong>Test Mail</strong><br>
</div>
<div class="mailListContent" id="C_6">
<div class="closeContent" id="CC_6">Close [x]</div>
<span id="SPAN_6"></span>
</div>
<div class="mailListFooter" id="F_6">
<span class="mailContentBtn" id="MCBTN_6" style="font-size:11px; color:#09C; cursor:pointer;">
View Content
</span>
<span class="mailListBtn" id="MLBTN_6" style="float:right; font-size:11px; color:#C06; cursor:pointer;">
Successfull-[0] Failed-[4]
</span>
</div>
</div>
Then, user can click View Content or Successfull-[0] Failed-[4] that will make a ajax request than display result in div mailListContent. Below is code for the jquery ajax request:-
$(".mailContentBtn, .mailListBtn").click(function(){
var currentId = $(this).attr('id');
currentId = currentId.split("_");
var actualId = currentId[1];
if($("#C_"+actualId).is(":visible")) {
$("#C_"+actualId).hide("slow","swing");
}
$("img#LOADER_"+actualId).show();
if(currentId[0]=="MCBTN") {
var dataString ="action=getMailContentByID&mailID="+actualId;
} else {
var dataString ="action=getMailListByID&mailID="+actualId;
}
$.ajax({
type: "POST",
url: "include/getMail.php",
data: dataString,
cache: false,
async: false,
success: function(html) {
$("#SPAN_"+actualId).empty();
$("#SPAN_"+actualId).append(html);
$("#C_"+actualId).show("slow","swing");
$("img#LOADER_"+actualId).hide();
}
});
});
The request and the events works fine, the problem is every time user click at View Content or Successfull-[0] Failed-[4] the loading image is not display. As you can see, I give a unique ID for every loading image than only 1 loading image will display on clik. There is no error in inspect code in Google Chrome. How can I solve this?
Thank you.
In your call to $.ajax, change the "async" option to "true". Because in your case, the $.ajax is blocking the ui thread in displaying the loading image as it is executed synchronously.
You have missed:
$(document).ready(function () {
});
try this:
<script>
$(document).ready(function () {
$(".mailContentBtn, .mailListBtn").click(function () {
var currentId = $(this).attr('id');
currentId = currentId.split("_");
var actualId = currentId[1];
if ($("#C_" + actualId).is(":visible"))
$("#C_" + actualId).hide("slow", "swing");
$("img#LOADER_" + actualId).show();
if (currentId[0] == "MCBTN") {
var dataString = "action=getMailContentByID" +
"&mailID=" + actualId;
}
else {
var dataString = "action=getMailListByID" +
"&mailID=" + actualId;
}
$.ajax({
type: "POST",
url: "include/getMail.php",
data: dataString,
cache: false,
async: false,
success: function (html) {
$("#SPAN_" + actualId).empty();
$("#SPAN_" + actualId).append(html);
$("#C_" + actualId).show("slow", "swing");
$("img#LOADER_" + actualId).hide();
}
});
});
})
</script>

JS/AJAX Auto submit form: Disabling enter key to prevent page refresh

I am using a function that will submit with ajax and without the help of a button click. But I am currently undergoing two issues which with trial and error haven't found plausible solutions:
First is there any way I can disable the enter button click(this causes the whole page to refresh)?
JSFIDDLE basic example in how the JS function works
Second, It feels like I am going the roundabout way to display what has been posted. How can I change this part of the function $('#special').html('<p>' + $('#resultval', result).html() + '</p>'); to have it POST just inside a div called #special without the need of span or <p> #resultval?
Everytime i echo through php I have to do set it like this to display a result: <div id="special"><span id="resultval">This is the result.</span></div>
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});
</script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(event){// the function call on click or on submit onclick=submitForm(event);
event.preventDefault(); //to prevent enter key
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').text(result); //you can use text() or html() only
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});

Categories

Resources