I'm trying to send a request and get answer from my own synonyms api. The api works very well. And the javascript is getting the answer, but it keeps refreshing the page and in the end there's no output in my html.
This is my html script:
<form method="POST">
<input type="text" class="question" />
<button class="gen-syn">Generate synonyms</button>
<input type="submit" value="Save"/>
</form>
And this is my javascript:
$(document).on('click','.gen-syn',function(){
var questionVal = $(".question").val();
if (questionVal == ''){
$(".question").focus();
}
else {
$.ajax({
type :'POST',
url : "http://192.168.1.9:5000/synonyme_word/"+questionVal,
success : function(response){
var divSynonymes = $(document.createElement('div'));
$(".question").after(divSynonymes);
for (var a in response){
$(divSynonymes).append('<h1 class="titre-textareal-question-icona-go " value=>'+a+'</h1>'+
'<div class="form-group row" >'+
'<div class="col-sm-12 listeSyn">'+
'</div>'+
'</div>'
);
for (syn in response[a]){
var synonyme = response[a][syn]
$(".listeSyn").append(
'<input type="checkbox" name="checkboxes[249]" id="frm-test-elm-110-100" autocomplete="off" />'+
'<div class="btn-group">'+
'<label for="frm-test-elm-110-100" class="btn btn-primary">'+
'<span class="fa fa-check-square-o fa-lg"></span>'+
'<span class="fa fa-square-o fa-lg"></span>'+
'<span class="content">'+synonyme+'</span>'+
'</label>'+
'</div>');
}
}
},
});
return False;
}
});
I didn't make any reload, but the navigator keeps reloading after calling the api (when I click on Generate synonyms button)
Get rid of the <form> altogether. Its behaviour messes with your code. Just use a <div>.
This should fix your issue.
<input type="text" class="question" />
<button class="gen-syn">Generate synonyms</button>
<input type="submit" value="Save"/>
you need only one button to make a API call and then your JS code is creating dynamic div and other elements to show the synonyms.
Hope this helps.
Related
I want to populate multiple forms with multiple buttons on PHP loop from mysql. For each entry, I have 3 buttons to be handled with the same ajax calls. The issue I'm facing is to recognize which button is clicked and added it to the form data to be sent for a PHP file
function() {
var form = $('#PayBillFormForm0'); // will be different for each PHP loop
var formMessages = $('#PayBillResults0'); // will be different for each PHP loop
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: "php/pay.php", // When pay0 button is clicked
url: "php/decline.php", // When decline0 button is clicked
data: formData
})
.done(function(response) {
var messageAlert = response.type;
var messageText = response.message;
var alertBox = '<div class="alert ' + messageAlert + '"style="margin-top:10px;"><d style="font-size:12px; ">' + messageText + '</d></div>';
(formMessages).html(alertBox);
$('#Bill0').delay(3000).fadeOut(2000); //Bill0 is different for each PHP loop
})
});
}
<div class="card" id="Bill0">
<div id="PayBillResults0"></div> <!-- To show Ajax Response Message -->
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body">
<form id="Form0" method="post" action="">
<input name="user" id="user" value="user" type="hidden">
<input name="id" id="id" value="9" type="hidden">
<input name="reciver" id="reciver" value="ppp" type="hidden">
<input name="amount" id="amount" value="333.0" type="hidden">
<input name="tax" id="tax" value="5.0" type="hidden">
<input name="comment" id="comment" value="XXX" type="hidden">
</form>
<div id="Buttons">
<div id="Pay">
<button form="" class="btn btn-success" id="pay0" value="pay0">Pay</button>
</div>
<div id="decline">
<button form="" class="btn btn-danger" id="decline0" value="decline0">Decline</button>
</div>
<div id="Hide">
<button form="" id="hide0" class="btn btn-warning" value="hide0">Hide</button>
</div>
</div>
</div>
</div>
I was able to perform this by labeling each form and labeling each button plus having multiple onclick functions as well as multiple jQuery codes. Any idea how to send clicked button value along with form data to PHP to handle differently.
When looping with PHP, you should NEVER use any id on elements. Use classes instead... Or some data attributes.
You were using unique ids by adding a number to them... Fine. But a class is more useful since you can add one event handler to a class... Instead of n event handlers for element created by the PHP iterations. So it avoid useless code duplication and just make sens.
That is what I suggest you now. Modify your PHP loop so it will create that HTML:
(I removed all that seemed useless)
<div class="card" data-id="0">
<div class="PayBillResults"></div> <!-- To show Ajax Response Message -->
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body">
<form>
<input name="user" value="user" type="hidden">
<input name="id" value="9" type="hidden">
<input name="reciver" value="ppp" type="hidden">
<input name="amount" value="333.0" type="hidden">
<input name="tax" value="5.0" type="hidden">
<input name="comment" value="XXX" type="hidden">
</form>
<div>
<div>
<button class="btn btn-success pay" value="pay">Pay</button>
</div>
<div>
<button class="btn btn-danger decline" value="decline">Decline</button>
</div>
<div>
<button class="btn btn-warning hide" value="hide">Hide</button>
</div>
</div>
</div>
</div>
See the data-id="0"? That is where you will have your form number using the PHP iteration counter.
Now here is the client-side script to use once (do not loop that):
$(document.ready(function(){
// Change the URL to use with Ajax on button click
var AjaxUrl = "";
$(".pay").on("click",function(){
AjaxUrl = "php/pay.php";
$(this).closest(".card").find("form").submit();
});
$(".decline").on("click",function(){
AjaxUrl = "php/decline.php";
$(this).closest(".card").find("form").submit();
});
// Form submit handler
$("form").submit(function(e) {
e.preventDefault();
var card = $(this).closest(".card");
var formData = $(this).serialize();
formData.append("formNumber",card.data("id"));
$.ajax({
type: 'POST',
url: AjaxUrl,
data: formData
})
.done(function(response) {
var messageAlert = response.type;
var messageText = response.message;
var alertBox = '<div class="alert ' + messageAlert + '"style="margin-top:10px;"><d style="font-size:12px; ">' + messageText + '</d></div>';
card.find(".PayBillResult").html(alertBox);
card.delay(3000).fadeOut(2000);
})
});
}); // End ready
So on .pay or .decline button click, the URL to use with the Ajax request is changed accordingly.
(I don't know the use of the third button)
Then the .closest() form submits. And from $(this), which is the <form>, you can find all the related elements you need.
Notice that the form number that is submitting is added to the formData.
You'll retreive it with $_POST['formNumber'].
I'm having problem using #click vue function inside an appended HTML element using a Vue component.
The component have two button to add and remove divs inside a container, as follow:
<div class="col-md-12">
<button class="btn btn-sm btn-warning" #click.prevent.stop="addQuestion()">Add Question</button>
<button class="btn btn-sm btn-danger" #click.prevent.stop="removeQuestion()" v-if="notRemovableQuestion">Remove Question</button>
</div>
addQuestion function is as follow:
addQuestion(){
var newQuestion = '<div class="questionBox col-md-12 f-left p-2 mt-2" style="border:2px solid blue;">' +
'<div class="col-md-11 f-left">' +
'<input type="text" class="form-control" name="domanda" placeholder="Question" v-model="domanda" />' +
'<input type="text" class="form-control" name="question_description" placeholder="Question Description" v-model="question_description" />' +
'<div class="form-check">' +
'<div class="newAnswerActions f-left full-width col-md-12 mb-2 mt-2">' +
'<a class="btn btn-sm btn-warning" #click.native="addAnswer()">Add Answer</a>' +
'<a class="btn btn-sm btn-danger" #click.native="removeAnswer()" v-if="notRemovableAnswer">Remove Answer</a>' +
'</div>' +
'<label class="form-check-label">' +
'<input class="form-check-input" type="radio" name="risposte" id="exampleRadios1" value="">' +
'<input type="text" class="form-control" name="answer" placeholder="Risposta" />' +
'</label>' +
'</div>' +
'</div>' +
'<div class="col-md-1 f-left">' +
'<button class="btn btn-sm btn-success" #click.prevent.stop="removeQuestion()">SAVE</button>' +
'</div>' +
'</div>';
$(".allQuestionContainer").append(newQuestion); }
The new container is successfully appended but the two buttons for Add Answer and Remove Answer, calling #click.native="addAnswer()" and #click.native="removeAnswer()" are not working. I've tried with or without native and anything else, also with js onClick but no luck, the function is never reached and the click event it's not working.
What I'm doing wrong? Any suggestions?
Thanks!
I would avoid the course you are taking and make use of components instead.
Rather than appending HTML to a div, you could create a component which contains the HTML you're currently assigning to newQuestion. That component would then be responsible for dealing with the addQuestion and removeQuestion methods and because it's a component registered with Vue, it'll automatically be reactive.
Once the component is registered you can control whether it's shown by doing something like:
<new-question v-if="showNewQuestion"></new-question>
Then within your addQuestion method you just set this.showNewQuestion = true so that the component will show. showNewQuestion would obviously need to be declared within your data prop and defaulted to false.
I've not gone into great detail about the formation of the component as I don't know if your using vue-loader or not but more information can be found on the Vue Docs Site.
Hi i currently have a document where i need to send data off via either email(which i am using php mailer) or sql. which is all pretty well sorted.
my only question is. as i am using append to generate a set of variables. how would i use pull all this user generated data to then send a json file.
below is the current code i have.
<div align="center" class="addsection"></div>
<button align="center" id="addbutton" class="btn btn-default">Add a product</button>
<button id="submitbutton" class="btn btn-default" onclick="sbmitbtn()">Submit</button>
<script>$('#addbutton').on('click', function () {
var count = $('div.addsection div').length, id = count + 1;
var large = '<p class="accordian_container">
<hr/>
<p class="accordian_item" id="accord_item_2">
<label> First Name</label><br/>
<input type="text"/><br/>
<label>Middle Name</label><br/>
<input type="text"/><br/>
<label>Last Name</label><br/>
<input type="text" /><br/>
<label>Home Number</label><br/>
<input type="text"/><br>
<label>Work Number</label><br/>
<input type="text"/><br>
<label>Cell Number</label><br/>
<input type="text"/><br>
</p>
</p>';
$('div.addsection').append('<div class="contentprint" id="product' + id + '">' +
'<h4>Product: ' + id + '</h4> <table class="selection1"></table>content goes here</div>');
$('div.addsection').append(large);
event.preventDefault();
});
$('#submitbutton').on('click', function () {
}
as you can tell i have a button to generate content. with a div to put that content in. now i need to figure out how to use that data that was created from the textboxes to send off via json. is this possible. any help would be awesome. do i need to move large within the append and make each items id have the id of the overall div. and if so is it as simple as running a for loop until all divs with ids have been passed.
can this json type array be done in php if it were on a php page. its a little confusing to get my head around so any help is greatly appreciated.
I have been trying to follow the example here to add a dynamic field that is created upon a button click example and have been unable to get it to work.
Here is my javascript file, which I am storing in my static file directory(other static files load fine, filename is 'recipeadd.js'):
$(document).ready(function(){
var next = 1;
$("#b1").click(function(e){
alert("Hi");
e.preventDefault();
var addto = "#field" + next;
var addRemove = "#field" + (next);
next = next + 1;
var newIn = '<input autocomplete="off" class="form-control" id="field' + next + '" name="field' + next + '" type="text">';
var newInput = $(newIn);
var removeBtn = '<button id="remove' + (next - 1) + '" class="btn btn- danger remove-me" >-</button></div><div id="field">';
var removeButton = $(removeBtn);
$(addto).after(newInput);
$(addRemove).after(removeButton);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
$("#remove").click(function(e){
e.preventDefault();
var fieldNum = this.id.charAt(this.id.length-1);
var fieldID = "#field" + fieldNum;
$(this).remove();
$(fieldID).remove();
});
});
});
Here is what's in my html header, loading both the js and associated css file:
<!--CSS code for recipeadd-->
<link href="{% static 'recipes/css/recipeadd.css' %}" rel="stylesheet">
<!--JS code for reccipeadd-->
<script src="{% static 'recipes/js/recipeadd.js' %}"></script>
Finally, here is the container that contains button 'b1', which I'm trying to have execute the javascript:
<div class="container">
<div class="form-group">
<!--div class="col-xs-4"-->
<label for="recipeName">Recipe Name</label>
<input type="text" class="form-control" id="recipeName">
</div>
<div class="form-group">
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1">Ingredients</label>
<div class="controls" id="profs">
<form class="input-append">
<div id="field"><input autocomplete="off" class="form-control" id="field1" name="prof1" type="text" placeholder="Enter one ingredient per line" data-items="8"/><button id="b1" class="btn add-more" type="button">+</button></div>
</form>
</div>
</div>
</div>
<div class="form-group">
<label for="directions">Directions</label>
<textarea class="form-control" rows="5" id="directions"></textarea>
</div>
I am teaching myself web development and using the Django framework for this project. Sincerely appreciate any help on this.
First I am assuming you have jQuery on the page, your code is not showing a jQuery reference.
Now assuming that the code adds the elements, I see one issue with adding your click event. You give the remove button the id with a number: id="remove' + (next - 1) + '"
Now when you attach the event, you do not use a number: $("#remove").click(
So either you need to use a number OR better yet, you already have the button element referenced, use that.
removeButton.click( function(){ });
Well as I mentioned I am just learning. I did not have a jQuery reference in my html file. I assumed as long as I had the javascript file reference that was good enough. I downloaded jQuery and added the following reference, working now - thank you!
<!--jQuery core code-->
<script src="{% static 'recipes/js/jquery-3.1.0.min.js' %}"></script>
The form begins:
<% using (Html.BeginForm("Index", "recordssbook", FormMethod.Post, new { id = "SubmitForm" }))
{ %>
The submit button I would like to validate (there are other submit buttons in the same form):
<div><input type="submit" value="Delete Selected" id ="DeleteButton" name="DeleteButton" onclick="deleteRecordsDialog();"/></div>
The buttons in my confirm dialog in js that automatically returns false:
function deleteRecordsDialog() {
var returnThis;
var numRecords = selectedRecordsArr.length;
document.getElementById("popupContainer");
var html = ""
html= html + '<table>';
html= html + '<tr>';
html= html + '<td class="warning-icon-cell"></td>';
html= html + '<td style="padding-left: 5px;">';
if (numAddresses == 1) {
html = html + '<p>You have chosen to delete a record.</p>';
}
else {
html = html + '<p>You have chosen to delete ' + numRecords + ' records.</p>';
}
html= html + '<p>Are you sure you wish to proceed?</p>';
html= html + '</td>';
html= html + '</tr>';
html = html + '</table>';
if (numAddresses == 1) {
html = html + '<div><input type="button" value="Yes, Delete Contact" style="width: 160px; onclick="document.DSubmitForm.HDeleteButton.submit(); CloseDialog();"/> <input type="button" value="Cancel" onclick="CloseDialog();"/></div>';
}
else {
html = html + '<div><input type="submit" value="Yes, Delete Contact(s)" style="width: 160px; onclick="document.DSubmitForm.HDeleteButton.submit(); CloseDialog();"/> <input type="button" value="Cancel" onclick="CloseDialog();"/></div>';
}
html = html + '</div>';
html = html + '</div>';
html = html + '</div>';
html = html + '</div>';
OpenDialog(html, 350, 180, false, "Delete Contact")
return false;
}
My issues:
Even with onclick returning false the form is submitted:
I can change the input type to button instead of submit, and this should work if I can get the psuedo submit to work
is _doPostBack another way to submit the form?: From my google searches I think this should simulate the submit but when I make the submit button a regular button as stated in number 1 clicking "Yes, Delete Record(s)" doesn't submit the form.
I have multiple submit buttons which makes this more complex
I cannot use JQuery's easy .dialog
If someone can help me out in getting this to work I would GREATLY appreciate it!
Thanks!!
EDIT
So the html a list of records with buttons that can query based on letter, add a record, delete a record and edit a record. All of these buttons are submit buttons in the same form.
<td><input type="submit" value="ABC" name="SubmitButton"/></td>
<td><input type="submit" value="DEF" name="SubmitButton" /></td>
<td><input type="submit" value="GHI" name="SubmitButton" /></td>
<td><input type="submit" value="JKL" name="SubmitButton"/></td>
<td><input type="submit" value="MNO" name="SubmitButton"/></td>
<td><input type="submit" value="PQRS" name="SubmitButton" /></td>
<td><input type="submit" value="TUV" name="SubmitButton"/></td>
<td><input type="submit" value="WXYZ" name="SubmitButton" /></td>
<div><input type="button" value="Add Contact" id="addAddress" onclick="AddAddresDialog()" /></div>
<div><input type="button" value="View & Edit Selected" id="EditButton" name="EditButton" onclick="updateAddressDialog()"/></div>
<div><input type="submit" value="Delete Selected" id ="DeleteButton" name="SubmitButton" /></div>
I only want to add the confirm dialog to the delete button being clicked. I want to confirm it using a custom dialog window which is a div on the site master that appears as a pop up by being placed on top of a mask that covers the whole screen which is created in deleteRecordsDialog().
What I want to do is change the submit button for the delete task (id="DeleteButton) to a regular button that just opens the dialog created by deleteRecordsDialog() instead of the form submission it does now. The "Yes, Delete Contact(s)" button in the custom confirm dialog should take on that task of submitting the form with the value "Delete Selected" just as the submit button does now.
It is hard to really understand what you are trying to do without your html. However, you can try out the following:
HTML:
<div>
<input type="submit" value="Delete Selected" id ="DeleteButton" name="DeleteButton" onclick="deleteRecordsDialog();"/>
<input type="button" id ="DeleteButtonSubmit" name="DeleteButtonSubmit" style="display:none;" />
</div>
Javscript:
To create button for modal:
html = html + '<div><input type="button" value="Yes, Delete Contact(s)" style="width: 160px; onclick="deleteContact();"/> <input type="button" value="Cancel" onclick="CloseDialog();"/></div>';
Function to post the delete confirmation:
function deleteContact()
{
document.getElementById('DeleteButtonSubmit').click();
}
This function will click a hidden button below the button the user initially clicked. if you setup this button correctly, the form should submit with all of the information you need.