1

So I have searched the forum for similar questions unfortunately I have been unlucky to find an answer that suits my problem. I am trying to make an ajax call in my jquery using the following code;

function submitForm(formData)
    {
    $.ajax({
        type: 'POST',
        url: 'addEvents.php',
        data: formData,
        dataType:'json',
        cache:false,
        timeout:7000,

        success: function(data){
            $('#addEventsForm #response').removeClass().addClass((data.error === true) ? 'error' : 'success').html(data.msg).fadeIn('fast');

            if($('#addEventsForm #response').hasClass('success')){
                setTimeout("$('#addEventsForm')",5000);
            }

        },

        error:function(XHR,textStatus,errorThrown)
        {
            $('#addEventsForm #response').removeClass().addClass('error').html('<p> There was an <strong>' + errorThrown +
                '</strong> error due to <strong>'+ textStatus +'</strong> condition.</p>').fadeIn('fast');
            console.log(arguments);
        //alert(XMLHttpRequest.responseText);
        },

        complete:function(XHR,status)
        {
            $('#addEventsForm')[0].reset();
        }
    });
}

But I am getting a sysntax error. I have tried doing this to see what errors I get in chrome

console.log(arguments);

but the responseText in the [Object, "parsererror" , SyntaxError] node seems to display the entire html of the page that contains the form where I am inserting the record.

I am still getting my feet wet in ajax so I am not yet a pro in absolutely understanding the error messages and what they mean.

Rahil Wazir
  • 10,007
  • 11
  • 42
  • 64
mistaFloss
  • 31
  • 1
  • 9
  • 1
    is the server actually returning json or html, that is the usual error i get when the endpoint is actually outputing html instead of json – Patrick Evans Aug 23 '14 at 17:05
  • 1
    Probably the server returns HTML while you expect JSON - that's a syntax error. – Bergi Aug 23 '14 at 17:05
  • it's a parse error, as the returned string can't be parsed, so it's **not** what you think it is. – adeneo Aug 23 '14 at 17:06
  • As you said, the responseText contains HTML. HTML is not JSON. Either return JSON from the server and change your client side code to deal with HTML. – Felix Kling Aug 23 '14 at 17:12
  • @FelixKling the way to return JSON from server is that using the `json_encode` method? because in the php code that does the inserting I have done something like this. `if($events->save()){ $return['error'] = false; $return['msg'] = "The event was uploaded successfully"; echo json_encode($return); } else{ $message = join("
    ", $events->errors); $return['error'] = true; $return['msg'] = "The event upload failed because".$error_message.$message; echo json_encode($return); }`
    – mistaFloss Aug 23 '14 at 17:24
  • Do you `echo` anything else on that page? Is the code successfully executed? – Felix Kling Aug 23 '14 at 17:41
  • @FelixKling no the code does not execute and I think the ajax could be affecting the php from executing because when I remove the jquery validation/ajax call the code runs. – mistaFloss Aug 23 '14 at 17:46
  • Have you seen my answer? Is this what you are doing? (i.e. posting AJAX to same page the ajax code block is on?) – cssyphus Aug 23 '14 at 18:06
  • @gibberish No. I am posting to a different page. The ajax is in a file called `"scripts.js"` and its posting to `addEvents.php` – mistaFloss Aug 23 '14 at 18:21

1 Answers1

0

Is the above js/jQuery code located on the addEvents.php page -- that is, on same page that you are posting the AJAX to? (In other words, are both the form/ajax and the AJAX destination on the same physical PHP page?)

If so, you will get exactly what you describe: the entire HTML of the page spat back at you.

AJAX, by design, must post to a different physical page on the server. That's just how it works.

Also, FWIW, note that dataType: 'json', refers to the data being returned, not the data being sent. Perhaps you already know this, but it is a common misunderstanding so is worth mentioning.

Edit:

As Felix points out, this answer is not technically perfect. It is possible to post AJAX code to the same page, but you must specifically allow for that. Perhaps FK or another could edit this post to add an example of what that additional code would look like?

cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • 2
    *"AJAX, by design, must post to a different physical page on the server."* I disagree. The server can send different responses for the same URL, depending on request headers or parameters. However one has to explicitly account for that, it doesn't happen automagically. – Felix Kling Aug 23 '14 at 17:14
  • Felix, you're the pro here (I know who you are, and congrats for landing the FB job!). Perhaps my explanation is technically imperfect, but this is something I've seen several times and if the AJAX is posted to the same page as teh form/ajax code block, then this is a common result. How would you rephrase/clarify my answer? – cssyphus Aug 23 '14 at 17:17
  • @gibberish no the above js/jQuery code is not located in `addEvents.php`. – mistaFloss Aug 23 '14 at 17:20
  • Thanks :) that's why I added the last sentence to my comment. I would say something like "If the Ajax request is sent to same page, the server has to be able to distinguish between a "normal" request and an Ajax request, so that it can send the appropriate response. It won't happen automatically." – Felix Kling Aug 23 '14 at 17:20
  • Thanks Felix. I've never seen how to do that (or even known it was poss prior to your comment). Can you add another answer with a brief example -- or link reference -- for syntax of what such a modification would look like? *(I can guarantee at least one upvote for your time...)* – cssyphus Aug 23 '14 at 17:23
  • @user3620197: it actually doesn't matter if it's the same page or not. If the page is designed to be directly accessible in the browser (i.e. returns HTML) and you also want to be able to make an Ajax request to it, it may have to return different data. – Felix Kling Aug 23 '14 at 17:26
  • @FelixKling I am not sure you understand what I am getting at. [In a different question](http://stackoverflow.com/questions/17529509/values-not-updated-after-an-ajax-response/17530014#17530014), I created a simple demo that will return exactly what this OP is describing. Please comment. – cssyphus Aug 23 '14 at 17:30
  • Oh, the simplest way would be to append `ajax=1` to the URL and in php do something like `if (isset($_GET['ajax'])) { echo $json; } else { echo $html; }`. Better implementations would look at the requested content type in the request headers. – Felix Kling Aug 23 '14 at 17:30
  • @FelixKling I just now [looked at the api](http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings) (this is a `type='POST'`) for the `ajax=1` param, but cannot find. Could you please clarify? – cssyphus Aug 23 '14 at 17:33
  • It's just a GET parameter you would add to the URL. It has nothing to is with jQuery. But I *think* that jQuery even sets a request header that indicates the rue west is an Ajax request. – Felix Kling Aug 23 '14 at 17:40