0

I am using a form to submit and update my database sitting on an external server. When I place all the files on the same server (PHP and html), I am able to update without any issues. But when I separate it out, leaving only the php file on the server and operating the html files from my computer, I am no longer able to update.

The first alert("submit") in the JavaScript doesn't even fire off when I click submit for the form. I can't keep all the files on the server as the html part is to be converted to a HTML5 app. Is there anyway I can resolve this being abel to keep the files separate.

HTML Code

<html>
    <head>
        <title></title>
        <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
        <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    </head>
    <body>
        <form method="post" id="infoForm">
            <input type="text" name="first_name" id="first_name" value="" placeholder="First Name"  />
            <input type="text" name="last_name" id="last_name" value="" placeholder="Last Name"  />   
            <input type="text" name="email" id="email" value="" placeholder="Email"  />
            <button type="submit">Submit</button> 
        </form>

        <script>
            $('#infoForm').submit(function() {
                alert("submit");
                var postTo = 'http://www.examplesite.com/add.php';

                $.post(postTo,({first_name: $('[name=first_name]').val(), last_name: $('[name=last_name]').val(), email: $('[name=email]').val()}),
                function(data) {
                    alert("data is " + data);
                    if(data != "") {
                        // do something
                    } else {
                        // couldn't connect
                    }
                    },'json');
                return false;

            });
        </script>
    </body>
</html> 

PHP Code:

<?php

$server = "localhost";
$username = "user";
$password = "pass";
$database = "db";

$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());

mysql_select_db($database, $con);

$firstname = mysql_real_escape_string($_POST["first_name"]);
$lastname = mysql_real_escape_string($_POST["last_name"]);
$email = mysql_real_escape_string($_POST["email"]);

$sql = "INSERT INTO personnel (first_name, last_name, email) ";
$sql .= "VALUES ('$firstname', '$lastname', '$email')";

if (!mysql_query($sql, $con)) {
    die('Error: ' . mysql_error());
} else {
    echo "Comment added";
}

mysql_close($con);
Trevor_zam
  • 592
  • 2
  • 7
  • 21
  • This can helps: http://stackoverflow.com/questions/33251197/sending-data-to-php-using-ajax/ – TSV Oct 23 '15 at 16:37
  • I'm not entirely sure how that is the same issue. – Trevor_zam Oct 23 '15 at 16:44
  • You are posting data in form-style, imho it is better to transfer data as serialized JSON. – TSV Oct 23 '15 at 16:47
  • Will look into that. More importantly looking to figure out how I can make the update when files are not residing together on the server. – Trevor_zam Oct 23 '15 at 16:49
  • If i understand you right, you can enable CORS (enable cross-origin resource sharing) if your server and client reside on different domains. – TSV Oct 23 '15 at 16:52
  • I have a .htacess file alongside the php file which sets the Access-Control-Allow-Origin to * which I believe resolves the CORS issue. – Trevor_zam Oct 23 '15 at 16:57
  • The alert fires fine here: http://jsbin.com/tokuno/1/edit?html,output — I can't reproduce the problem. – Quentin Oct 23 '15 at 20:03
  • Are you keeping the files separate? Everything works fine when I keep them together on my server. Nothing happens when I pull out the html file to use it from my computer. – Trevor_zam Oct 23 '15 at 20:04
  • @TSV — JSON would be more work to generate, more work to decode, and couldn't be generated by the plain HTML fallback that [should be provided](https://en.wikipedia.org/wiki/Unobtrusive_JavaScript) because [JavaScript sometimes fails](http://kryogenix.org/code/browser/everyonehasjs.html). It wouldn't be better. – Quentin Oct 23 '15 at 20:05
  • @Trevor_zam — "Use from your computer" — are you loading it from your hard disk without a web server? Does your error console complain that `$` is undefined? – Quentin Oct 23 '15 at 20:05
  • **Warning**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). – Quentin Oct 23 '15 at 20:07
  • [The HTML5 placeholder attribute is not a substitute for the label element](http://www.456bereastreet.com/archive/201204/the_html5_placeholder_attribute_is_not_a_substitute_for_the_label_element/) – Quentin Oct 23 '15 at 20:07
  • @Quentin The php file is currently at an external server. My html file is on my harddisk. – Trevor_zam Oct 23 '15 at 20:09
  • @Trevor_zam — That doesn't answer my questions. Are you loading it from a web server on your computer (i.e. `http://localhost/`) or not (i.e. `file:///home/username/etc`)? What does the Console in your developer tools say? – Quentin Oct 23 '15 at 20:10
  • @Quentin Hm is this clearer - php file is at a domain like http://www.example.com/add.php. index.html is on my desktop. – Trevor_zam Oct 23 '15 at 20:12
  • If you copy/paste the URL from your browser's address bar, does it start with `http://`? What does the Console in your browser's Developer Tools say? (Do you know what the Developer Tools are or how to access them?) – Quentin Oct 23 '15 at 20:13
  • @Quentin using firebug. The index file location is file:///C:/Users/userName/Desktop/index.html – Trevor_zam Oct 23 '15 at 20:14
  • I would expect the code to break if the URL starts with `file:///` and I would expect Anton F's answer (though it is woefully lacking anything resembling an explanation) to solve the problem. What does the Console in Firebug say? It should be moaning that `$` is undefined. (And the Net tab should show it failing to load jQuery and jQuery migrate) – Quentin Oct 23 '15 at 20:16
  • @Quentin under console I'm watching 'All', both before and after pressing submit - no errors. <- DISREGARD. Give me asec – Trevor_zam Oct 23 '15 at 20:17
  • @Quentin I don't get it. Everything works fine if I place html file on server too. The error is "$ is not defined" Is it possible to just disregard all my code and get one very simple working example connecting to an external server. Been at it for hours n trying to figure out via multiple guides online. Just aint happening. – Trevor_zam Oct 23 '15 at 20:20
  • `file:///code.jquery.com/jquery-1.11.3.min.js` doesn't exist. See Anton F's answer. – Quentin Oct 23 '15 at 20:21
  • Couldnt reproduce bug either. The only problem i got is $ is undefined. BTW added a little explanation to my answer. – Anton F Oct 23 '15 at 20:28

1 Answers1

1

You saying that even alert is not firing. Check if jQuery is loaded properly. Try changing while runing from localhost:

//code.jquery.com/jquery-1.11.3.min.js to http://code.jquery.com/jquery-1.11.3.min.js

That is because browser serving files localy doesn't know that it should load external libraries from web. Explicitly setting protocol will make him search for them not in the filesystem, but load via url.

Anton F
  • 328
  • 1
  • 8
  • Tried no difference. Jquery loads fine when the files are together btw. Thus don't think that is the issue. – Trevor_zam Oct 23 '15 at 20:06