Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to access individual values of form data, passed from an HTML page with jQuery.ajax(), inside a PHP script?
    text
    copied!<p>I'm passing form data to a PHP script for processing via JS(<code>jQuery.ajax()</code>). </p> <p>Problem is - I can't figure out a way to access individual form control values inside PHP( e.g. <code>$_POST['zipcode']</code> ). </p> <p>Instead I can only access the data with <code>$_POST['form']</code>, which is an entire form represented as one long string( e.g. <code>string(89)"color=red&amp;color=blue&amp;zipcode=12345..."</code> ). </p> <p>How can I access individual values of form data inside PHP script passed from a HTML form via JS?</p> <p><em>index.php(form)</em></p> <pre><code> &lt;form id="myform"&gt; &lt;select name="color" id="color"&gt; &lt;option value="Red"&gt;Red&lt;/option&gt; &lt;option value="Green"&gt;Green&lt;/option&gt; &lt;option value="Blue"&gt;Blue&lt;/option&gt; &lt;/select&gt; &lt;input type="text" id="zipcode" name="zipcode" /&gt; &lt;input type="submit" id="submit" name="submit" value="Submit" /&gt; &lt;/form&gt; </code></pre> <p><em>index.php(JS)</em></p> <pre><code>$('#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); }); }); </code></pre> <p><em>PHPscript</em></p> <pre><code>&lt;?php if(isset($_POST["form"])){ $form = $_POST["form"]; $myzipcode = $_POST['zipcode']; // won't work; will be null or empty echo json_encode($form); } ?&gt; </code></pre> <p><strong>EDIT:</strong> <em>The zipcode field:</em></p> <pre><code>$("#zipcode").focus(function(){ if(this.value == "zipcode"){ $(this).val(""); } }).blur(function(){ if(this.value == ""){ $(this).val("zipcode"); } }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload