Cant figure out why my button wont work that is for the ajax response. Trying to get it to print out the name of one of the people from the form upon pressing the button id AJAX button. Is there something i am overlooking because no matter what I place in the success portion nothing happens.
<div class="formContainer" id="container">
<form class="form-horizontail form" role="form"
action="/process-form" method="post">
<input type="hidden" name="csrf" value="{{csrf}}">
<div class ="form-group">
<label for="fieldName" class="col-sm-2 control-label" >Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="fieldName" name="name1">
</div>
</div>
<div class ="form-group">
<label for="fieldName" class="col-sm-2 control-label" >phone number</label>
<div class="col-sm-4">
<input type="tel" class="form-control" id="fieldPhone" name="phoneNumber1">
</div>
</div>
<div class ="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class=" btn btn-default" id = "list">List</button>
</div>
</div>
</form>
</div>
<button type="button" id="AJAX-Button"> Draw</button>
{{#section 'jquery'}}
</script>
<script>
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max)) +1;
}
$(document).ready(function () {
$("#AJAX-Button").on('click', function (event) {
//event.preventDefault();
var winner = "name" + getRandomInt(3);
var formData = { 'name': $('input[name= \winner]').val() };
var jsonData = JSON.stringify(formData);
console.log(formData);
console.log(jsonData);
console.log(winner);
var $container = $('#container');
$.ajax({
url: "/process-form",
type: 'POST',
data: jsonData,
success: function (data) {
alert(winner);
},
error: function () {
alert("failed");
}
});
});
});
EDITED: fixed the code thanks
2
Answers
The error seems to be that you are not separating the two
<script>
instructions. Use one for<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
and then open a new one for your code<script></script>
like this:Note: If you are using HTML5 you don’t need to specify
type="text/javascript"
in the script tag. See this answer for more info: Is type attribute necessary inside script tag.Place you javascript code outside the cdn link.Like this