StudentX StudentX - 2 months ago 16
Javascript Question

Codeigniter & Jquery Ajax, Post data not going through

I am having problem getting the post data in the controller when I send the post request via Jquery Ajax, I have checked with firebug and the form post data is being submitted, but in the controller when I do print_r($_POST); it returns an empty array. What could be wrong ?

Here is the relevant code :

FORM HTML

<form id="contact-form" class="form-horizontal subscribe" accept-charset="utf-8" action="<?= base_url ( 'Contact/' ); ?>" method="post">
<!--Name-->
<div class="form-group">
<label class="sr-only" for="name">Name</label>
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-user" aria-hidden="true"></span></div>
<input id="name" type="text" class="form-control validate" name="name" placeholder="Your full name" value="">
</div>
</div>
<!--Email-->
<div class="form-group">
<label class="sr-only" for="email">Email</label>
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span></div>
<input id="email" type="text" class="form-control validate" name="email" placeholder="Your email address" value="">
</div>
</div>
<!--Message-->
<div class="form-group">
<label class="sr-only" for="message">Message</label>
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span></div>
<textarea id="message" name="message" class="form-control" rows="3" placeholder="Message"></textarea>
</div>
</div>
<!--Submit Button-->
<div class="form-group text-right">
<input id="contact_us" type="hidden" name="contact_us" value="Submit" />

<button type="submit" id="contact_us" class="btn btn-warning" name="contact_us" value="Submit">
Send &nbsp;<span class="glyphicon glyphicon-send" aria-hidden="true"></span>
</button>
</div>
</form>


JAVASCRIPT

<script>
$( '#contact-form' ).submit ( function ( event ) {

event.preventDefault ( );
event.stopPropagation ( );

var $scriptUrl = $( '#contact-form' ).attr ( 'action' );

$.ajax ( {
method : 'POST',
url : $scriptUrl,
data : $( this ).serialize ( ),
cache : false,
processData: false,
contentType: false,
dataType : 'json',
success : function ( data, textStatus, jqXHR ) {
if ( data.success === true ) { alert ('success'); }
else { alert ('failure'); }
},
error : function ( jqXHR, textStatus, errorThrown ) {
alert ( jqXHR.responseText );/*This returns the empty array*/
}
} );

} );
</script>


Controller (index function) (http://mysite/Contact - Localhost-wamp)

public function index ( )
{
print_r($_POST);
}

Answer

change data : $( this ).serialize ( ), to data : new FormData($('#contact-form')[0]) remove dataType : 'json' if this didnot work for you please let me know?

Comments