Jessie Stalk
Jessie Stalk

Reputation: 991

Input validation through AJAX

I have the following AJAX in my index.php:

$(document).ready(function() {
     $('.buttono').click(load);
 });

 function load() {
     $.ajax({
         url: 'http://localhost/Generator/js/ajaxRequest.php'
     }).done(function(data) {
         $('#content').append(data);
     });
 }

HTML (part of index.php):

<form method="POST" action="">
    <input type="text" name="input">
    <input type="submit" name="submit" class="buttono" value="Convert">
</form>
<div id='content'></div>

And in my ajaxRequest.php I have the following PHP snippet:

if ($_POST['input'] == 'dog') {
    echo 'Status 1';
} else if ($_POST['input'] == 'cat') {
    echo 'Status 2';
}

How can I perform the PHP check through AJAX? So that if I click the submit button and have typed 'dog', to return the string Status 1?

Upvotes: 0

Views: 62

Answers (3)

hellokitty
hellokitty

Reputation: 1

Try this:

in you php file:

$res = array();

if ($_POST['input'] == 'dog') {
    $res['status'] = '1';
} elseif ($_POST['input'] == 'cat') {
    $res['status'] = '2';
}

echo json_encode($res);

Then in your jquery:

function load(){
    $.ajax({
         type : "POST",
         data : { input : $("input[name='input']").val() }, 
         url:'http://localhost/Generator/js/ajaxRequest.php'
    }).done(function(data){
        $('#content').append(data.status);
    });

}

Upvotes: 0

recoup8063
recoup8063

Reputation: 4280

What you have to do is make the user fill out the form and then instead of clicking a type="submit" button just make them click a regular button. Then when that person clicks the regular button submit. You can do this by:

<!-- HTML -->
<form method="POST">
    <input type="text" id="type"/>
    <button id="submit">Sumbit</button>
</form>


<!-- JS -->
$(document).ready(function(){
    $('#submit').click(onSubmitClicked);
});

function onSubmitClicked(){
    var data = {
        "input": $('#type').val()
    };

    $.ajax({
      type: "POST",
      url: "url/To/Your/Form/Action",
      data: data,
      success: success
    });

    function success(data){
        if(data == 'status 1'){
           //Do something
        }
    }
}

Upvotes: 0

Mostafa Talebi
Mostafa Talebi

Reputation: 9183

Well what I see in your code is that:

first you have not specified your request method,

second you have not set $_POST['dog']

I would have gone with this ajax:

$.ajax({
  type : "POST",
  url : 'to/url',
  data : { input : $("input[name='input']").val() },
  success :  function(data){
    // do whatever you like
  }
});

Upvotes: 2

Related Questions