not_this_again not_this_again - 1 year ago 72
PHP Question

$('form').submit changing content length header and causing request to fail?

Fail Scenario:

I bind a submit event to an AJAX post request to send a hardcoded key-value pair to a PHP script which will return a message saying the request has been correctly received.

The submit event fires and the AJAX request is sent, but it fails. Looking at the paramters in firebug, the parameters look exactly as they should.

$(document).ready(function(event) {

$('form').submit(function(event) {
$.post( "reqhandler.php", { "division": "division"});


Working scenario:

I copy the POST request and enter it into the console as is. The request is performed just like above with the same paramters, but this time it works:

$.post( "reqhandler.php", { "division": "division"});

My guess:

The only difference between the two scenarios I showed up above is the content-length in the request headers. The failing scenario has a content-length header of 23, and the working one has a content-length of 17, which is what it should be.

Why is the failing scenario not working? Im not sure how to fix it.

Answer Source

Assuming you have a form with a submit button, use the following external JavaScript:

$(function(){ //load start

$('form').submit(function(){ // no need for EventObject here
  $.post('reqhandler.php', {division: 'division'}, function(res){
    console.log(res); // use Firebug
    // res could be result from PHP's echo json_encode($assocArray);
  }, 'json');
  return false;

}); // load end

reqhandler.php might look like:

$res = array('someProp' => 'a value', 'prop2' => array('now', 'you', 'see', 365));
  echo json_encode($res);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download