samedi 18 avril 2015

AJAX won't get JSON data second time

I'm sending Ajax request to a php file, that file returns an JSON array of the submitted data, the first time is great, it sends the data and gets it, so i can use it, but second time it gives me an error



SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data


My goal is to validate the data in the php file, if the data is not validated then i'm adding an error classes to the fields that are not validated, then the user correct those fields, and sends the form again, without refreshing.


My testing shows that its working for the first time, but when i want to send the form the second time, it gives me the above error, any clues what it can be?


AJAX :



$('#ajax').submit('submit', function(){

var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};

that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();

data[name] = value;
});

$.ajax({
url: url,
type: type,
data: data,
cache:false,

success: function(response){
var json = response,
obj = JSON.parse(json);
if(obj.title == 'Mrs.'){
// $('#title').addClass('has-warning');
$(function () {
$('#name').tooltip({ 'title': 'Please fill name'});
});
}
alert(obj.title);
}

});
return false;
});


PHP file:



if(Input::exists()){
if(token::check(Input::get('token'))){

echo json_encode(
array(
"title" => Input::get('title')
)
);
}

}

Aucun commentaire:

Enregistrer un commentaire