randommman randommman - 6 months ago 13
Javascript Question

jQuery data being passed back is coming up as undefined

I am sending error messages back to my jQuery/ajax form post, when I alert the data: it passes back:

{"success": false, "error": "Security tokens do not match, please try again"}


But when I try to get the error message like so:

if(!data.success){
alert(data.error);
}else{


The alert passes back undefined. Do I have to initiate a variable with the error first or...?

Sorry, I am new at this.

Here is my jQuery in case anyone needs it:

<!-- process add employment form without refreshing, then load the div with the new information !-->
$("#content").on("submit", "#add_employment_form", function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
alert(data);
if(!data.success){
alert(data.error);
}else{
$('#add_employment').text("+ <?php echo System::translate("Add employment"); ?>");
$(".add_qualification_json").slideUp("slow");
$("#content").load("<?php echo Config::get('URL'); ?>employment/employment" + " #inner_main_content");
$("html, body").animate({ scrollTop: 0 }, "slow");
}
}
});
return false; // important: prevent the form from submitting
});
<!-- end process add employment form without refreshing, then load the div with the new information !-->

Answer

The response mime type might be text/plain instead of application/json. So, its being processed by the javascript function as a normal string and not as a json object.

So, you need to set the right response mime type or do this in your success callback javascript function.

success: function(data) {
            alert(data);
            data = JSON.parse(data);
            .....