0

I have a php file to validate a form with data that need to get sent through ajax. The data that I receive back from the php file is unchanged, how can I receive the correct data? main.js

$("#PersonForm").submit(function()
{ 
  var data = $("form").serializeArray();
  $.ajax({
    type:"post",
    url:"main.php",
    act: 'validate',
    datatype:"json",
    data:data,
    function(data){
      console.log(data);
  }});

  return false;
});

main.php

else if ($_REQUEST['act'] == 'validate')
{
    $validateData = array();

    if (preg_match("[A-Za-z]{3,20}$/",$_REQUEST['name'])){
        $validateData['name'] = 1;
    }else{
        $validateData['name'] = 0;
    }

    echo json_encode($validateData);

The data that originally gets sent in the data array is name:Bob
The expected return is 1 or 0 but I recieve name:Bob back.

4
  • 1
    What is this doing? $_REQUEST['act'] == 'validate' does it ever enter this else if statement? Commented Dec 8, 2016 at 18:14
  • Yeah, what is the condition for the if statement on that? Commented Dec 8, 2016 at 18:17
  • I think that act is missing from the data that you post via ajax Commented Dec 8, 2016 at 18:18
  • if ($_REQUEST['act'] == 'default') the default act and the one after enter no problem, just this validate act has issues Commented Dec 8, 2016 at 18:18

1 Answer 1

2

Ok, the issue is you have to actually pass that in the data. You are doing this:

$.ajax({
    type:"post",
    url:"main.php",
    act: 'validate', // <--- THIS IS WRONG
    datatype:"json",
    data:data,       // <--- IT SHOULD BE IN THIS
    function(data){
      console.log(data);
    }
});

It has to be in your data variable to be passed. You are using it as an option to the jQuery ajax() method, which doesn't work.

var data = $("form").serializeArray();
data.push({name: 'act', value: 'validate'});
// Then make ajax call here

After serializing your form data, you can add that on as an additional value.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.