Dropdown list using jquery - javascript

I am trying to implement a simple Jquery drop down.
HTML
<h2> Networked Graphs</h2>
<p> Select the node ID from the drop down to see graphs up to a depth of 5 </p>
<form id="my form">
<label for="Node_type">Node_Type</label>
<select id="dropdown_change">
<option value="Customer">Customer</option>
<option value="Phone">Phone</option>
<option value="ID_Card">ID_Card</option>
</select>
<input type='submit' value='Submit'>
</form>
This is the jquery code:
var selectID = $("#dropdown_change").val();
$.ajax({
type: "POST",
url: '/echo/html/',
data: {
html: "<span>This is the ajax response...</span>",
delay: 2
},
success: function(data) {
showMsg('SUCCESS: ' + data);
},
error: function (xhr, textStatus, errorThrown) {
document.getElementById('dropdown_change').selectedIndex = 0;
showMsg('ERROR: ' + errorThrown);
return false;
}
});
}) // closes ?
Selecting from the drop down and clicking on the submit button should display the success message 'SUCCESS: This is the Ajax response'.
Even though I specify "type: POST" and SUCCESS as well as ERROR messages, it fails with the below error:
{"error": "Please use POST request"}
Here is the Jsfiddle. Trying to learn javascript/jquery.

The jQuery Ajax is running as soon as the page loads. It does not run when the button is clicked. When the button is clicked, the HTML form is being submitted.
The way to do this would be to add a listener to the button that intercepts the submit and calls the jQuery Ajax. It would look something like this:
$('input[type=submit]').click(function() {
var selectID = $("#dropdown_change").val();
$.ajax({...
return false;
});
Here is a working fiddle

After jquery 1.9.0, you should use
method: "POST"
instead of
type: "POST"
Link

Related

how to fire two different event from the same toggle switch using php and ajax

switch off image
switch on image
I want to make a toggle switch which needs to fire two different event from the same toggle switch using php and ajax & I have made this following html code
<div id="about-btn" class="card-action">
<div class="about-btn">
<input type="checkbox" id="cfl" name="cfl" class="switch-input">
<label for="cfl" class="switch-label"><h4>CFL <span class="toggle--on">ON</span><span class="toggle--off">OFF</span></h4></label>
</div>
</div>
& following php code
<?php
if(isset($_POST['cfl'])) {
makeRequest('cfl_on'); // user checked the box
} else {
makeRequest('cfl_off'); // user did not check the box
}
?>
this php needs to pass value to the "makeRequest()" function of my script
<script>
function makeRequest(actionParam){
var request = $.ajax({
url: "controller.php",
type: "POST",
data: {Action : actionParam},
dataType: "html"
});
request.done(function(msg) {
//alert(msg);
// $("#ResponseDiv").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
I know I'm doing something wrong but unable to figure it out. any help will be highly appreciated. thanks in advance for the help.
if you want to do two diferent ajax calls than:
$('.switch-label').on('click', function(){
if($('#cfl').is(':checked'){
"make ajax call 1 here"
}
else{
"make ajax call 2 here"
}
});
Or if you only want to hide/show your image than than just toggle the image container on click $('cfl')

Ajax request doesn't auto trigger on form change

<form>
<select name="select-1">
<option value="option-1">Option 1</value>
<option value="option-2">Option 2</value>
</select>
<button type="submit">Submit</button>
</form>
I have a form that when the button is clicked, it populates a div with html content from an Ajax request without any page reload ( its done in the backend, cant say much more because its not my area of expertise ). When the submit button is clicked, it works as expected, but the behaviour I want is for the Ajax request to auto-trigger when the form has an option selected, without the need to press the button.
$(document).on(
"change",
"select[name=select-1]",
function(e) {
if ($(this).val()) {
$(document)
.find("form")
.submit();
}
}
);
The problem here is that the form submits and reloads the page, not triggering the Ajax request. I have also tried to trigger a click event on the button itself:
$(document).on(
"change",
"select[name=select-1]",
function(e) {
if ($(this).val()) {
$(document)
.find("button")
.click();
}
}
);
.. but nothing happens.
// try something like this, as suggested by #Anjana. try to submit form data
// using ajax.
$(document).on(
"change",
"select[name=select-1]",
function(e) {
if ($(this).val()) {
var formData = new FormData();
formData.append("select-1", $(this).val());
$.ajax({
url: {your url},
method: "post",
data: formData,
success: function(data) {
div.innerHTML = data;
}
});
}
}
);
In my opinion, if you are using AJAX, you should trouble with form. You only need something to trigger the call. That can simply be a button.
<select id="menu" name="select-1">
<option value="option-1">Option 1</option>
<option value="option-2">Option 2</option>
</select>
<button type="submit">Submit</button>
Select the value that the user has selected in the select menu with:
const selection = $( "#menu option:selected" ).text();
Then use the $.ajax() function provided by jQuery:
$(document).ready(function() {
$('#submit').click(function() {
$.ajax({
type: "POST",
url: "<CHANGE HERE>",
data: { selection: selection },
dataType: "json"
});
});
});
You have used button type ="submit", which makes the page reload. So remove type submit from your button and use ajax or use e.prevent default() like
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
url: url, //type your url,
method: "post",
data: data,
success: function(data) {
},
error: function(data){
}
});
After that on change when you submit the form on change event as you are doing, it will trigger the Ajax request and work as you expect.
Learn More about Ajax here
First of all, the jQuery code you are using is not AJAX, you can learn more about jQuery and AJAX from their documentation here:
http://api.jquery.com/jquery.ajax/
Here is the solution to your problem:
<!--HTML CODE-->
<form>
<select name="select-1">
<option value="option-1">Option 1</value>
<option value="option-2">Option 2</value>
</select>
<button type="submit">Submit</button>
</form>
Here's the jQuery code that actually uses AJAX.
A selector is used to get the <select></select> and then we set an event listener to listen when the object is changed.
UPDATE: This now allow you to attach event listener to dynamically created elements
$(document).ready(function() {
$(body).on('change', "select[name=select-1]", function() {
$.ajax({
url: "https://example.com",
method: 'GET',
data: {"id": 123, "value": $('select[name=select-1]').val()}
})
.done(function (){
alert("success");
})
.fail(function (){
alert("error" + $('select[name=select-1]').val());
});
})
});
You can change the url in the AJAX, as well as method with GET or POST, and the data to be sent to the URL.
After that, if the AJAX request is successful, the code in the .done() section will be executed.
Similarly, if the request fails, the code in fail() will be executed.

Calling same controller's method using ajax GET and POST type

Hi I am a newbie to Grails and Groovy. Please help me to solve the below issue related to calling controller's method using ajax call.
The scenario behind the code is to recover the password using the username whenever the user is unable to remember the password. I have explained the code flow in detail below.
Application begins with the below auth.gsp page:
<form action='${postUrl}' method='POST' id='loginForm' autocomplete='off'>
<input type='text' name='j_username' id='username'/>
<input type='password' name='j_password' id='password'/>
<input type='submit' id="submit" value='${message(code: "default.button.login")}'/>
<g:message code="etranscripts.forgotPassword"/>
</form>
When I click on the Forgot password link of the anchor tag, it will call the below ajax method:
<script>
$(document).ready(function () {
$('#recovery-link').click(function () {
var url = $(this).attr('recovery-url')
$.ajax({
url: url,
dataType: "html"
}).done(function (html) {
$('#loginForm').replaceWith(html)
$('#sign-in-instruct').text('<g:message code="js.resetEnterName"/>')
}).fail(function (jqXHR, textStatus) {
console.log("Request for url failed: " + url)
})
event.preventDefault()
return false
});
});
The controller method for the above call is as below.
def recoverPassword = {
println "RecoverPassword method of ctrl....."
if (!request.post) {
// show the form
render(template: "recoverPassword" )
return
}
//some other stuff based on the input conditions.
The successful output template for the above ajax call is:
<div id="recover-password" >
<ul>
<li>
<span><g:textField name="username" id="username" value="" /></span>
<input type='submit' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>
</li>
</ul>
Till here my code works perfect. But the issue begins from here.
i.e When I enter some value in the username field of the template and click on submit, it should call the below ajax method.
$(document).on('click', '#submit-username-link', function (event) {
var url = $(this).attr('recovery-url')
var username = $('input#username').val();
$.ajax({
url: url,
type: "POST",
data: {username:username},
dataType: "json"
}).done(function (responseJson) {
$('#sign-in-instruct').text(responseJson.message)
$('div.copyright').css('margin','74px 0px 0px 140px')
$('#home-link').show()
if ( responseJson.status == 'success') {
$('#recover-password').remove()
}
}).fail(function (jqXHR, textStatus) {
$('#recover-password').remove()
$('#sign-in-instruct').text(textStatus)
console.log("Failed to send the email " + textStatus)
})
event.preventDefault()
return false
});
The thing is, url refers to the same method of the controller but the only change is POST type is used and that will be taken into consideration inside the method using if conditions.(i.e some other stuff of the controller)
These GET and POST type of method calls are configured as shown below in the URLMappings.groovy file.
"/recoverPassword/recoverPassword"(controller: 'recoverPassword') {
action = [GET: "recoverPassword", POST: "recoverPassword"]
}
The whole summary of this question is, for the same method of controller, GET request is working but POST type of ajax call is not able to reach the controller's method.
Am I doing anything wrong over here? Please help me to solve this issue. Thanks in advance :-)
Overcomplicated. Why don't you use separate function in controller for GET (rendering the form) and separate function for POST (for handling the recovering the password)?
Check out also https://en.wikipedia.org/wiki/KISS_principle
Change input Type submit to button
<input type='button' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>

AJAX POST success and error firing

I checked many posts here regarding same issue but nothing was working, and more or less it behaves like a glitch:
function onbtnclick(){
var user_email=$('#user_email').val();
var send_data = {email:user_email};
$.ajax({
type: 'POST',
url: 'someURL.php',
crossDomain: true,
data:send_data,
dataType: 'text',
success: function(responseData, textStatus, jqXHR) {
alert("Thank you for the mailing list");
},
error: function (responseData, textStatus, errorThrown) {
alert('Your email is already in our mailing list.');
console.log('log e:'+responseData);
console.log('log e:'+textStatus);
console.log('log e:'+errorThrown);
}
});
return false;
}
};
<form name="myform">
<input id="user_email" type="email" name="email" placeholder="Your Email Here" style="width:300px" required><br>
<br><button type="submit" class="leka-button button-style2 offer_button" onclick="onbtnclick()"><h5>SIGN UP</h5></button>
</form>
Simply i'm trying to alert the proper message if the user new to fire success or if he registered to fire error, I tried to remove dataType:'text' or adding 'json' and\with removing crossDomain attribute as well but all didn't give me the reason.
In case this was useful, here is where I fire the AJAX script.
You call the JavaScript when you click on a submit button.
The JavaScript runs. The Ajax request is prepared. The JavaScript finishes. The submit button's default behaviour submits the form. The page unloads. The Ajax request is canceled. The regular form submission takes place.
Get rid of the onclick attribute. Bind your event handlers with JavaScript instead.
$(function () {
var $form = $([name="myform"]); // `name` is obsolete for form elements, give it an ID instead
$form.on('submit', onbtnclick);
function onbtnclick(event) { // Give this function a better name
event.preventDefault(); // Don't submit the form normally
// Then put the rest of your existing code
}
});

How to test for success and redirect web page after product added in opencart?

I'm using the following form to add a product to the opencart shopping cart. The problem I'm having is that after the product adds it doesn't redirect to the shopping cart but just shows a page with a product successfully added notification.
here's the form:
<form action="purchase/?route=checkout/cart/add" id="addToCartForm" method="post">
<input type="hidden" name="product_id" value="40">
<input type="hidden" name="quantity" id="quantity_field" value="">
<input type="hidden" name="price" value=>
<input type="submit" alt="Order Now" title="order now" value="Order Now test">
</form>
and the javascript code:
<script>
$(document).ready(function() {
$('form#addToCartForm input[type="submit"]').click(function(e) {
e.preventDefault(); // prevent the form from submitting
$.ajax({
type: 'POST',
dataType: 'json',
url: 'purchase/index.php?route=checkout/cart/add'
data: 'product_id=' + $('form#addToCartForm input[name="product_id"]').val() + '&quantity=' + $('form#addToCartForm input[name="quantity"]').val(),
success: function(json) {
window.location = 'purchase/index.php?route=checkout/cart';
console.log('add success');
}
});
});
});
</script>
after the form is clicked the page redirects to http://*****/purchase/?route=checkout/cart/add and the page message reads "{"success":"Success: You have added Product Name</a> to your shopping cart</a>!","total":"4 item(s) - \u00a64.40"}"
So, it does add a product, but the redirect upon 'success' doesn't seem to do anything.
the javascript console doesn't output anything with console.log('add success'); (or it moves to the shopping cart add page too quickly to see)
thanks for any help
First remove action attribute from form, its not required (and may cause confusion in debugging)
and then use following javascript
$('form#addToCartForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'purchase/index.php?route=checkout/cart/add'
data: 'product_id=' + $('form#addToCartForm input[name="product_id"]').val() + '&quantity=' + $('form#addToCartForm input[name="quantity"]').val(),
success: function (json) {
window.location = 'purchase/index.php?route=checkout/cart';
console.log('add success');
}
});
});
in your question part of your ajax requested is commented out, is it really the case or it just got commented while posting to SO ?
I'm not sure where the element with ID 'personalVirtualPrivateServerForm' is from, but clicking a button doesn't necessarily allow you to perform the e.preventDefault() you are attempting.
In your case, you are essentially saying, on click of the button perform an action, but you want to say something like:
$('form#addToCartForm').submit(function(e) {
e.preventDefault();
.... (rest of code here) ....
});
Basically, your form is submitting before you have a chance to redirect, when you want to stop the form submission and then send it via your $.ajax submit. That should allow your success callback to execute.

Categories

Resources