Bob
Bob

Reputation: 1375

How to access individual values of form data, passed from an HTML page with jQuery.ajax(), inside a PHP script?

I'm passing form data to a PHP script for processing via JS(jQuery.ajax()).

Problem is - I can't figure out a way to access individual form control values inside PHP( e.g. $_POST['zipcode'] ).

Instead I can only access the data with $_POST['form'], which is an entire form represented as one long string( e.g. string(89)"color=red&color=blue&zipcode=12345..." ).

How can I access individual values of form data inside PHP script passed from a HTML form via JS?

index.php(form)

 <form id="myform">
    <select name="color" id="color">
    <option value="Red">Red</option>
    <option value="Green">Green</option>
    <option value="Blue">Blue</option>
    </select>
    <input type="text" id="zipcode" name="zipcode" />
    <input type="submit" id="submit" name="submit" value="Submit" />
    </form>

index.php(JS)

$('#myform').on('submit', function(e) {
                    e.preventDefault();
                    $.ajax({
                        type: 'POST',
                        dataType: 'html',
                        url : 'PHPscript.php',
                        data: {form : $('#myform').serialize()}
                    }).done(function(data) {
                         var myJSONresult = data;
                         alert(myJSONresult);
                    });
                });

PHPscript

<?php
if(isset($_POST["form"])){
$form = $_POST["form"];

$myzipcode = $_POST['zipcode']; // won't work; will be null or empty

echo json_encode($form);

}
?>

EDIT: The zipcode field:

$("#zipcode").focus(function(){
                    if(this.value == "zipcode"){
                        $(this).val("");
                    }
                }).blur(function(){
                    if(this.value == ""){
                        $(this).val("zipcode");
                    }
                });

Upvotes: 0

Views: 1821

Answers (3)

James L.
James L.

Reputation: 4097

You need to use serializeArray() on the form data instead of serialize. That will submit as an array.

data: $('#myform').serializeArray()

HTML

<input type="hidden" name="action" value="submit" />

PHP

if(isset($_POST["action"]))
{
    //code
}

Upvotes: 2

JIA
JIA

Reputation: 1495

set traditional to true like

$.ajax({
traditional:true,
//your rest of the ajax code
});

on the php end you are getting the value fine the problem is at the form serialization end

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382696

Add dataType: 'json' to your ajax handler and further modify your code like this:

$.ajax({
    type: 'POST',
    dataType: 'json', // changed to json
    url : 'PHPscript.php',
    data: {form : $('#myform').serialize()},
    success : function(data){ // added success handler
     var myJSONresult = data;
     alert(myJSONresult.yourFieldName);
    }
});

Upvotes: 1

Related Questions