EDIT: It's about synchronization, the ajax call is asynchronous so it doesn't block the execution of code.
I have a JavaScript code that use JQuery.ajax() to upload an user supplied file, and if successful submits the form otherwise shows an error and stops the form from being submitted.
I have placed alert(); at all the important places to keep an eye on the flow of the code.The problem is the alerts are not showing up the way I was expecting and everything is messed up.
If the ajax call is successful first we should see alert('1'), if file upload is successful we should see alert('2') otherwise we should see alert('3'), if the ajax call failed for some reason we should see alert('4') and in the end we should see alert('5');
But in reality the alerts are showing like this :
alert('5')
alert('4')
alert('5')
And the alert('4') shows even before alert('5') goes away(without doing anything).
What am I missing ?
The file is getting uploaded but the result is not returning in the success function of the code.
JavaScript
var files;
$( document ).ready ( function ( ) { $ ( '#user_file' ).on ( 'change', prepareUpload ); }
function prepareUpload ( event ) { files = event.target.files; }
$( 'myform' ).submit( function ( event )
{
var gender = $ ( 'input[name=gender_group]:checked', 'myform' ).val ( );
var data = new FormData ( );
data.append ( 'userfile', files [ 0 ] );
data.append ( 'gender', gender );
data.append ( 'ajaxUpload', 'true' );
$returnvalue = false;
$.ajax ( {
method : 'POST', url : scriptUrl, data : data, cache : false, processData: false, contentType: false, dataType : 'json',
success : function ( data, textStatus, jqXHR ) {
alert ( '1' );
if ( typeof data.error === 'undefined' )
{
alert ( '2' ); $returnvalue = true;
}
else
{
alert ( '3' ); $returnvalue = false;
}
},
error : function ( xhr, ajaxOptions, thrownError ) {
alert ( '4' ); $returnvalue = false;
}
});
alert ( '5' ); return $returnvalue;
}
Controller
if ( $this->input->post ( 'gender' ) && $this->input->post ( 'ajaxUpload' ) )
{
$this->load->model ( 'My_model' );
echo json_encode ( $this->My_model>do_upload ( ) );
}
Model (My_model)
public function do_upload ( ) {
$this->load->library ( 'upload' );
$data = array ( );
// The cofiguration for the upload call is saved in a config file - config/upload.php
if ( ! $this->upload->do_upload ( ) ){
$data [ 'error' ] = 'true';
} else {
$data [ 'screen_name' ] = $screen_name;
}
return $data;
}