Krystian
Krystian

Reputation: 71

AJAX post data from php file

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.

Upvotes: 0

Views: 121

Answers (1)

Jeremy Harris
Jeremy Harris

Reputation: 24599

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.

Upvotes: 2

Related Questions