I am using jQuery to send a request to my server and then render the results. However, now I want to use a button, so that the request would only be sent after clicking on the send button, not like my previous code where I used an "onkeyup" which is uncontrollable; because I want to send my request after finishing typing my request and not before.
<script>
function Search(query_text)
{
$.get( "http://localhost:9000?query="+query_text, function( data ) {
$(\"#div2\").empty()
..............
$(\"#div2\").append("</table>")
}, "json")
.fail(function() {
$("#rep")
.append('<br/><p style="color:red">Oops! Error with XMLHttpRequest</p>')
});
;
}
</script>
This is the input that calls the jQuery function:
<input id="queryText" type="text" onkeyup="Search($(this).val())" /><br>
I've tried to add a simple button and then call the jQuery function like this, but it didn't work because the page reloads and I don't get the results I need:
<form class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="queryText" placeholder="Your text">
</div>
<button type="submit" class="btn btn-primary" onclick="Search($('#queryText').val())">Find courses</button>
</form>
I don't know if there is a way to keep using GET requests instead of using a form and sending that time a POST request.
Thank you in advance!
Correct the id you are using its queryTexte and not queryText and instead of double quotes use single quotes in jQuery selector as shown :-
<button type="button" class="btn btn-primary" onclick="Search($('#queryTexte').val())">Search</button>
Instead of using type=submit button make it type=button as shown above.
I would do something like this to keep JS and HTML separated and avoid quote issues:
$("button").on("click", function(){
Search($("#queryTexte").val());
});
And if your script is loaded before the DOM element, wrap it like this to wait for the DOM to be ready:
$(function){
$("button").on("click", function(){
Search($("#queryTexte").val());
});
});
HTML:
<input id="queryTexte" type="text" /><br>
jQuery:
<script>
jQuery(document).ready(function($){
$('.btn-primary').click(function(){
var query_text = $('#queryTexte').val();
$.get( "http://localhost:9000?query="+query_text, function( data ) {
$('#div2').empty();
..............
$('#div2').append("</table>");
}, "json")
.fail(function() {
$("#rep")
.append('<br/><p style="color:red">Oops! Error with XMLHttpRequest</p>')
});
});
});
</script>
Related
I am wondering how to get 2 actions in PHP from a single Button.
Attached here is an screenshot of the page:
I have the following code:
For the Submit button
<form method='POST'>
<div class="form-group">
<input type="text" name="s_amount" style='width:20%;' required>
<input type="submit" class="btn btn-primary" name="submit" value="Submit" />
</div>
</form>
<?php
$s_amount = $_POST['s_amount'];
echo $s_amount;
?>
AND for the Submit Code button
<button id="submitcode"type="button" class="btn btn-default">Submit Code</button>
<pre><code id="output">.../...</code></pre>
When the Submit code is pressed, this executes the following script
<script>
$(document).ready(function(){
$("#submitcode").on("click", function(){
ocpu.seturl("https://public.opencpu.org/ocpu/library/base/R")
//arguments
var mysnippet = new ocpu.Snippet("V_CT="+$('[name="CT"]:radio:checked').val()+"\r V_TP="+$('[name="LENGTH"]:radio:checked').val()+$('#input2').val());
//perform the request
var req = ocpu.call("identity", {
"x" : mysnippet
}, function(session){
session.getObject(function(data) {
//data is the object returned by the R function
$("#output").text(data);
});
});
})
});
</script>
What I would like to have is a single button, which not only gets the value next to the first submit button (here 12, see attached pciture) but also executes the script.
Many thanks !
try giving id to form tag and on click on submitcode button call the form using its id.
for ex.
<form method='POST'>
function(session){
session.getObject(function(data) {
//data is the object returned by the R function
$("#output").text(data);
// using form id call the form
$("#formdata").submit(); // it will simply submit the form.
});
});
<form method="post" id="formdata"> <!--assign id to form tag-->
</form>
Could finally do it very easily using js.
<input type="text" id="VTP" value="0">
and get the value in the javascript form
document.getElementById("VTP").value
# nikhil borikar: Thanks but it did not work
I created custom form for fast reply (.append), now I want to use ajax for submit reply without reloading, I tried .on('submit', function(e)... which doesn't work (tried event delegation also). Now I tried .on('click', function(e)... and this works - don't know why.
$("#newpost").on('click', '.send', function(event) {
event.preventDefault();
});
This doesn't work:
$("#newpost").on('submit', '.send', function(event) {
event.preventDefault();
});
Appended form:
<form id="newpost" method="post" action="/forum/addpost/"+ id +"/"+ rek +" name="newpost">
<div class="editor" align="left">
<textarea name="post" cols="50" rows="5"></textarea>
<div class="submit" align="right">
<input class="send" value="." title="Send" type="submit">
</div>
</div>
</form>
So why .on('submit'..) doesn't work even if I use event delegation?
Thank you
This is not working because you have conflicting name to textarea(name="post") with the form properties.
As from jquery documentation:
jquery submit
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint.
If you append the whole form dynamically then you'll have to attach the submit listener to something that already exists when the page loads. Something like this:
$('body').on('submit', '#newpost', function(event) {
event.preventDefault();
});
EDIT:
I might have misread the question. The part you said doesn't work cant work because you don't submit a ".click" button, but the form that your ".click" button is in.
The right form is
$( "#newpost" ).submit(function( event ) {
event.preventDefault();
});
Later edit:
I understood now what you want.Try a new approach.Presuming that id is 23 and rek is value "add" you have the following:
HTML
<div class="editor" align="left">
<textarea name="post" cols="50" rows="5" id="post"></textarea>
<div class="submit" align="right">
<input class="send" value="." title="Send" type="button" id="23" data-rek="add">
</div>
</div>
JS ( can be used in external file also):
//get the answer based on id-s and classes
$("body").on("click", ".send", function() {
//get what is at attribute id of the clicked link
var ID=$(this).attr("id");
//get the text from the form with id "fasttext"
var thetext = $("#post").val();
//take the value of rek ( don't know what means :) )
var therek = $(this).attr("data-rek");
//create the string that will be posted
var theString = 'post=' + thetext;
//post the form using ajax and without reloading the page
$.ajax(
{
type: "POST",
url: "/forum/addpost/"+ id +"/"+ therek,
data: theString,
cache: false,
success: function(html)
{
//do what you want to do as success - html is the returning response
//you can also make this div disappear or display a success message
}
});
});
});
May be problem is here
<div class="submit" align="right">
<input class="send" value="." title="Send" type="submit">
try to remove class="submit" from div tag
<div align="right">
<input class="send" value="." title="Send" type="submit">
I've looked at several existing questions on here already. They're all for submitting post requests, but the mechanics should be the same for get requests, so I modified my code to work for get requests. But it's not working correctly.
What's wrong: I submit a form, but the page continues to reload (right now it's redirecting to a new page with the json data.
What I want to do: Submit a form, prevent it from reloading, and display the json data on the same html page
<div class="row">
<div class="col-md-3">
<form method="GET" action="/search">
<div class="form-group">
<input type="text" class="form-control" id="term" name="term" placeholder="Find">
<br>
<input type="text" class="form-control" id="location" name="location" placeholder="Near">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
<script>
$(function() {
$('form').submit(function(event) {
event.preventDefault();
var $this = $(this);
$.get($this.attr('action'), function(data) {
$('pre').text(data);
});
});
});
</script>
And in my express code, I have this:
app.get('/search', function(req, res) {
var apiUrl = getApiUrl(req.query);
var apiData = getApiData(apiUrl, function(statusCode, data) {
// console.log(data);
// res.render('api-guide', data);
res.send(data);
});
});
I should note, I'm using handlebars for templating. So the form is in its own template, while the jquery script is in the main template. Would this be why it's not working as expected?
Can someone please help me?
You are setting an action parameter in your form that is conflicting with your AJAX request. If you remove
action="/search"
and set the path directly in your AJAX request
$.get('/search', function(data) {
$('pre').text(data);
});
from your form declaration, it should work as you expect.
I would like to create a form with multiple submit link buttons. I know it can be done by using and specifying the name of <button> or <input type="button"> something like this:
In HTML:
<form action="" method="get">
Other form elements here...
<button type="submit" name="activated">Activated</button>
<button type="submit" name="pending">Pending</button>
<button type="submit" name="suspended">Suspended</button>
</form>
In PHP:
<?php
if(isset($_GET["activated"])) {
Activated codes here...
}
elseif(isset($_GET["pending"])) {
Pending codes here...
}
elseif(isset($_GET["suspended"])) {
Suspended codes here...
}
?>
I want the submit buttons to be done by using link, not <button> or <input type="submit"> something like this:
Activated
Pending
Suspended
I heard that it can be done by using JavaScript or JQuery but I don't know how, anyone knows?
Update: What I want to happen is when I clicked the "Activated" link for example, I want only to process the logic under isset($_GET["activated"]).
The reason behind:
The reason why I want to have a submit link buttons instead of normal submit button tags is that, I want to use this bootstrap dropdown button style to change the status of user(s) on table:
and it is based on links, so that's why.
PS: Sorry for bad English, not my native language.
You could use data attributes on your anchors, then load that attribute into a hidden field to check in your PHP code.
<form action="" method="post">
Activated
Pending
Suspended
<input type="hidden" id="actionName" name="actionName" value="" />
</form>
$('.anchor-btn').click(function(e) {
e.preventDefault();
$('#actionName').val($(this).data('name'));
$('form').submit();
});
<?php
if($_POST['actionName'] == "activated") {
Activated code goes here
}
...etc.
?>
Yes you can submit the form using jquery just add a class to your buttons and add a click handler
$(document).ready(function() {
$( ".buttons_class" ).click(function() {
$( "#target_form" ).submit();
});
});
so your buttons will look like this
<button type="button" name="activated" class="buttons_class">Activated</button>
<button type="button" name="pending" class="buttons_class">Pending</button>
<button type="button" name="suspended" class="buttons_class">Suspended</button>
if using anchors
Activated
Pending
Suspended
And in javascript
$(document).ready(function() {
$( ".buttons_class" ).click(function(e) {
e.preventDefault(); //This will stop the default anchor action
$("#target_form").attr("action", "yourphpfile.php?"+$(this).text()+"=true"); //This will send the text inside the anchor as a GET param.
$( "#target_form" ).submit();
});
});
However if I were you I would consider using POST instead of GET for this. and do something like this
$( ".buttons_class" ).click(function(e) {
e.preventDefault(); //This will stop the default anchor action
var paramName = $(this).text(); //get text inside anchor
$( "#target_form" ).submit(function(eventObj) {
$('<input />').attr('type', 'hidden')
.attr('name', paramName);
.attr('value', "something")
.appendTo('#form');
return true;
}); //Add hidden field
});
Change your isset to $_POST instead of $_GET, it will then use the name attributes.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['test1'])) {
###
} else if ($_POST['test2']) {
###
}
}
<form method="post">
<input name="test1" type="submit" value="TEST 1" />
<input name="test2" type="submit" value="TEST 2" />
</form>
sorry for the dumb question but I can't seem to get this going and I figured I best give you more info than not enough -
I have a form that I am running inside a loop in php like this:
<form name="primaryTagForm'.$post->ID.'" id="primaryTagForm'.$post->ID.'" method="POST" enctype="multipart/form-data" >
<fieldset class="tags">
<label for="post_tags'.$post->ID.'">Tags:</label>
<input type="text" value="" tabindex="35" name="postTags'.$post->ID.'" id="postTags'.$post->ID.'" />
</fieldset>
<fieldset>
<input type="hidden" name="submitted" id="submitted" value="true" />
'.wp_nonce_field( 'post_nonce', 'post_nonce_field' ).'
<button class="button" type="submit">Tag</button>
</fieldset>
</form>
I have tried adding my ajax under that form (Still within the loop so I can grab the post_id) and in my console it my tag-ajax.php file is posted just fine. Here is my weak attempt at that based on this: Save data through ajax jQuery post with form submit and other like questions.
<script>
jQuery(document).ready(function($) {
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "'.get_stylesheet_directory_uri().'/tags-ajax.php",
data: "primaryTagForm'.$post->ID.'",
success: function(data){
//alert("---"+data);
alert("Tags have been updated successfully.");
}
});
});
});
</script>
And lastly here is what is in my tags-ajax.php file -
if(isset($_POST['submitted']) && isset($_POST['post_nonce_field']) && wp_verify_nonce($_POST['post_nonce_field'], 'post_nonce')) {
wp_set_object_terms( $post->ID, explode( ',', $_POST['postTags'.$post->ID] ), 'product_tag', true );
echo'Success!';
}
So when I try running this a couple of things happen by looking in the console, if I hit submit on one of the forms then all them forms on that page post to tags-ajax.php (Im sure it is because I am doing this in a loop but not sure how else to do it and bring in post->ID on tags-ajax.php)
The second, most important thing is that nothing actually saves, I click the "Tag" but (submit) and I get those success alerts (for each post unfortunately) but when I click through those the tags are not actually saved.
My question: How do I get the data to actually save with the ajax/php and how can I have that post refresh without reloading the page so the user sees they actually were added?
Latest Update: After making the serialize edits mentioned below I submit my form and check the console and see the post method is getting a 500 internal server error.. Im thinking if my problem is coming from because I have the form and an inline script with the ajax running in a loop? So there are technically 20 posts/forms/inline scripts on a page and when you submit one, all of them submit which may be causing the 500 internal error?
The data: option in ajax should be
data: $("#primaryTagForm'.$post->ID.'").serialize(),
Use serialize
You have to change
data: "primaryTagForm'.$post->ID.'",
to
data: $("#primaryTagForm'.$post->ID.'").serialize(),
Simplify your markup. You dont have to use id attributes everywhere. Just include a hidenn tag in your form with the value of $post->id. Also echo the ajax url at the form's acton attribute.
So the html should be similar to this:
<form method="POST" action="' . get_stylesheet_directory_uri() .'/tags-ajax.php" >
<input type='hidden" name="id" value="'.$post->ID.'">
<fieldset class="tags">
<label>Tags:</label>
<input type="text" value="" tabindex="35" name="tags" />
</fieldset>
<fieldset>
<input type="hidden" name="submitted" id="submitted" value="true" />
'.wp_nonce_field( 'post_nonce', 'post_nonce_field' ).'
<button class="button" type="submit">Tag</button>
</fieldset>
</form>
Then you can use a script like this:
jQuery(document).ready(function($) {
$(".button").click(function(e) {
e.preventDefault();
var $target = $(e.target),
$form = $target.closest('form');
$.ajax({
type: "POST",
url: $form.prop('action'),
data: $form.serialize(),
success: function(data){
//alert("---"+data);
alert("Tags have been updated successfully.");
}
});
});
});