I have a form in which currently posts to a hard coded php page in the action of the form, this works fine, it posts to the DB no problem, but where things get tricky for me is I don't want to post to a new page so I have opted to use ajax. So I got rid of the action field from the form and put in some jquery to make an ajax call. the issues I am having is well..it doesn't work :D. Could someone take a look at my js file and explain to me what I am doing wrong or what I should do?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<form>
<p>Comment</p>
<textarea name= "comment" rows="6" cols="50"></textarea><br />
<input type="submit" name= "submit" value="submit" id = "submit">
</form>
$('#submit').on('click',function(){
$.ajax({
type : 'POST',
url : 'comment.php',
data : formData,
dataType : 'json',
})
});
You should handle the 'submit' event of the form over the 'click' event of the submit button. You should also return false; at the end of function to prevent the form from posting to a new page. You are handling the submit yourself. Also I would put the action attribute back on the form element for the rare occasion that JavaScript is disabled on the client. Give the form an id and target that. Your code is correct otherwise.
HTML
<form id="my-form" action="comment.php" method="post">
<!-- input fields -->
</form>
JavaScript
$('#my-form').on('submit', function(){
// code...
return false;
});
Providing the action attribute, as well as the method attribute, on the form element will make these available to access in your submit handler as well as providing a proper fallback for any JavaScript failures. That may not be necessary for this instance but may be helpful in the future.
Your handler could now look something like this:
JavaScript
$('#my-form').on('submit', function(){
// serialize the form
var formData = $(this).serialize();
$.ajax({
type : this.method,
url : this.action,
data : formData,
dataType : 'json'
})
.done(function (data) {
// do some stuff with 'data'
})
.fail(function (error) {
// do some stuff with 'error'
});
return false;
});
Related
I want to use another page of my site to validate HTML form input. If the input is NOT valid, I want to show an error somewhere on my form page without reloading. And otherwise, if it IS valid, I want to submit the form normally.
After reading similar SO questions, I didn't found any exact solution, but actually invented my own, which works for me. Though, I still think that my solution is a bit weird, so I'm asking for proper ideas.
HTML:
<form id="form" method="POST"> ... some inputs ... </form>
<button id="submit" type="submit">Save</button>
<p id="errors"></p>
JS:
$('#form').submit(function (event) {
var formData = $(this).serializeArray();
event.preventDefault();
$.ajax({
type: "POST",
url: '/validate/',
data: formData,
success: function(data) {
if(!data)
{
$('#form').unbind('submit');
$('#submit').trigger('click');
}
else
{
$('#errors').text(data);
}
}
});
return false;
});
NB: It works as expected, I'm asking for better solutions.
I need help on something that sounds easy but is difficult for me.
So when someone clicks on this div:
<div onclick="<go to url sending data using the post method>">Click Me</div>
I want it to send data to a PHP file that will take the information that i want it to. I would use the GET function but I have heard that its easily hackable. If their is a lot simpler solution or something more secure please help me out.
If you need to use div you can do it like this but I suggest that you use button or input of type submit.
<form id="form-id" method="post" action="your-php-file-url">
<input type="hidden" name="your-variable-name" value="your-variable-value">
<div onclick="document.getElementById('form-id').submit();">Click Me</div>
</form>
Also you may use jQuery or some other JS library.
NOTE: Keep in mind that if the data that you send is provided via browser it's really easy to manipulate (doesn't mater if you use POST or GET) so it's important to check it out when you process it.
Using form would be ideal. If for some reason if you don't want to use form or want to build a dynamic app then use it in this way.
//jquery library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="someInput">
<div onclick="sendData()">Click Me</div>
<script>
function sendData(){
//get the input value
$someInput = $('#someInput').val();
$.ajax({
//the url to send the data to
url: "ajax/url.ajax.php",
//the data to send to
data: {someInput : $someInput},
//type. for eg: GET, POST
type: "POST",
//datatype expected to get in reply form server
dataType: "json",
//on success
success: function(data){
//do something after something is recieved from php
},
//on error
error: function(){
//bad request
}
});
}
</script>
You can use <form> to send data
<form action="yourpage.php" method="post">
//form contents
<input type="submit" value="Submit">
</form>
The action URL specifies the URL of the page to which your data has to be send.
I'm developing a webpage which creates a form with various select tags dynamically. Unfortenatley the jquery submit function passes incorrect information to the php file (form_submit.php) that must process this information; the (netbeans 7.4) debugger always shows default (not selected) values in $_POST within the php file instead of the selected values . The even stranger part: when I copy (in the code below) the console output with the serialised formdata straight into the following ajaxcode (see code), the php debugger shows the correct -selected values within the $_POST array..(?)
The resulting form is quite substantial. The only theoretical cause I can think of is that therefore the execution of 'var dataAjax = $( this ).serialize();' takes time and is not finished when the following ajax call starts...(??)
The code:
$("#myForm").submit(function(event){
event.preventDefault();
var dataAjax = $( this ).serialize(); //does not work, but when copying the string from the console in line below it does work.
console.log('SUBMITTED FORM: '+ dataAjax );
//next line is only used as a test
//var dataAjax = 'agreementapproval0=SolarX_10&selected_emeterproductid0=SolarX_10_1_1&selected_eproductid0=SolarX_10_2_4&selected_emeterproductid1=NOSELECTION&selected_emeterproductid2=NOSELECTION&selected_eproductid1=NOSELECTION&selected_eproductid2=NOSELECTION&form_token=30688e467ee88167805ad0f330809d74';
$.ajax({
type: "POST",
url: "form_submit.php",
data: dataAjax,
dataType: "json",
async: true,
success: function(msg){
if(msg.statusgeneral == 'success'){
}
else
{
}//else
}, //succes: function
error: function(){
$("#errorbox").html("There was an error submitting the form. Please try again.");
}
});//.ajax
//make sure the form doesn't post
//return false; //depreciated
//} //if(form.valid()
});//$("#myForm").submit()
<form id="myForm" name="myForm" action="" method="post">
<div id="wrapper"></div> <!--anchor point for adding set of product form fields -->
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
<input type="submit" name="submitForm" value="Confirm">
</form>
It works fine http://jsfiddle.net/a9DN4/
You might have been trying to hook form before it have been created, try to wrap your code with
$( document ).ready(function() {
// Handler for .ready() called.
});
PS and move event.preventDefault(); to the 1st string of your function, as Kevin says.
I have an HTML page with one button, and I need to execute a python script when we click on the button and return to the same HTML page with the result.
So I need do some validation on return value and perform some action.
Here is my code:
HTML:
<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue"></button>
JS:
function validate(){
if (returnvalue=="test") alert(test)
else alert ("unsuccessful")
}
What my python code is doing is some validation on the name entered in the text box and gives the return status.
But I need the result back on the same page, so I can do the form submission later with all the details. Any help will be appreciated
You can use Ajax, which is easier with jQuery
$.ajax({
url: "/path/to/your/script",
success: function(response) {
// here you do whatever you want with the response variable
}
});
and you should read the jQuery.ajax page since it has too many options.
Make a page(or a service) in python, which can accept post or get request and process the info and return back a response. It is better if the response is in json format. Then you can use this code to make a call on the button click.
<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue">
<script>
$('#id').click(function(){
$.ajax({
type:'get',
url:<YOUR SERVERSIDE PAGE URL>,
cache:false,
data:<if any arguments>,
async:asynchronous,
dataType:json, //if you want json
success: function(data) {
<put your custom validation here using the response from data structure >
},
error: function(request, status, error) {
<put your custom code here to handle the call failure>
}
});
});
</script>
I hope this helps
I have a form that I want to check if the userID is already used and then display the answer to the user before submitting the form. I found a way to do it through another site, but the code comes back with e.nodename is undefined. I am using jQuery 1.6. Any thoughts on how to do this? I am very new to jQuery. Thanks.
I would do a
$.getJSON("http://host.com/?action=isUserIDavailable&userid=" + userid, function(){});
to check if the userid is available before you submit the form
lets assume that your submit button is something like this
<input type="submit" id="submit-button" name="submit" value="submit"/>
you need to send an ajax request to the server with the userID i guess your userID is something like a select menu
<select id="user-id" name="user-id">
<option value="1">xx</option>
....etc
</select>
your javascript code will be something like that
$(function(){
$('#submit-button').click(function(e){
e.preventDefault(); // to prevent posting the form
//now sending ajax call to the server to check if the userID is valid
$.ajax({
url: 'ajax.php',
data: {'userID':$('#user-id').val()}
success: function(data) {
if(data == "OK"){
//the id is value
//you can post the form by using $('#form-id').submit();
}else{
//the id is n't valid
}
}
});
});
});