0

I am try to post a data from a from I have this code on my html.

<javascript>
$(document).ready(function(){
$("#btnsubmit").click(function(e){
    e.preventDefault();
    var testData = $("#test").serialize();
    $.ajax({
        type: "POST",
        url: "ajaxSurvey.php",             
        data: {survey:testData}          
    });
});
})
</javascript>

and my form

<form id="test" name="test" method="POST">
  <input name="surveyperiod" id="surveyperiod" type="date">
  <input name="deadline" id="deadline" type="date"  >
  <input type="submit" id="btnsubmit"name="btnsubmit" value="   Update    ">
</form>

and my php page

if(isset($_POST['survey']){
    $myDate = $_POST['survey'];

    mysql_query('INSERT INTO (surveyperiod,deadline) VALUES (????????)');

}

Now how can I deserialize $myDate which is look like below

surveyperiod=2014-02-25&deadline=2014-02-18

jules
  • 19
  • 3
  • 8

2 Answers2

0

You do not need to deserialize, you can do that in different way by putting hidden field like;

HTML:

<form id="test" name="test" method="POST">
  <input name="survey" type="hidden" value="true"/>
  <input name="surveyperiod" id="surveyperiod" type="date">
  <input name="deadline" id="deadline" type="date"  >
  <input type="submit" id="btnsubmit"name="btnsubmit" value="   Update    ">
</form>

PHP:

if(isset($_POST['survey']){
    $myDate = $_POST['survey'];

    mysql_query('INSERT INTO (surveyperiod,deadline) VALUES ($_POST["surveyperiod"], $_POST["deadline"])');

}

JS:

<javascript>
$(document).ready(function(){
$("#btnsubmit").click(function(e){
    e.preventDefault();
    var testData = $("#test").serialize();
    $.ajax({
        type: "POST",
        url: "ajaxSurvey.php",             
        data: testData          
    });
});
})
</javascript>

By doing this, you dont neede to post data like {survey:testData}. Simply add,

<input name="survey" type="hidden" value="true"/>

html and check hidden field on php side. If a field with name survey exists, then run your code

Hüseyin BABAL
  • 15,400
  • 4
  • 51
  • 73
0

Tricky method is use parse_str()

// Access as Variable
if( isset($_POST['survey']) ){

    // surveyperiod=2014-02-25&deadline=2014-02-18
    parse_str($_POST['survey']);

    $S_Period = $surveyperiod;
    $S_Deadline = $deadline;

   // do whatever you want
   mysql_query('INSERT INTO (surveyperiod,deadline) VALUES ( "'.$S_Period.'", "'.$S_Deadline.'" )');

}

Explanation:

In you Ajax Request you send the data via POST method( data: {survey:testData} ) and assigned a POST variable that is survey and this POST variables contains the data string surveyperiod=2014-02-25&deadline=2014-02-18 as you assigned in your javascript testData. Now what we have to do is, Now we have to parse string into variables and parse_str() inbuilt function do it for you. That's it :)

jogesh_pi
  • 9,762
  • 4
  • 37
  • 65