Alert message in browser using Ajax based on Node JS response - javascript

I developed a simple form where a user can enter an author name. The name will be queried using Node JS in the database to check if there are tweets written by this author or not. If there is no data, I want to response to the client using Ajax by showing an alert.
This is the client side:
<html>
<head>
<script>
$(document).ready(function() {
$.ajax({
error: function(error){
if(error.responseText == 'showAlert'){
alert("Please enter correct user name and password.");
}
}
});
});
</script>
</head>
<body>
<form action="/process_post" method="POST">
<select name="SearchTypes">
<option value="Author" selected>Author</option>
<option value="Mention">Mention</option>
<option value="Tag">Tag</option>
</select>
<input type="text" name="term">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
This is the part of the Node JS that includes the response:
var query = connection.query(queryString, [term,term], function(err, rows) {
console.log(rows);
var tweet = JSON.parse(JSON.stringify(rows));
if (tweet.length == 0){
res.status(500).send('showAlert');
}else{
for(var i in tweet){
res.write("Author: ");
......
As you see, I used res.status(500).send('showAlert'); to send the response to the client side but what really happens is that when I provide an input that does not have any data in the database (tweet length is zero), it just prints showAlert in the HTML page.

That's because the above JavaScript runs the control only if there is an error, but your message is sent as a correct response. You should change your client code to check in case of success, like this:
$(document).ready(function() {
$.ajax({
error: function(error){
if(error.responseText == 'showAlert'){
alert("Please enter correct user name and password.");
success: function(result){
if (result.responseText == 'showAlert'){
alert("There was an error")
}else{
//Do things...
}
}
}
}
});
});

You want to wrap the ajax call in a form submit handler. Right now, when you submit the form, it is doing a full synchronous request and coming back with the text "showAlert".
$(document).ready(function() {
$('form').on('submit', function (e) {
// keep the form from submitting synchronously
e.preventDefault();
var $form = $(e.currentTarget);
// submit via ajax
$.ajax({
url: $form.attr('action'),
method: $form.attr('method'),
data: $form.serialize()
})
.done(function (response) {
console.log('done: ', arguments);
})
.fail(function(error){
console.log('failed: ', arguments);
if(error.responseText == 'showAlert'){
alert("Please enter correct user name and password.");
}
})
});
});
Remove those calls to console.log once you have it working as you need. See $.ajax for options in that call.
You will probably also want to give your form an id and then refer to it that way, e.g. $('#myForm'), so that you can add more forms to the page without causing any problems.

Related

jQuery / ajax data container + organization

My dad and I are working on a project where we'd like to create a script that calls in data when a number is submitted into a form. For example, when you type in your ID number then press ENTER or SUBMIT, the form will print/display information. This is a project for school, so when a student submits their ID number it will read their first period class, for example.
I have the following script code to set up the form:
<form id="firstPeriod" action="firstPeriod.html">
<p>Find your first period.</p>
<p><label>Student no.: <input type="text" name="studentNo"></label></p>
<p><input type="submit" value="Find it"></p>
<p id="result"></p>
</form>
<script type="text/javascript">
$(function() {
$('#firstPeriod').submit(function() {
$.ajax({ // Send the request behind the scenes
url: $(this).attr('action'), // Send it here
data: $(this).serialize(), // With this student no.
success: function(data) {
$('#result').html(data); // Display the resulting HTML
},
error: function(jqxhr, status, error) {
console.log(error);
$('#result').html('No results found. Please check your number and reenter'); // Notify an error
}
});
return false; // Prevent the normal form submission
});
});
My question is, what would be the best way to organize the data? An array, HTML, etc.? There are quite a lot of ID numbers and are currently set up in an HTML table, but that doesn't seem to work in calling the information. And I'd like for the data to be specific. So when a specific ID number is typed in, it reads a specific answer. Right now my problem is when I type in a number it reads several classes.
If there are any suggestions/advice/other posts that could help me, I'd be grateful. I have solid HTML, CSS experience but I'm still learning JS and jQuery so this is a little new for me. Thanks!
Edit, Updated
Note, added value attribute to input type="text" element
<input type="text" name="studentNo" value="" />
substituted .submit() for .on("click") at input type="submit" element
Two possible approaches could be 1) using HTML to store data, .load() to retrieve fragment identifier within html file; or 2) storing data using JSON, retrieving file using php
html at firstPeriod.html
<div id="0">data 0</div><div id="1">data 1</div>
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$("#result").load(form.attr("action") +" #"+ id)
})
})
plnkr http://plnkr.co/edit/4onHf9jlJTyDei1zo9IC?p=preview
JSON
0.json
{
"0":"<div id='0'>data 0</div>"
}
1.json
{
"1":"<div id='1'>data 1</div>"
}
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$.post("data.php", {id:id}, function(result) {
$("#result").html(result[id])
}, "json")
})
})
php
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
$file = $id . ".json";
if (file_exists($file)) {
$jsondata = file_get_contents($file);
$id_data = json_decode($jsondata, true);
echo json_encode($id_data);
};
}

AJAX button not submitting and not going through

I'm having an issue where my Ajax code doesn't go through .. As if the functions is empty.
I clicked submit , nothing happens ..
My HTML code :
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<body>
<form method="POST" id="contactForm" >
<input type="text" name="email" id="email"></input>
<input type="submit" name="submit"></input>
</form>
<script type="text/javascript">
$('#contactForm').submit(function(e){
e.preventDefault();
var email = $('#email').val();
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'check.php',
data: {email: email},
success: function(data){
if(data.status == 'success') {
alert('The e-mail address entered is correct.');
} else {
alert('The e-mail address entered is Incorrect.');
}
}
});
});
</script>
</body>
</head>
My check.php:
<?php
if (isset($_POST['email'])) {
$status = 'success'
} else {
$status = 'failed';
}
echo json_encode(array('status' => $status));
?>
When i click submit , it just do nothing..
i want the error to pop up.
Is there anything i missed?
Make sure that all the options you're passing into the ajax call are properly cased. Example: datatype needs to become dataType, and beforesend needs to become beforeSend.
Here is the reference: http://api.jquery.com/jquery.ajax/
The brackets are misplaced and you are missing a : for "success" callback. See fixed code below,
And the case too as mentioned in the other answer here..
$('#contactForm').submit(function () {
var email = $('#email').val();
$.ajax({
type: 'GET',
dataType: 'json',
url: 'check.php',
beforeSend: function () {},
// v--- missing :
success: function (data) {
if (data.status == 'success') {
alert('The e-mail address entered is correct.');
} else if (data.status !== 'success') {
alert('The e-mail address entered is wrong.');
}
} // this was misplaced in the line below in your code
}); // this was misplaced in the line above in your code
});
Try to debug using the dev tools of Firefox or Chrome.
On Chrome's DevTools for example:
Debug Javascript with the source option. Or you cold add some console.log() inside your .submit() function to make sure that the event handler is triggering.
Use the network tab to make sure the ajax call is being made and check which response you get from server.
Last but not less important, check the console tab for Javascript errors to see if another script throws an error before the excecution of your script.
With these techniques, you can identify what could be wrong and see how could could solve it.

Call php in HTML form on action but don't redirect

I have an HTML form as follows:
<form id="ContactForm" name="ContactForm" method="post" action="emailinfo.php">
and then a submit button that calls verify():
Send
verify is defined as such:
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
document.getElementById('ContactForm').submit();
}
}
Currently, when I click the submit button, the browser redirects to emailinfo.php, which is just a blank white screen because that php file just sends off an email and does nothing else. How can I run that php file without redirecting to it?
What you want to do is use AJAX to send a request to the emailinfo.php file when the button is clicked. Making the form action blank will cause the form to post to the same page you're on.
If you're using jQuery, it's pretty easy to submit the form via ajax:
$(document).ready( function() {
$('.button1').click(function(){
var f = $('#ContactForm');
$.ajax({
type: "POST",
url: "emailinfo.php",
data: f.serialize()
});
});
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
//document.getElementById('ContactForm').submit();
var name=$('#name').val();
var email=$('#email').val();
var formData = "name="+name+"&email="+email;
$.ajax({
url : "emailinfo.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
//data - response from server
alert(data);
},
});
}
}
</script>
<form id="ContactForm" name="ContactForm" method="post" action="">
<input type="text" name="name" id="name"/>
<input type="text" name="email" id="email"/>
Send
</form>
ContactFormFirst change that a tag to a button, then assign that verify() to its onclick. then in verify(). use ajax to post the values from your form to emailinfo.php.
u can use
$.post(
"emailinfo.php",
$( "#ContactForm" ).serialize(),
function( data ) {
/* do things with responce */
} );
What I usually do in this scenario is ajax, but if you do not want to use ajax, you can simply add 'return false' for it not to be redirected when using form submit:
function verify()
{
if(document.getElementById("name").value=="" ||document.getElementById("email").value=="")
{
alert("Please enter a name and an email.");
}
else
{
alert("Looks good, sending email");
document.getElementById('ContactForm').submit();
return false;
}
}

in ajax form do validation and show a hidden div

I have this function(to make my form work with ajax):
$(function() {
$('#restore_form').ajaxForm({
beforeSubmit: ShowRequest,
success: SubmitSuccesful,
error: AjaxError
});
});
function ShowRequest(formData, jqForm, options) {
var queryString = $.param(formData);
alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
return true;
}
function AjaxError() {
alert("An AJAX error occured.");
}
function SubmitSuccesful(responseText, statusText) {
alert("SuccesMethod:\n\n" + responseText);
}
my form(django form) only contains a file upload field. i want also check validation and i have this function for this purpose:
function TestFileType( fileName, fileTypes ) {
if (!fileName) {
alert("please enter a file");
return false;
}
dots = fileName.split(".")
fileType = "." + dots[dots.length-1];
if(fileTypes.join(".").indexOf(fileType) != -1){
alert('That file is OK!') ;
return true;
}
else
{
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
return false;
}
}
now when i try to use validation function(TestFileType) in the first function, it doesn't work. both of them works seperately. fore example if i write the below line in onclick of submit button, it works:
onclick="TestFileType(this.form.file.value, ['tar.gz']);"
I also want instead of alerting user, show a hidden div in success function:
i have:
and i want in success function do:
$('.response').html(responseText);
$('.response').show();
EDIT:
Here is my template:
<form id="restore_form" enctype="multipart/form-data" method="POST" action="restore/">
{{ form.non_field_errors }}
{{ form.as_p }}
{{ form.file.errors }}
<p id="sendwrapper"><input type="submit" value="{% trans "Send" %}" id="submitButton" style="margin-bottom:10px; cursor:pointer; background-color:#F90;"/></p>
</form>
<div class="response" style="display: none;"></div>
but it doesn't work! it seems only alert works in this function. Can you please help me?
really thanks :)
I've attempted to use the AjaxForm plugin in the past and found that unless you have a very specific reason to use it, it's typically easier to write the ajax form submit code without the plugin. This is a simplified/commented version of a previous jquery ajaxform that I created using Jquery without the plugin:
$('form').submit(function(event) {
var form = $(this);
// creates a javascript object of the form data
// which can be used to validate form data
var formArray = form.serializeArray();
// (validate whatever values in formArray you need to check here);
if (form_is_valid) {
var formData = form.serialize(); // a URL-encoded version of the form data for the ajax submission
$.ajax({
type: "POST",
url: someUrl,
data: formData,
success: function(data) {
// update success message boxes here
}
});
} else {
// update client-side validation error message boxes
}
event.preventDefault(); // prevent the form from actually navigating to the action page
});
Hopefully this helps, I've found that the plugin can be useful at times, however I've typically found that this leads to easier to understand code and avoids the use of plugins..

Jquery and the plug-in Validate, testing for no errors

I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(document).ready(function() {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form()) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)

Categories