jQuery Load() and AJAX

RationalRabbit
RationalRabbit used Ask the Experts™
on
jQuery 1.11.1 (may be able to use newer version)
And yes, for now we're using mysql
I am loading a form into a div, using jQuery's load() function. I'm loading that file inside a 3rd party tab (Solid Tabs). The form submits through AJAX to a PHP file. Some jQuery functions, including the AJAX routine, need to be accessed by both the main program and the loaded form, so I created a js file, which is called up by both, since the form would not otherwise be able to access the javascript in the main file.

I am having problems troubleshooting. The process is acting like it is not finding the DBFunctions.php file, as the server is not receiving a request. However, as I was unsure of where the imported file was seeing itself, I changed the url to the full path and it is still failing. Click code works okay and the form serializes okay. Then, nothing.

Main File
    <div>
        <div id="UtilButtons">
            <div>
                <a class="btn" id="AddAdmin" href="javascript:void(0)">Add Program Admin</a>
            </div>
        </div>
    </div>

Open in new window



pAddPA.php

    <div class="SaveButton" id="ProgPAReg" data-formname="AddPA">Register</div>

Open in new window

jQueryEdit.js
    $(document).ready(function()
    {
        $("#AddAdmin").click(function()
        {
            $("#UtilButtons").hide("slow");
            $("#ReturnButton").show();
            $("#AddPAFile").show();
            $("#AddPAFile").load("include/pAddPA.php?PubCode="+PubCode);
        });
        // ======================================== //
        //        S A V E  F O R M  D A T A         //
        // ======================================== //
        $('.SaveButton').click(function ()
        {
            var Sec  = this.id;
            var Name = $("#"+this.id).data('formname');
            var Form = $("#"+Name);
            var Data = Form.serialize();
            Data = Data + "&Sec="+Sec;
            console.log(Data);
            $.ajax(
            {
                type: "POST",
                url:  "http://{path to file}/DBFunctions.php",
                data: Data,
                dataType: 'JSON',
                success: function(data)
                {
                    // Result message
                }
            });
        }   
    });

Open in new window

DBFunctions.php  (Just to show where it is supposed to go. ... Never gets here.
 
    session_start();
    #====================================================
    include("../include/connect.php");
    $Conn = mysql_connect($HOST, $USER, $PASSWORD) or die(mysql_error());
    mysql_select_db($DBName, $Conn) or die(mysql_error());
    #====================================================
    $Log = array();
    $Error = array();
    $Message = "";
    $ErrorCount = 0;
    switch($_POST[Sec])
    {
        case "ProgPAReg":
        {
            // Save to database
            echo json_encode(array("Message"=>$Message, "Log"=>$Log, "Error"=>$Error));
        } break;
    }

Open in new window

I believe the load()-ed file thinks it is in its' local directory, but I am not totally confident in that, but, as I stated, I put the full url path in for the PHP processing file anyway, so that shouldn't make a difference. Since both the main program and the loaded program are using the same js file (jQueryEdit.js), I tried removing that file and testing which, of course, caused things not to function in the relative file, but seemed to indicate the js file was not the cause of the problem as far as any possible conflicts.

If there is a request going out to the server, it is not getting it. Web Console Network shows nothing. the console.log(Data) in jQueryEdit.js shows that the file is properly serialized.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Advice: Before testing your JavaScript FIRST make sure the endpoint is working.

To do this you can use a number of strategies
1. Simplest - change your POST to GET in your PHP file and then call the script with the form data specified as URL parameters
2. Create a test form that has the fields to be submitted along with default values and post it in the normal way to the end point
3. Download and install PostMan and use that to test your endpoint.

You can get into knots trying to debug AJAX when you don't know if your endpoint is correct - so first confirm that it is working, what the URL is and what the parameters are - after that it is relatively simple to wire it to your AJAX function.

So, first get your AJAX Endpoint working - then lets look at the jQuery that invokes it.

Author

Commented:
By "endpoint", I assume you are talking about the PHP file that receives the request. Yes, that was tested out - actually with and without AJAX. It processed and returned a proper response. This was independent of its present environment.

I'll try using get. I have PostMan, which I use to debug API stuff. Never thought of using it for AJAX. Thanks. I'll do that. Will let you know the results.
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
GET is only suggested because it enables you to use the URL to test - you don't want to be using it in your code.

If the endpoint has been confirmed to work the next thing is to wire up your AJAX to talk to the endpoint.

Important: check the console (F12) for errors while the AJAX is firing.

When the AJAX fires - look at the request - expand it by clicking on it. Then look at the Parameters that were sent to the function, check the response to see if there is anything in that.

Bottom line - if your endpoint works and you send the right data to the endpoint from AJAX - it WILL work - if it does not then you have an error in your script OR you are sending the wrong data.

Just a note in your PHP file DONT ACCESS $_POST directly ... ever!!!

Extract the data from it first and then use it like so
$sec = isset($_POST[Sec]) ? $_POST[Sec] : false;
if ($sec === false) {
   // handle error here
}
 switch($sec)  {

Open in new window

Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

Author

Commented:
The error is in my php process. Haven't figured where yet but that should be easy. I was thrown for a loop because I have pretty extensive error handling and, anyway, the data string was not showing that it was going anywhere in the network setting on my Web console. Still don't know why that was. I created another very basic PHP file and it then showed the request going out. I then tried again with the original file and it worked - at least, I could see a request going out. Response is blank. But this is where the GET came in handy. I had never thought of doing that. Simple and helpful.
I'm sure the AJAX is okay - pretty basic and the same code I am using elsewhere. Somewhere in the PHP file it's just crashing, apparently even without a PHP error. I've determined the section of code - just have to find the problem.

Two things that will definitely benefit me in the future - 1) Put the url in the address bar and see what the result is and 2) PostMan can also be a helpful tool. Pretty basic stuff that never crossed my mind.

I am curious as to why you say not to use POST directly. My usual method, since I will usually use one file for various AJAX requests is to use an "Sec" variable to designate the section, then use a case structure with the default sending back a "Section not found" message. Everything gets converted to standard PHP vars, but I usually use switch($_POST['Sec']). Is there a security reason you recommend against that?

Author

Commented:
I was at a loss when my normal troubleshooting tools were not helping me, staring into the abyss for long periods of time :)

Author

Commented:
The problem was that I had an include file at the top of my php file that it was not finding. This file had several functions that needed to be accessed. So it was crashing when it tried to apply one of those functions.  No error was being returned in either of these instances. I resolved to opening my include files henceforth as follows:
if(!@include('Include File Path and Name')){Error code;}

Open in new window

Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
I am curious as to why you say not to use POST directly.
Because there is no gaurantee that it exists - if you use it and it does not exist you error out.

Also - if you are going to use $_POST for db operations ALWAYS make sure you sanitise the values first - my recommendation is ALWAYS use prepared statements and for this my preference will be PDO over MySQLi. Failing that at least make sure you are escaping the string (real_escape_string) and if possible perform other validation checks.

If you believe that every request to your site is a hack and act accordingly you will be ok.

Included file - that would come out in a direct access call to the script - just need to make sure that your error logging is on - either to the screen or a file and don't use the @ sign to turn errors off.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial