10 Replies - 749 Views - Last Post: 12 March 2015 - 11:12 AM

#1 humanatore  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 02-March 15

Valitdating form values with AJAX, how to output response

Posted 08 March 2015 - 12:47 PM

I'm completely new to Javascript, jQuery and AJAX! I'm using all the above to validate some user input in a large form. I have no idea what I'm doing and just need someone to point me in the right direction!

What I need help with
  • Looping through the AJAX response
  • How to show which tag caused the conflict in the form
  • Prevent the form from ONLY if there is a conflict


$(document).ready( function () {
    console.log('ready');
    var submitButton = $('#tagProductForm');

    submitButton.on('submit', function (e) {
        e.preventDefault();

        var tags = ($('.tag').map(function () { return $(this).val(); })).get();

        $.ajax({
            type: "POST",
            url: "validateTag.php",
            data: 'jData=' + JSON.stringify(tags)            
        })
        .done(function( response ) {
            if(response.length != 0){
                console.log('done response');

                for(var i = 1; i < response.length; ++i){
                    document.getElementById("tagValidity" + i).innerHTML = response.val;
                }
            }
            $('#response').html(response);
        })
        .fail(function() {
            $('#response').html('error');
        })
    });
});



Is This A Good Question/Topic? 0
  • +

Replies To: Valitdating form values with AJAX, how to output response

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4138
  • View blog
  • Posts: 13,073
  • Joined: 08-June 10

Re: Valitdating form values with AJAX, how to output response

Posted 09 March 2015 - 12:42 AM

Quote

Looping through the AJAX response

what does your response look like?

Quote

How to show which tag caused the conflict in the form

changing border, color, background-color. adding/showing a failure message, etc.

Quote

Prevent the form from ONLY if there is a conflict

prevent from what? if you mean submitting, you must not trigger a submit before the AJAX returns. that is, donít use a submit button.
Was This Post Helpful? 1
  • +
  • -

#3 humanatore  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 02-March 15

Re: Valitdating form values with AJAX, how to output response

Posted 09 March 2015 - 08:32 AM

OK, so I got the border changing styles for the elements with tags that conflict with the database.

$.ajax({
    type: "POST",
    url: "validateTag.php",
    data: 'jData=' + JSON.stringify(tags)            
})
.done(function( response ) {
    response = response.replace(/[[\]]/g,'');
    var responseArray = response.split(",");
    var size = responseArray.length;
    if(size != 0){                 
        for(var i = 0; i < size; ++i){
            if(responseArray[i]=='false'){
                $('#tag' + i).attr('style','border:3px solid #FF0000');
            }
        }
    }
})



I'm not sure how to make this work without using a submit button and how to submit the form only when there aren't conflicts. Also, I could use some help with validating the tags against themselves. I don't want someone to be able to submit conflicting tags on the same form as well as tags that conflict with the database.
Was This Post Helpful? 0
  • +
  • -

#4 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4138
  • View blog
  • Posts: 13,073
  • Joined: 08-June 10

Re: Valitdating form values with AJAX, how to output response

Posted 09 March 2015 - 09:08 AM

Quote

I'm not sure how to make this work without using a submit button and how to submit the form only when there aren't conflicts.


explained in pseudo code:
$.ajax
    settings
.done
    if no error
        call form.submit()
    else
        show errors


Was This Post Helpful? 1
  • +
  • -

#5 humanatore  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 02-March 15

Re: Valitdating form values with AJAX, how to output response

Posted 10 March 2015 - 06:41 AM

I have been trying to get this to work and I just can't get it.. I have a love/hate relationship with Javascript. Right now its the latter.

I need to stop the form from submitting if validation fails.

I've tried onsubmit() from the HTML linking to a function in JS.

<!-- HTML -->
form onsubmit="return validateTags(this);">

// Javascript
function validateTags(form) {



I've tried this event handler on the submit button

var submitButton = $('#tagProductForm');
submitButton.on('submit', function (e) {
    e.preventDefault();




Javascript
$(document).ready( function () {
    
    function validateTags(form) {
        
        var valid = true;
        var tags = ($('.tag').map(function () { return $(this).val(); })).get();
        
        $.ajax({
            type: "POST",
            url: "validateTag.php",
            data: 'jData=' + JSON.stringify(tags)            
        })
        .done(function( response ) {
            
            response = response.replace(/[[\]]/g,'');
            var responseArray = response.split(",");
            var size = responseArray.length;
            
            if(size != 0){                 
                for(var i = 0; i < size; ++i){
                    if(responseArray[i] == 'false'){
                        $('#tag' + i).attr('style','border:3px solid #FF0000');
                        // set valid to false
                        valid = false;
                        console.log('valid is ' + valid);
                    }
                }
              // tried validated clause here too
            }
        })
        .fail(function() {
           $('#response').html('error');
           return false;
        });

        // validated clause
       if(valid == false)
       {
           return false;
       }
   }
});




HTML
<!DOCTYPE html>
<html>
    <head>

    </head>
	<body>
		<!-- Eventually submit form to countEntry.php -->
		<form onsubmit="return validateTags(this);">
			<table class="gridtable2" align="center">
				<tr>
				    <td class="whse gridtable center">main</td>
				    <td class="count medFont gridtable">A2132566</td>
				    <td class="count gridtable">ac01aa02</td>
				    <td class="count gridtable">
				    	<input type="text" class="tableTxt" name="inv[1163][Count]" placeholder="count"/>
				    </td>
				    <td class="gridtable">
				    	<input type="text" class="tag" id="tag0" name="inv[1163][Tag]" placeholder="tag"/>
				    </td>
				</tr>
				<tr>
				    <td class="whse gridtable center">main</td>
				    <td class="count medFont gridtable">A2132567</td>
				    <td class="count gridtable">ac02aa02</td>
				    <td class="count gridtable">
				    	<input type="text" class="tableTxt" name="inv[1164][Count]" placeholder="count"/>
				    </td>
				    <td class="gridtable">
				    	<input type="text" class="tag" id="tag1" name="inv[1164][Tag]" placeholder="tag"/>
				    </td>
				</tr>
				<button type="submit" id="submitButton">Submit</button>
			</table>
		</form>

		<div id="response"></div>

		    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
        	<script type="text/javascript" src="tval.js"></script>

	</body>
</html>




PHP

<?php

$tagArray = array();

$conn = new PDO("sqlsrv:Server=localhost;Database=inventory", "sa", "pcmAdmin2014");
if($conn === false ){
    die(print"Could not connect. <br /> Try testing your connection to the SQL server.");
}

$queryString = "SELECT DISTINCT Tag FROM tag_table";
$query = $conn->prepare($queryString);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);

foreach ($results as $record) {
    if(isset($record['Tag']) && $record['Tag'] != '')
        $tagArray[] = $record['Tag'];
}

$jDataPost = $_POST['jData'];

$jTagArray = json_decode($jDataPost);

$responseArray = array();

foreach ($jTagArray as $value) {
    $tag = $value;
    if(in_array($tag, $tagArray))
        $responseArray[] = false; //don't insert record, this tag exists. 
    else
        $responseArray[] = true; //this record can be inserted, tag does not exist
}

echo json_encode($responseArray);

?>




I'm trying to put headings on top the different kinds of code, and that's not working either... so I'm giving up before I smash this laptop.
Was This Post Helpful? 0
  • +
  • -

#6 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4138
  • View blog
  • Posts: 13,073
  • Joined: 08-June 10

Re: Valitdating form values with AJAX, how to output response

Posted 10 March 2015 - 08:31 AM

the problem is that you have problems understanding how asynchronous code (AJAX) works.

for starters put some alerts or console logging statements to see which part of your code is executed in which sequence.

second, you can submit a form purely from JS, no onsubmit attribute in the HTML code needed. (and my pseudo-code didnít mention any events either Ö should you have read it)
Was This Post Helpful? 1
  • +
  • -

#7 humanatore  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 02-March 15

Re: Valitdating form values with AJAX, how to output response

Posted 10 March 2015 - 10:29 AM

I did read the psuedo-code, but I guess I assumed that an event was necessary. I do use console.log() statements as well, but I remove them from my code when I make a post. I will leave them in from now on.

I'm so confused about how to initiate the validation or submit this form. Should I use a submit button? Or a generic button that calls my script? Or should I use onkeyup or onchanged for each of the text fields? But aren't those all events? Am I completely missing what you're trying to tell me?
Was This Post Helpful? 0
  • +
  • -

#8 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4138
  • View blog
  • Posts: 13,073
  • Joined: 08-June 10

Re: Valitdating form values with AJAX, how to output response

Posted 10 March 2015 - 10:43 AM

Quote

I'm so confused about how to initiate the validation or submit this form.

initiate as usual, submit from within the validation.

Quote

Should I use a submit button?

of course not. that would submit the form before you even know if the input validates.

Quote

Or should I use onkeyup or onchanged for each of the text fields?

that would enhance the user friendliness.

Quote

But aren't those all events?

events are an important part of JS. but not every time an event is the tool of choice.

Quote

Am I completely missing what you're trying to tell me?

what I try to tell you is that asynchronous code works totally different from synchronous code and hence the (coding) strategies you are used to with synchronous code usually fail in 99% of the cases.

that jQueryís $.ajax() uses a Promise (sort-of) [canít find a good link right now] doesnít make it easier for you.

Quote

I do use console.log() statements as well, but I remove them from my code when I make a post.

so, did you find out in which order your code executes?
Was This Post Helpful? 1
  • +
  • -

#9 humanatore  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 02-March 15

Re: Valitdating form values with AJAX, how to output response

Posted 11 March 2015 - 07:28 AM

So, I had to take a break for a little while yesterday and focus on something else. Back to it today and I've realized I might have a design flaw.

Right now the flow looks like:

validate.js -> checkExistingTag.php -> validate.js -> insertTagData.php

I'm wondering if I should merge the two PHP files into one? Or is this design suitable?
Was This Post Helpful? 0
  • +
  • -

#10 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4138
  • View blog
  • Posts: 13,073
  • Joined: 08-June 10

Re: Valitdating form values with AJAX, how to output response

Posted 11 March 2015 - 08:03 AM

Quote

Right now the flow looks like:

and what’s the flow in your JS code?

Quote

I'm wondering if I should merge the two PHP files into one?

you do not validate data immediately before you insert them into the DB?

if insertTagData.php does not perform any validation itself, this is dangerous design (anyone could send data to that script, whether they are validated or not).

so, if the sole purpose is to find out whether a tag already exists there is a far easier solution, which makes pretty all your code here superfluous: (unless you would use this as UX helper)
ALTER TABLE tag_table ADD UNIQUE KEY (Tag);

(of course you would have to make sure there are no duplicates already in there)

obviously this advice assumes that the tags are supposed to be unique and maybe should even serve as Primary Key.


Note on your PHP code: the PDO connection object is never ever false. read in the Manual why.

also, your query string (not having any data in it) doesn’t need to be treated as prepared statement.

 //# this is sufficient:
//# if Tag were UNIQUE, you would omit DISTINCT
$query    = $conn->query('SELECT DISTINCT Tag FROM tag_table WHERE Tag <> ""');
$tagArray = $query->fetchAll(PDO::FETCH_COLUMN, 0);


This post has been edited by Dormilich: 11 March 2015 - 08:07 AM

Was This Post Helpful? 1
  • +
  • -

#11 humanatore  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 02-March 15

Re: Valitdating form values with AJAX, how to output response

Posted 12 March 2015 - 11:12 AM

Thank you, Dormilich for your continued support. Thanks for the pointers on the PHP script, I'll look into that stuff.

I think I figured out something that's going to work for me with the form validation.

A Working Solution

Javascript

function validate(field, query)
{
    $.ajax({
        type: "POST",
        url: "validateTag2.php",
        data: 'jData=' + JSON.stringify(query)          
    })
    .done(function(response) {
    	response = response.replace(/[[\]]/g,'');
    	if(response == 'false') {
    		$('#' + field + 'cell').attr({ style: 'border:3px solid #FF0000' });
            $('#' + field).attr({ valid: 'false'});
        }
    	else {
    		$('#' + field + 'cell').attr({ style: 'border: none' });
            $('#' + field).attr({ valid: 'true'});
        }
    })
    .fail(function() {
    	$('response').html('error');
    });
}

function checkForm(variable)
{
    var allTagsValid = true,
        tags = ($('.tag').map(function () { return $(this).attr('valid') })).get();

    tags.forEach(function(tag) {
        if(tag == 'false')
            allTagsValid = false;
    });

    if(allTagsValid == true) {
        $('form').submit();
    } else {
        alert('there is an invalid tag');
    }
}



HTML

<!DOCTYPE html>
<html>
    <head>

    </head>
	<body>
		<!-- Eventually submit form to countEntry.php -->
		<form class="validate" id="countEntryForm" action="insertTagData.php" method="post">
			<table class="gridtable2" align="center">
				<tr>
				    <td class="whse gridtable center">main</td>
				    <td class="count medFont gridtable">A2132566</td>
				    <td class="count gridtable">ac01aa02</td>
				    <td class="count gridtable">
				    	<input type="text" class="tableTxt" name="inv[1163][Count]" placeholder="count"/>
				    </td>
				    <td id="tag0cell" class="gridtable">
				    	<input type="text" class="tag" id="tag0" name="inv[1163][Tag]" placeholder="tag" onblur="validate('tag0', this.value)" valid="default"/>
				    </td>
				</tr>
				<tr>
				    <td class="whse gridtable center">main</td>
				    <td class="count medFont gridtable">A2132567</td>
				    <td class="count gridtable">ac02aa02</td>
				    <td class="count gridtable">
				    	<input type="text" class="tableTxt" name="inv[1164][Count]" placeholder="count"/>
				    </td>
				    <td id="tag1cell" class="gridtable">
				    	<input type="text" class="tag" id="tag1" name="inv[1164][Tag]" placeholder="tag" onblur="validate('tag1', this.value)" valid="default"/>
				    </td>
				</tr>
				<input type="button" onclick="checkForm('submitButton')" id="submitButton" value="Submit">
			</table>
		</form>

		<div id="response"></div>

		    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
        	<script type="text/javascript" src="validator.js"></script>

	</body>
</html>



PHP

<?php

// header("Content-Type: application/json", true);

$tagArray = array();

$conn = new PDO("sqlsrv:Server=localhost;Database=inventory", "sa", "pcmAdmin2014");
if($conn === false ){
    die(print"Could not connect. <br /> Try testing your connection to the SQL server.");
}

$queryString = "SELECT DISTINCT Tag FROM tag_table";
$query = $conn->prepare($queryString);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);

foreach ($results as $record) {
    if(isset($record['Tag']) && $record['Tag'] != '')
        $tagArray[] = $record['Tag'];
}

$jTag = json_decode($_POST['jData']);

if(in_array($jTag, $tagArray))
    $response = false; 
else
    $response = true;

echo json_encode($response);

?>


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1