I'm attempting to send a GET request as soon as a button is pressed. As I'm quite inexperienced with HTML and JQuery/Ajax, I'm a little bit confused as to how to do this. My code is as following
<div id = "Reset">
<!-- <form method="get"></form> -->
<!-- <form action="https://wt.ops/reset" method="get"> -->
<button>Reset</button>
<!-- </form> -->
</div>
<script>
$("Reset").ready(function(){
$( "#Reset" ).click(function(){});
$.get( "https://wt.ops/reset", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
})});
</script>
Currently what it's doing is that it just loads the JQuery scripts automatically when the page is reloaded. But when I click the button, it does nothing.
You should attach the click handler after the document is loaded.
$("document").ready(function(){
//.. click handler
});
Your $.get should be within the click handler.
$("#Reset").click(function(){
$.get( "https://wt.ops/reset", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
});
Few things you have to update
1. this is just to ask have you added the jquery script in head
2. You have to change the id from div to button tag or remain as it is
<div>
<!-- <form method="get"></form> -->
<!-- <form action="https://wt.ops/reset" method="get"> -->
<button id="Reset">Reset</button>
<!-- </form> -->
</div>
3. You have to update the script function to below function. I have only changed the url to check the data
$(document).ready(function () {
$("#Reset").click(function () {
$.get("https://jsonplaceholder.typicode.com/todos", function (data) {
console.log(data);
alert("Load was performed.");
})
});
});
I see you use Jquery.
<div id = "reset">
<button >Reset</button>
<span id='result'> data</span>
</div>
$().ready(function(){
$( "#reset" ).click(function(){
console.log('click')
getFileFromNet();
});
function getFileFromNet(){
$.get( "https://rickandmortyapi.com/api/character/2", function( data ) {
$( "#result" ).html( data );
alert( "Load was performed." );
})
}
});
https://jsfiddle.net/eaLjb1n5/
Maybe it help you
First, you add jQuery in your html file. We use ajax method for send request.
Here is my code
<div>
<button id="submit">Reset</button>
</div>
<script>
$(document).ready(function(){
$("#submit").on("click",function(event){
$.ajax({
url: "", //your url
method: "GET",
success: function(data){
console.log(data);
},
error: function(){
alert("error");
}
});
});
});
</script>
if you have form data then you can submit form like this
<form id="form">
<input name="name" type="text"/>
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function(){
$("#form").on("submit",function(event){
event.preventDefault();
var f = $(this).serialize();
$.ajax({
url: "", //your url
method: "GET",
data: f,
success: function(data){
console.log(data);
},
error: function(){
alert("error");
}
});
});
});
</script>
Related
I am looking to use AJAX to submit multiple forms on submit. I need to get the value of a hidden field to use in the AJAX call. I have the first submit working just fine and returns the response expected.
example:
<form name="add_to_cart-12345" action="add_product" method="post">
<input type="hidden" name="products_id" value="12345" />
<input class="quantity" id="product_quantity" min="1" name="cart_quantity" value="1" step="1" type="number">
<input type="submit" class="add-to-cart" value="Add to Cart" id="addProduct-12345" />
This code can repeat 1 to n times with the values 12345 changing and being unique.
My Javascript is:
<script>
$(function() { // begin document ready
$('#addProduct').on('click', function(e) {
e.preventDefault();
var cart_quantity = document.getElementById('product_quantity').value;
var products_id = parseInt(document.getElementsByName('products_id').value);
var form = $(this).closest('form');
// AJAX request
$.ajax({
url: 'ajax_add_product.php',
type: 'POST',
dataType : "html",
data: {cart_quantity, products_id},
success: function(response){
console.log(response)
var TotalInCart = parseInt(document.getElementById('cartTotal').innerText);
var cartQuantity = parseInt(document.getElementById('product_quantity').value);
var headerTotal = cartQuantity + TotalInCart;
$("#cartTotal").html(headerTotal);
$("#cartProducts").html(response);
$("#ShoppingCartModal").modal({show:true});
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
$( document ).ajaxError(function() {
$( ".log" ).text( "Triggered ajaxError handler." );
});
});
</script>
What I need to do is to be able to submit any form when clicked. And push the product id, product quantity to the AJAX call.
let's say I have 2 pages :
index.html with this code :
<!DOCTYPE html>
<html lang="fr">
<head>
<title>test formulaire</title>
</head>
<body>
<div id="formulaire">
</div>
<!-- /#formulaire -->
Montre le formulaire
<!-- jQuery -->
<script src="js/jquery.js"></script>
<script src="js/monscript.js"></script>
</body>
</html>
I have an other page that containts my form :
<form name="monformulaire" id="monformulaire" role="monformulaire">
<input type="text" name="montexte" id="montexte" value="" />
<button id="bouton" type="submit">Let's go man !</button>
</form>
I have a Jquery.js and a personnal script like this :
function montreformulaire() {
alert('ok charge formulaire');
$.get( "monformulaire.html", function( data ) {
var formData = $.parseHTML (data );
$( "#formulaire" ).html( formData );
});
$('monformulaire').submit(function(event) {
alert('formulaire envoyé !');
event.preventDefault();
/*
$.ajax({
type: 'POST',
url: 'ajoute.php',
data: $(this).serialize(),
success: function (data) {
alert($('form').serialize());
//showMsg(data);
showSupportPage(id);
},
cache: false
});
*/
});
$( "#montexte" ).val( 'toto' );
}
my problem is that when the form is submit I want to use a jquery submit function but it doesn't work.
I don't see why and how I could fix that.
Any idea is welcome :-)
Thanks,
Alex
Because you missed a # while passing the id on submit handler
$('#monformulaire').submit(function(event) {
// Your code here..
});
Other selector is
$('[name=monformulaire]').submit({
// Your code here..
});
Choose whichever suits you.
Very classic and common question. You make an ajax call to an element, but you do element.click(...) before it is fetched, thus before it actually exists.
Place the $('#monformulaire').submit(function (with a #, that you forgot) inside the ajax callback function, like this :
$.get( "monformulaire.html", function( data ) { // This is done FIRST
var formData = $.parseHTML (data );
$( "#formulaire" ).html( formData ); // this is done THIRD, #monformulaire now exists
$('#monformulaire').submit(function(event) {........}) // this is done FOURTH, accessing the element!
});
$('#monformulaire').submit(function(event) {........}) // This is done SECOND and won't do anything because #monformulaire doesn't exist yet
Welcome to the world of async languages :)
Your submit functions is not good. Do it like so:
$('[name=monformulaire]').submit();
or
$('[name=monformulaire]').submit(function(){
//Do your thing here
});
You have to use $('form[name="monformulaire"]').submit(...)
I trying to sort the list of titles of the pages I can see the correct order after sorting in firebug console when i am hitting sort button it is not taking my request to the requested method. here is my jquery code I am kinda new in it.
<script>
$(function(){
$("#sortable").sortable();
$sortable = $("#sortable");
$( "#sortable_nav_items" ).sortable({
placeholder:"sortable-placeholder",
update: function( event, ui ) {
console.log($("#sortable_nav_items").sortable("toArray",{attribute:"pageid"}));
}
});
var order = $("#sortable_nav_items").sortable("toArray",{attribute:"pageid"});
console.log(order);
$sortable.bind('sortupdate',function(event,ui){
console.log($(this).sortable('toArray'));
$.post(
"content.cfc",
{method:"sortOrder",data:$(this).sortable('toArray')}
);
});
});
</script>
here is my list.
<cfoutput>
<div class="well">
<ul id="sortable_nav_items" class="list-group">
<cfloop query="_q">
<li class="list-group-item" pageid="#_q.id#" navOrder="#_q.nav_order#">
#_q.title#
</li>
</cfloop>
</ul>
</div>
<div class="form-group">
<div class="col-md-offset-3 col-md-9">
<button class="btn btn-info" type="submit">
<i class="glyphicon glyphicon-retweet"></i>
Sort
</button>
</div>
</div>
</cfoutput>
can anyone please help me out what i have to do in it to post the changes to the requested method ? Thanks.
You have not bound click event for your button.
$("button").click(function() {
var order = $("#sortable_nav_items").sortable("toArray",{attribute:"pageid"});
$.post(
"content.cfc",
{method:"sortOrder",data:order}
);
});
Here is jsfiddle (no coldfusion stuff though): http://jsfiddle.net/nn4x8/4/
If you want to send server request on every sort change, same handler for 'sortupdate' event. E.g.:
$("#sortable_nav_items").bind('sortupdate', function() {
var order = $(this).sortable("toArray",{attribute:"pageid"});
$.post(
"content.cfc",
{method:"sortOrder",data:order}
);
});
Try this,
$.post( "content.cfc", { data: $(this).sortable('toArray') } ).done(function( data ) {
alert( "Data Loaded: " + data );
});
Alternate of POST in jquery
$.ajax({
type: 'POST',
url: "content.cfc",
dataType: 'json',
beforeSend: function(){
sortOrder()
},
data: {'data':$(this).sortable('toArray')},
success: function(result){
alert(result)
},
});
I am trying to remove a div using jquery, but its not working.
This is my html code:
<html>
<body>
<div id="logout">
<form class="ajax" method="post" action="">
<div id="box_22">
<div id="box_23">
<div id="box_56">
<script src="http://code.jquery.com/jquery-1.10.2.min.js">
<script src="/../js/tt.js" type="text/javascript">
</body>
</html>
and my script is : how do i delete a box .
$(".delBtn").click(function (event) {
event.preventDefault();
var clickedID = 'clickId=' + this.id;
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "/addchannel/delUsr.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:clickedID, //Form variables
success:function(response){
alert("#box_"+clickedID);
$( "div #box_"+clickedID ).remove();
},
});
});
Your selector is wrong.... "div #box_"+clickedID is searching for an element with id "#box_"+clickedID inside a div element.
In your case you can use the id-selector directly
Update: The real culprit is the variable clickedID, you created it as a param string.... so the selector will fail.
$(".delBtn").click(function (event) {
event.preventDefault();
var id = this.id;
var clickedID = 'clickId=' + id;
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "/addchannel/delUsr.php", //Where to make Ajax calls
dataType: "text", // Data type, HTML, json etc.
data: clickedID, //Form variables
success: function (response) {
alert("#box_" + id);
$("#box_" + id).remove();
}
});
});
Remove the space:
$( "div#box_"+clickedID ).remove();
You don't need the 'div' in the Jquery selector
$( "#box_"+clickedID ).remove();
I am currently using JQuery BBQ Js plugin for ajaxified navigation of my website, while I am navigating the whole site with ajax, there's one link that would show me this error.
This is my markup
<ul>
<li><a id="thankyou" href="#views/thankyou.jsp">Ajaxified Thank You Message</a></li>
<li><a id="register" href="#views/ajaxvalidation.jsp">Ajaxified Register Register</a></li>
<li><a id="register" href="#views/othermessage.jsp">Ajaxified Other Message</a></li>
</ul>
All of those two links are working, but when I click the 2nd link and submit the form this error shows up when I click the other anchor tags.
Uncaught TypeError: Object function (e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")} has no method 'fragment'
That error was triggerd by this script.
$(function(){
var cache = {
'': $('.bbq-default')
};
$(window).bind( 'hashchange', function(e) {
var url = $.param.fragment();
$( 'a.bbq-current' ).removeClass( 'bbq-current' );
$( '.bbq-content' ).children( ':visible' ).hide();
url && $( 'a[href="#' + url + '"]' ).addClass( 'bbq-current' );
if ( cache[ url ] ) {
cache[ url ].show();
} else {
// Show "loading" content while AJAX content loads.
$( '.bbq-loading' ).show();
// Create container for this url's content and store a reference to it in
// the cache.
cache[ url ] = $( '<div class="bbq-item"/>' )
.appendTo( '.bbq-content' )
.load( url +"#content");//loads the content and get the div you want
}
})
$(window).trigger( 'hashchange' );
});
Specifically this line
var url = $.param.fragment();
What's causing that error?
Also this is what the second link looks like..
<!DOCTYPE HTML>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#content').on('submit','#result',function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
//this is the php file that processes the data and send mail
url: "register.action",
type: "POST",
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
$('#content').html(html);
}
});
})
})
</script>
</head>
<body>
<h3>Simple Ajax Validation.</h3>
<div id="divErrors"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id = "content">
<s:form action="register" id="result">
<label>UserName</label>
<s:textfield name="userBean.username" />
<s:fielderror />
<input type ="submit" id = "result_0" value="AJAX Submit" />
<!-- Test if Even Outside the main page can access the other elements -->
</s:form>
</div>
</body>
</html>
I've found the solution, the Jquery-bbq js is not being included on the Ajaxvalidation.jsp, what I did was I have included the jquery-bbq.js and its AJAX request in another JS file and both imported them if the respective page made a request