I'm trying to receive a POST request containing user-input form data using AJAX, but I keep returning errors. I'm following this tutorial almost verbatim.
Here's my code:
views.py
#app.route('/table_data', methods=['POST'])
def table_data():
user_id = request.form['userID']
name = request.form['name']
return user_id, name #of course I'll return something more meaningful in the future
datapage.html
<script type="text/javascript" src="app/static/js/submit.js"></script>
<form action="{{ url_for('table_data') }}" class="form-inline" method="post"
role="form" enctype="application/json">
<input type="text" class="form-control" id="userID" placeholder="4-Character ID">
<input type="text" class="form-control" id="name" placeholder="Name">
<button type='submit' class="btn btn-default">Submit</button>
</form>
submit.js
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data: {
userID: $('#userID').val(),
name: $('#name').val()
},
type: 'POST',
url: '/table_data'
})
event.preventDefault();
});
});
My console is returning "GET /app/static/js/submit.js HTTP/1.1" 404", even though I know that the route to submit.js is correct.
I'm brand new to JavaScript/jQuery. Any help for a rookie?
Moved solution from question to answer:
SOLUTION:
First, thanks to #reptilicus for the solution to the 404 error on the .js file (see comments). After that I was stuck with a "Bad Request" error message (400) in the browser window because my HTML input parameters did not include "name". I added name="userID" and name="name" to the tags in the HTML script, and it ran.
Related
I have a very simple form that has an input field for first name. I captured the form data and transmitted it via ajax to a PHP page using the standard jQuery posting method. However, I am not able at all get any responses from the PHP page that any data was captured on the server-side. I am not sure what I have done wrong or what is missing.
Here is my code.
Form:
<form action="process.php" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
<div class="d-none" id="firstName_feedback">
<p>Please enter a first name.</p>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Here is my Jquery Ajax call:
<script>
$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
console.log(formData);
$.ajax({
type: 'POST',
url: 'form.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
And here is my PHP page:
if(isset($_POST['formData']))
$ajaxData = ($_POST['formData']);
echo $ajaxData;
{
}
In your Ajax function, you're passing the contents of formData to the server, though not as formData but as their original input name.
In this case, you have:
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
The input's name is firstName, so you need to call $_POST['firstName'] instead of $_POST['formData'].
if (isset($_POST['firstName'])) {
$ajaxData = $_POST['firstName'];
echo $ajaxData;
}
The same applies for any other field you would have in your form, so for example, having another input with the name lastName means you'd have to call $_POST['lastName'] to access it.
There were also some misplaced brackets and parentheses in the PHP code which I accommodated above.
I have a problem when validating a form, the fields are correctly checked, but it return the current html source code instead of the value inside "ctrl.php", in other words the stuff inside the "success bloc" is done but I get nothing from "ctrl.php", just the current page in html is returned:(
Any idea ?
$("#form_contest").validate({
submitHandler: function(form){
var email=$("#email").val();
$.ajax({
url: "ctrl.php",
data:{name:$("#name").val(),email:email},
success: function(data){
alert(data); //data is the current source code??
//other stuff after is okay
}
});
return false;
}
});
the html form :
<form id="form_contest" method="post">
<input type="text" id="name" name="name" />
<input type="text" id="email" name="email" />
<input type="submit" id="submit-contest" name="submit-contest" value="Enter" />
</form>
ctrl.php :
<?php
echo 1;
?>
the page ctrl.php couldn't be reached and I had an nginx rule that redirected 404 error to the homepage. Not easy to find.. but that's why ajax always gave me the homepage source code..
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.");
}
});
});
});
I'm working on phonegap, basically its like making mobileapps crossplatform by using HTML, JS and CSS. On the device i currently have the JS and the HTML (form) in same document.
What I'm trying to do is to pass email and password to my server, and then process it there through a login. I've tested the login script on the server and it works with hardcoded data. So I'm guessing somewhere when sending the data from the device its failing.. I'm fairly new to JS too.
I tried to hardcode the data in the AJAX but it doesnt seem to work. Preferebly I would like to use something like var pdata = $('#form').serialize(); or something else if its better.
Any ideas?
EDIT: Forgot to say that the PHP on the server auto submits by using JS when $_POST is set (isset)
The form
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="email" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-primary">Logg inn</button>
</form>
The javascript
<script>
function dologin() {
//var pdata = $('#form').serialize();
//alert(pdata);
$.ajax({
type: 'POST',
data: {email:"test#test.no",password:"test"},
url: 'LINK',
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
};
</script>
The PHP
<form id="form" method="post">
<!-- {{ Form::label('email', 'Email Address') }} -->
<div class="form-group">
<input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST['email'];?>">
</div>
<div class="form-group">
<!-- {{ Form::label('password', 'Password') }} -->
<input type="text" name="password" value="<?php if(isset($_POST["password"])) echo $_POST['password'];?>">
</div>
</form>
Are you able to hit your server via through phonegap?
If no then please check your config.xml for white list urls - change access control property to
access origin = "*"
Hopeful you will be able to hit your server with data.
You can use weinre to debug your app. That way you will be able to see if the request was placed from the app or not.
http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html
I try writing code using JavaScript
The file sending technology AJAX
HTML code
<form action="" method="post" id="contact_form" enctype="multipart/form-data">
<input type="text" name="name" id="name">
<input type="text" name="email" id="email">
<input type="file" name="cv" id="cv">
<input type="submit" name="submit" id="contacts_send">
</form>
JavaScript code
jQuery(document).ready(function(){
jQuery("#contacts_send").click(function(){
$.ajax({
type : 'POST',
url : 'process_job.php',
dataType : 'json',
data: { cv : $('#cv').val()
name : $('#name').val(),
email : $('#email').val()},
success: function () {
alert("Data Uploaded: ");
}
});
})
})
I researched the internet I did not find a similar solution to my problem
I tried this solution but it did not work How can I upload files asynchronously?
i want my code do like this http://www.jainaewen.com/files/javascript/jquery/iframe-post-form.html
the issue that you might be having is that you are not getting the files as you should get and instead you are trying to just catch them as simple queryString objects.
Use this:
if ($_FILES["file"]["error"] > 0) {
And then run the code. It will work, since the code is going good!