Looking for a list of JavaScript error codes - javascript

Is there a list of JavaScript or jQuery error codes (the kind which, for example, MySQL and MariaDB have)?
I have received an Error 5001, and I have no idea what it means. Will elaborate, if it turns out to be necessary.
EDIT
The reason I'm asking is this. A webapp which I'm partially involved in has recently started returning unusual responses from jQuery AJAX calls. Response is
Error 5001
I have never seen something like this before, and googling for a solution returned this old link.
Even after receiving steps to reproduce the error, my team and I haven't been able to do so.
The code is setup like this:
jQuery
$('#someId').on('change',function() {
var id = $('#otherId').val(); // this is a hidden input field
$.ajax({
url: 'ajax/check.php',
type: 'post',
data: {valId:id}
async: true,
success: function(data) {
if(data=="ok") {
$('#someId').removeClass('blue').addClass('green');
} else {
$('#someId').removeClass('green').addClass('blue');
}
},
error: function(desc, err) {
console.log("Details: "+ JSON.stringify(desc) + "\r\nError: " + JSON.stringify(err);
}
});
});
PHP
$id = preg_replace('/\D/','',(int)$_POST['id']);
if($id < 1 || $id != $_POST['id']) {
echo "no";
die();
}
$date = date('Y-m-d H:i:s');
$mysqli->query("UPDATE mytable SET dateupdated = '".$date."' WHERE id = $id");
if($mysqli->affected_rows < 1) {
echo "no.";
die();
}
echo "ok";
Error logging has been disabled globally, and there's nothing from the PHP side of things, which would printout this error.
If it's of any relevance, the server on which the app is hosted has recently started responding sluggishly, and returning a query such as
SELECT * FROM users ORDER BY datemodified DESC LIMIT 10
requires the users to wait for up to 3 minutes. The database has been optimized and repaired when these issues starting happening, but that didn't help. DB has also been tested on two other unrelated servers (same PHP and MariaDB version), and the same query performed quickly, as expected.

After doing an extensive search through all the files in the entire webapp, it turned out that the error came from a custom error handler in an old custom JS library. Apologies for wasting everybody's time.

https://learn.microsoft.com/en-us/scripting/javascript/reference/javascript-run-time-errors - This might be what you are looking for if you are doing something with Windows Apps.
In your case Error 5001 could be - 5001 Number expected

Related

Error 500 When Updating MySql Database from WordPress - Same Code Works Fine Outside of WordPress

I need to update a MySql database from inside a JS function within a WordPress Woocommerce page. I'm using Ajax to do this. The following code works fine as a stand-alone code but when I put it into the WordPress page (on my localhost) it throws an error 500. Also I put the required data (which will eventually be a variable) onto the end of the url (?test=14230) because I couldn't get it to send the data when using the data: line in the Ajax.
Here's the Ajax:
function db()
{
$.ajax({
url: 'update_db.php?test=14230',
type: 'post',
data: 0,
success: function(output)
{
alert('Success, server says '+output);
}, error: function()
{
alert('Something went wrong.');
}
});
}
Here's the update_db.php:
<?php
if(isset($_GET['test']) ){
$id = $_GET['test'];
}
include 'database-handler.php';
$sql = "UPDATE db_name SET column = 'Some Value' WHERE id = $id";
if(mysqli_query($conn, $sql)){
//echo ('<p>'."Success.".'</p>');
} else {
//echo ('<p>'."Something went wrong. $sql. " . mysqli_error($conn).'</p>');
}
mysqli_close($conn);
?>
So I'm just wondering why this works as a stand-alone code but not when it's inside WordPress?
Edit: Here is the error log:
[Wed Nov 09 15:16:47.543162 2022] [php:error] [pid 4564:tid 1828] [client ::1:5888] PHP Fatal error: Uncaught TypeError: mysqli_query(): Argument #1 ($mysql) must be of type mysqli, null given in C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php:17\nStack trace:\n#0 C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php(17): mysqli_query(NULL, 'UPDATE new_card...')\n#1 {main}\n thrown in C:\xampp\htdocs\my-sites\wowcard\wp-content\themes\blocksy-child\woocommerce\single-product\save-card-size.php on line 17, referer: http://localhost/my-sites/wowcard/product/polka-dot-brush-strokes-two-photo-birthday-card-purple/?card=complete&id=14230
Edit:
I believe the issue I had was due to the Ajax being embedded within more than one WordPress function and also a Woocommerce action. The variable I needed was not being passed from my PHP to the Ajax like it normally would be. I used a session variable instead, which fixed that particular issue.
The Ajax now uses the "data:" line to pass the data over to save-card-size.php rather than passing it inside the url. I would show the code but the editor is too glitchy on this site, it wouldn't allow me to copy and paste my code properly.
I also had to replace the include in save-card-size.php with the contents of database-handler.php.
Everything is now working.
WordPress has its own database handler which is automatically loaded, there are most likely conflicts between your code and WordPress, but without seeing the actual error, I can not give more information.
Check this out https://developer.wordpress.org/reference/classes/wpdb/
Example:
global $wpdb;
$results = $wpdb->query($wpdb->prepare( 'UPDATE db_name SET column = 'Some Value' WHERE id = %d' , $id ));

Error 500, AJAX to PHP using $_POST [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
EDIT:
This is solved. Thank's to everyone who pointed me towards the error log files. Amazing community, this got answered so much faster than I expected.
I'm embarred to say... it was a semicolon.
As a study project, I'm working on a home automation based on a Raspberry Pi.
I installed Apache and built a small website that functions as a GUI. On click, data will be sent via POST-request to ajax.php (in the root folder) which then writes stuff into text files (that then will be read by a python script to do things with the GPIOs - not very elegant, but that's the task now).
Some relevant code:
$("#R0Light1_on").click(function(){
var Value = $(this).val();
var data = {'id': 'R0Light1_on', 'value': Value};
$.ajax({
type: 'POST',
url: 'ajax.php',
data: data,
success: function(){
console.log("#R0Light1_on", data);
$("#R0Light1_on").addClass("on");
$("#R0Light1_off").removeClass("off");
},
error: function() {alert('ERROR: $.ajax #R0Light1_on');}
});
});
<?php
if (isset($_POST['id'])) {
switch ($_POST['id']){
case 'R0Light1_on':
R0Light1_on();
break;
case 'R0Light1_off':
R0Light1_off();
break;
}
}
function R0Light1_on() {
$content = "Not relevant to this Question";
$fp = fopen("/var/www/html/shares/pi/R0Light1_on.txt","wb");
fwrite($fp,$content);
fclose($fp);
exit;
}
function R0Light1_off() {
...
}
?>
<button type="button" id="R0Light1_on" value="1">an</button>
AJAX worked for a month now. 200 ok, all the time and $_POST['id'] did it's job. Then yesterday, it stopped doing so. I don't know what I did, but now it's throwing 500 Internal Server Error messages at me. Even using back-up files doesn't help me and I feel like I read everything Google could find me.
One Thing do I know, though: when I remove the if(isset($_POST['id']))-part, the HTTP-request is successful again (it just also make's the php-script useless, as obvious).
Btw, changing everything to GET doesn't help either (data is visible in URL, but the error stays the same).
Thanks for your time, I'd really appreciate any kind of help.
A 500 error is an internal server error.
You can check your PHP error_log file in the root directory of where the script runs or alternatively at the top of your script, add this to enable error reporting and see the real error that the 500 error translates to:
error_reporting(E_ALL);
#ini_set('display_errors', 1);
It is most likely a PHP fatal error or syntax error.
The issue might be related permissions on the text file, or that it's failing to write to it. Adding permissions to the file would help resolve the issue.
One way to fix this yourself is by checking your apache/php error logs. That should give you a pretty clear indication where the problem lies.

How to make an Excel file an interactive webpage?

How can I make my Excel file work as a web page where people can enter data and it will stay there? I am new to this!
Required technologies for this exercise: JavaScript, JQuery, PHP, AJAX and MySQL. And Excel! All this requires a minor edit, only adding 3 lines of text to the generated html page.
A running demonstration is at https://ip.jawfin.net
I'd like to state that the html of Excel Save As has been badly maligned - Excel 2013 generates a very clean html, its styles are built into the comments (so only 1 file is produced, no CSS), it's well indented and easy to read. The only down-side is the names of classes of the styles are rather arbitrary! No JavaScript, just plain html - it's a nice place to start then refine in Notepad++ or your favourite editor. Mind you, the lack of CSS may come back to bite you, for extensive use I would recommend extracting the comments to build a CSS from.
Firstly, our Excel. Here's one I made, and this is for a simple application which puts your IP in the cell you select on the screen. (My practical use of this method was for a month scheduler, this "pick a colour" is good to demonstrate all the features and I hope will be easily adaptable.) One change though, I scramble the visitor's IP as a protection.
Here's my Excel file: https://ip.jawfin.net/ip.xlsx
We don't export the whole spreadsheet, just select the cells you want which will make up the webpage. In my case: -
With the cells selected, go into File / Save As, pick your folder, Save as Web Page (*.htm), choose only the Selection, give it a Title if desired, name it index.htm and Save!!
Now, rename index.htm to index.php as we will putting php code in it. Now for the 3 lines of code to make this an interactive webpage. Between the </body> and </html> at the bottom insert these 3 lines: -
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<?php include 'excel.php';?>
<script src="excel.js"></script>
so we have: -
</body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<?php include 'excel.php';?>
<script src="excel.js"></script>
</html>
The 1st line importing JQuery for our AJAX to work.
The 2nd is to get the user's IP. Note, this can do a lot more if required, for instance in my implementation I use it to log into a phpBB forum and get the logged-in username and permissions. This php also shows how we can pass server php variables to the local javascript.
The 3rd line is the brains, doing all the work and communicating with the server for updating and fetching data.
(You know, this really could just be one line of code if I embedded the script lines as echo's in the php - but that loses readability in my opinion.)
For the database: on your webserver log into your panel and create a new database for this app.
Then log into your phpMyAdmin to create the table[s] your application needs.
In this case it's one table, called cell_ip. Its structure: -
field:cell; type:integer; index:primary + unique
field:ip; type:text
Or as it appears in phpMyAdmin: -
The files this project uses are: -
index.php the one we just created in Excel, goes in the web folder
excel.php the file which fetches server-side variables (note we could also use this to inject dynamically created controls)
excel.js the script running local interface, also communicates with the server
server.php the database handler on the server, deals with the AJAX requests and database manipulations
settings.php just a means of storing the database configuration in a safe place
All these files go into the root of the web folder, except settings.php which goes in home, the folder above web, where the Internet cannot see it, but our server.php can.
Note the 4 php files are all doing completely different jobs:  index.php is the web page they see, the only user visible php file.  excel.php injects code into index.php, into the webpage, where it can get server-side settings for the client.  server.php is like a program running on the server alone, an application which our webpage calls to save and load data into our server-side database.  settings.php is just a glorified ini file, a quick means of storing sensitive info out of sight from the Internet.
All the source has relevant comments explaining the processes - but I'm willing to answer any questions I can, please note though that I am not an expert. So, without further ado, the work source codes.
(Edit: As I can't fit the full source here I'll provide links. Please let me know if there is a smarter/preferred way. As it is, I renamed these to .txt so it doesn't behave like a webpage!)
index.php - This too big to include, so download, or make it yourself from instructions above.
excel.php
<?php //excel.php
//Let's create a string specific to the user without giving away private info
$ip = $_SERVER['REMOTE_ADDR']; //I'm going with hashing the md5 of their IP, then mod'ing back to 12 digits (from 38)
$hash = fmod(hexdec(md5($ip)),1e12);
echo '<script>'; //clever means of getting a php variable into javascript
echo 'var user_ip = ' . json_encode($hash) . ';'; //replace $hash with $ip you want to see the real address!
echo '</script>';
?>
excel.js
//excel.js
$.ajaxSetup({ cache: false }); //needed to stop IE/Edge from caching AJAX GET requests
var cells = document.getElementsByTagName("td"); //array of all cells, excel assigns them type HTML table cell "td"
var updating = false; //prevent flicker if writing to the dataset and a read overwrites our status messages
var reentry = false; //prevent overlapping refresh. polls 1 a sec, 5 second time-out, could lead to massive overlap!
var addingStr = ' -- Adding IP --'; //const not used for backwards compatibility, IE9 etc.
var removeStr = ' -- Removing IP --';
var replaceStr = ' -- Replacing IP --';
for (var i = 0; i < cells.length; i++) { //you can assign different aspects by the .innerHTML
cells[i].style.cursor = 'cell'; //or 'pointer' - the default is the edit caret cursor which looks ugly
cells[i].id = i; //tag our elements, but note this is happening AFTER the DCOM scan so getElementById() won't work
cells[i].onclick = function() { cellClick(this); };
}
refreshScreen();
setInterval(function() { //ajax poll, refresh every second!
refreshScreen();
}, 1000);
function cellClick(cell) {
updating = true; //don't allow the refresh to remove our status comment in the cell
var mydata = 'action=';
if (cell.innerHTML == "" || cell.innerHTML == " ") {
cell.innerHTML = addingStr;
mydata += 'c'; //write into this cell the users IP
} else {
if (cell.innerHTML == user_ip) { //let's be smart and allow them to remove their own IP :)
cell.innerHTML = removeStr;
mydata += 'd'; //clear/delete this cell
} else { //it's someone else, hijack them!!
cell.innerHTML = replaceStr;
mydata += 'u'; //update this cell
}
}
mydata += '&cell=' + cell.id + '&ip=' + user_ip; //add our parameters
$.ajax({ //JQuery ajax, so much cleaner and safer than using JavaScript ajax
url: "server.php", //our server-side worker
type: 'POST', //database changes, use POST, we don't want a webcrawler or a cache hitting a GET with parameters
data: mydata,
timeout: 5000, //5 second should be ample, but if they lose connectivity allow it to fail
success:
function(data) {
updating = false;
if (data != 1) { //no matter what, in this CRUD only 1 record should have been affected
alert('Data update error. Parameters: ' + data + '. Result: ' + data);
}
refreshScreen(); //refresh screen with new data
},
error:
function(xhr, ajaxOptions, thrownError) { //put better error handling in if this fires too often!
// alert('Data = ' + mydata + '. Error # = ' + xhr.status + '. Message = '+thrownError); //uncommend to debug
updating = false;
refreshScreen();
}
});
}
function refreshScreen() {
if (updating) return; //just wait a second
if (reentry) return; //we're already pending a refresh
reentry = true;
var mydata = 'action=r'; //we want to Read the data - stored in a varible in case we turn on our error alert
$.ajax({
url: "server.php",
type: 'POST',
data: mydata,
timeout: 5000,
// dataType: 'json', //just saves us a line of formatting text on success. !!commented out, not debug friendly
success: function(data) { //on recieve of reply
reentry = false;
if (updating) return; //they clicked between the request and the return here, just wait it out, next second!
data = JSON.parse(data); //i prefer this instead of dataType:'json' so I check server script errors in the throw
var results = []; //get our data into a 2 dimensional array (has 2 dimensions as our query returned 2 fields
for(var x in data) { //get all the data ready before we touch the screen, cut down any possibly latency
results.push(data[x]);
}
for (var i = 0; i < cells.length; i++) { //reset screen
if (cells[i].innerHTML != removeStr) { //skipping the "Remove" messages (dirty read) - will clean up below if they were removed!
cells[i].innerHTML = ""; //clear field
}
}
for (var i = 0; i < results.length; i++) { //now we stuff our cells with the IPs we have
cells[results[i][0]].innerHTML = results[i][1]; //first array element is cell number, the second is the IP
}
//as the "Remove" status was skipped above need to loop again to clear any found
for (var i = 0; i < cells.length; i++) { //backwards clean
if (cells[i].innerHTML == removeStr) { //text is here as this cell didn't come through the SELECT
cells[i].innerHTML = ""; //clear field
}
}
},
error:
function(xhr, ajaxOptions, thrownError) { //uncomment alert for debugging
reentry = false;
// alert('Query = ' + mydata + '. Error # = ' + xhr.status + '. Message = '+thrownError);
//Note that xhr.status == 200 is an OK from the server but JSON invalid, so check for that first!
}
});
}
server.php
<?php //server.php
if (!isset($_POST['action'])) exit; //no action parameter, just leave. could echo an error message if required though
$action = $_POST['action'];
if (!strpos(' crud',$action)) { //note the space out front, or else it'll fail on 'c' as it returns zero, which = false
echo("Unknown action='$action'"); // took me ages to debug that, resulting in this line of code!!!!
exit; //otherwise not one of ours, quit before SQL stuff starts
}
require "../settings.php"; //lazy place to easily store settings out of reach from the Internet, parent of the web root.
//Be aware I used ".." - if this server.php is not in the webroot then the database.php is not out of reach.
//Note this method is easier than loading an .ini file and parsing it within an array.
if ($db_server == "") { //ASSERT: this should never fire as the require would fail on not find, but can't be too sure
echo "Problem getting database settings.";
exit;
}
$connection = mysql_connect($db_server, $db_username, $db_password); // Establishing Connection with Server
if (!$connection) {
echo "Error connecting to database.";
exit;
}
$db = mysql_select_db($db_database_ip, $connection); // Selecting Database
if (!$db) {
echo "Specific database not found.";
exit;
}
if ($action == 'c') { //note this will fail if there is a blank record against this cell, so check here
$cell = mysql_real_escape_string($_POST['cell']); //extract our parameter
$ip = mysql_real_escape_string($_POST['ip']);
if ($ip == "") {
echo "Cannot add blank IP in cell '$cell'";
} else {
$query = mysql_query("INSERT INTO cell_ip(cell, ip) values ('$cell', '$ip')"); //Create Query
echo $query; //always return the result, even if its unexpected. can hold error messages for debugging
}
}
if ($action == 'r') { //JSON our database back to the client.
//Note I am using the POST protol instead of GET, tidier on this server.php keeping all my server requests in one file
$result = mysql_query("SELECT cell, ip FROM cell_ip"); //Read Query
while ($row = mysql_fetch_row($result)) {
$table_data[] = $row;
}
echo json_encode($table_data); //return the whole dataset
}
if ($action == 'u') { //pinching someone else's cell with our ip, make sure the new ip exists too
$cell = mysql_real_escape_string($_POST['cell']);
$ip = mysql_real_escape_string($_POST['ip']);
if ($ip == "") {
echo "Cannot edit to a blank IP in cell '$cell'";
} else {
$query = mysql_query("UPDATE cell_ip SET ip = '$ip' WHERE cell = '$cell'"); //Update Query
echo $query;
}
}
if ($action == 'd') { //delete this cell
$cell = mysql_real_escape_string($_POST['cell']); //extract our parameter
$query = mysql_query("DELETE FROM cell_ip WHERE cell = '$cell'"); //Delete Query
echo $query;
}
mysql_close($connection); //Note this was never opened if the caller failed the "action" validation, being polite to our sql
?>
settings.php (this goes in root home, change the values in this to suit)
<?php //settings.php
$db_server='localhost';
$db_username='root';
$db_password='root_password';
$db_database_ip='excel_ip';
?>
Things to note: -
If your database relies on the cell number they may change if you edit your Excel and republish the html.
This demo relies on the cell numbers only because it is only a demo - for instance you could put text in the cells and use that to identify your relevant cells.
If you run your server on CloudFlare and change any of your .js or .php they get cached, so you need to purge those files on the CloudFlare (Caching) after you upload them.
SECURITY!!! Your JavaScripts will be available to the end user, they cannot not be, as JS runs on the client - not matter how packaged or encrypted they can be discovered. Do not have passwords or intellectual property in them. This also means your AJAX requests can be launched maliciously, be sure to put extensive handling and filtering in your server-side php's. I would also recommend employing a token + session handler to validate the calling client.
Final note: I wrote this for 2 reasons. First I wanted to read this in 10 years time so I can see how hacky and newby I am now (this is my second day as a web developer), and secondly I do not wish anyone to go through the shameful and humiliating experience which I did when asking for help on this project on StackOverflow (you won't find my question about that though, it got deleted). I hope this post is useful to somebody, I spent a whole day on designing it :)

Why am I getting this Internal Server Error in the Laravel Framework?

I have come across a situation that doesn't make much sense to me. Just as some background information, I'm using the Laravel framework. The page in question calls a query when the page is requested using Laravel's '->with('var', $array)' syntax. This query (which I will post later) works perfectly fine on page load, and successfully inserts dummy data I fed it.
I call this same query via an Ajax $.post using jQuery, on click of a button. However, when I do this $.post and call this query, I get an Internal Server Error every time. Everything is exactly the same, information passed included; the only difference seems to be whether or not it is called on page load or via the $.post.
Here is the error:
Below is the code that performs the query on page load:
routes.php sends the HTTP get request to a file called AppController.php
routes.php
AppController.php
The page is then made with the following array acquired from DeviceCheckoutController.php
Which then goes to DeviceCheckout.php
I am able to echo $test on the page, and it returns the ID of a new row every time the page is reloaded (which obviously mean the 'insertGetId' query worked). However, I hooked this query up to the page load just to test. What I really want to happen is on click of a button. Here is the code for that:
$("#checkoutFormbox").on('click', '#checkoutButton', function() {
var checkoutInformation = Object();
var accessories = [];
var counter = 0;
var deviceName = checkoutDeviceTable.cell(0, 0).data();
$(".accessoryCheckbox").each(function() {
//add accessory ID's to this list of only accessories selected to be checked out
if($(this).val() == "1")
{
accessories[counter] = $(this).data('id') + " ";
}
counter++;
});
checkoutInformation['deviceID'] = $(".removeButton").val(); //deviceID was previously stored in the remove button's value when the add button was clicked
checkoutInformation['outBy'] = '';
checkoutInformation['outNotes'] = $("#checkOutDeviceNotes").val();
checkoutInformation['idOfAccessories'] = 2;
checkoutInformation['dueDate'] = $("#dueDate").val();
if($("#studentIdButton").hasClass('active'))
{
checkoutInformation['renterID'] = 0;
checkoutInformation['emplid'] = 1778884;
console.log(checkoutInformation);
$.post("http://xxx.xxx.xxx.xxx/testing/public/apps/devicecheckout-checkoutdevices", {type: "checkoutDeviceForStudent", checkoutInformation: checkoutInformation}, function(returnedData) {
alert(returnedData);
});
}
});
Which is also then routed to AppController.php, specifically to the 'checkoutDeviceForStudent' part of the switch statement:
And then back to that query that is shown previously in DeviceCheckout.php
Finally, here is my DB structure for reference:
Any explanation as for why this would be happening? Also, any Laravel or other general best practice tips would be greatly appreciated as I'm inexperienced in usage of this framework and programming overall.
Sorry for such a long post, I hope there is enough information to diagnose this problem. Let me know if I need to include anything else.
Edit: Included picture of error at the top of the page.
Everything is exactly the same, information passed included
No, it isn't. If it was exactly the same you wouldn't be getting the error you're getting.
These sorts of issues are too difficult to solve by taking guesses at what the problem might be. You need to
Setup your system so Laravel's logging errors to the laravel.log file
Setup you PHP system so errors Laravel can't handled are logged to your webserver's error log (and/or PHP's error log)
Put Laravel in debug mode so errors are output the the screen, and the view the output of your ajax request via Firebug or Chrome
Once you have the actual PHP error it's usually pretty easy to see what's different about the request you think is the same, and address the issue.
I found a resolution to my problem after some advice from a friend; much easier than I anticipated and much easier than any solution that has been offered to me here or other places.
Essentially, what I needed to do was place a try, catch clause in my model function, and then if an exception is encountered I store that in a variable, return it, and use console.log() to view the exception. Here is an example to emulate my point:
public function getUserFullname($userID)
{
try
{
$myResult = DB::connection('myDatabase')->table('TheCoolestTable')->select('fullName')->where('userID', '=', $userID)->get();
return $myResult;
}
catch(Exception $e)
{
$errorMessage = 'Caught exception: ' . $e->getMessage();
return $errorMessage;
}
}
And then on the View (or wherever your model function returns to), simply console.log() the output of your POST. This will display the results of the successful query, or the results of the Exception if it encountered one as opposed to an unhelpful Internal Server Error 500 message.

Connecting to a server-side SQL database via php with jquery

I have been trying to look over an example to figure out how to connect to a server's SQL database from a client using JQuery, AJAX, and PHP, and though it is old it seems well done and straight forward: Example Link.A single folder contains all of my php files as well as the product version of jQuery (javascript-1.10.2.min.js).
Problem 3 - Fixed
JS console shows [Object, "parsererror", SyntaxError] at
var id = data.data[0]; //get id, data['data'][0] works here as well
in client.php. Object responseText shows ..."No Database Selected"... I have updated my client.php based on Daedalus' response and am still getting the same error.
Error was in mislabeling a variable ($link instead of $con) in server-api.php
-- Code --
db-connect.php:
<?php
//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "root";
$pass = "password";
$databaseName = "server-db";
$tableName = "inventory";
?>
server-api.php:
<?php
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'db-connect-99k.php';
$con = mysql_connect($host,$user,$pass);
$db_selected = mysql_select_db('zgc7009_99k_db', $con);
$array = array('mysql' => array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con)));
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); //query
$array['mysql'][] = array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con));
$array['data'] = mysql_fetch_row($result); //fetch result
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($array);
?>
client.php
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>
<body>
<!-------------------------------------------------------------------------
1) Create some html content that can be accessed by jquery
-------------------------------------------------------------------------->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'server-api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
//dataType: 'json', //data format (comment out or get parsererror)
// Successful network connection
// Successful network connection
success: function(data) //on recieve of reply
{
var id = data.data[0]; //get id, data['data'][0] works here as well
var vname = data.data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
$('#error_code').html("Success!");
},
error: function() {
console.log(arguments);
}
});
});
</script>
</body>
</html>
Problem 1 - Fixed
Thanks to user help, I have managed to get rid of my original error of:
OPTIONS file:///C:/Users/zgc7009/Desktop/Code/Web/php/server-api.php No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. jquery.js:8706
XMLHttpRequest cannot load file:///C:/Users/zgc7009/Desktop/Code/Web/php/server-api.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Problem 2 - Fixed [now running on temporary web server (see link at bottom)]
Now I am running WAMP (including phpmyadmin and apache) as my webserver. I can run my php page with script (client.php) no problem, it runs, can't seem to find any errors in my logs. However, I still never seem to hit the success function of my script. I am assuming that I have inappropriately set something somewhere (eg localhost/"my site".php) but I am not sure where.
I also tried changing my AJAX function a bit, to include .done:
$.ajax({
url: 'localhost/server-api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
// Successful network connection
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
}
}).done(function() {
$('#output').html("AJAX complete");
});
but my output value never gets changed within the ajax call. I could be implementing .done incorrectly, but I just can't seem to figure out why I am not hitting anything and can't seem to find a log that is a help in finding the next step.
On previous edit I removed localhost from php calls ('localhost/server-api.php' returned a 404) and now I am stuck again. I get a 304 Not Modified from my jQuery call, but I thought that, as of jQuery 1.5 ajax handled this as a success so I should still be hitting my html text update (correct?) and I don't.
WAMP access Log:
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /client.php HTTP/1.1" 200 2146
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /jquery.js HTTP/1.1" 304 -
127.0.0.1 - - [14/Jan/2014:14:22:45 -0500] "GET /server-api.php HTTP/1.1" 200 38
Note - this is the only log that updates when I refresh client.php in my browser. my js console stays blank. I have uploaded this to a temp site: zgc7009.99k.org/client-99k.php
Forgive me if the following is drawn out, but I wish to explain all that I can;
Firstly, as noted in comments, the error method of the jQuery .ajax() method only gets called if there is an error when the method attempts to load the requisite php page you(or it(if you don't specify a url, it uses the current page)) has specified. An error in this regard would be something like a 404(page not found), 500(server error), or what-have-you.
The current error you are experiencing is two-fold:
You are not running a server on your computer(or you are and aren't accessing the page via the correct url in your browser(it should be localhost/path/to/file.extension)
Same origin policy is preventing your page from even being loaded
In regards to problem #1, a php page needs to be processed by your php interpreter, which you need to have installed on your system. I would recommend something like xampp to suit this case, though there are plenty others available.
When accessing a server which is running on your machine, one uses the localhost url in the address bar, no protocol(http://,https://,ftp://,etc), and never a file:/// protocol. For example, if I were to visit the folder test's index.php file, it would be localhost/test/index.php.
In regards to problem #2, browsers have various restrictions in place in order to prevent malicious code from executing.. One of these restrictions is the Same Origin policy, a policy which restricts documents of a differing origin than the originating request from accepting that request. For example..
If we have a server at domain.website.com, and it makes a request to otherdomain.website.com, the request will fail as the endpoint of the request is on a different domain.
Likewise, the same exists for any requests made in regards to a file:/// protocol.. It is always1 treated as a different origin, and it will always1 fail. This behavior can be changed, but it is not recommended, as it is a security hole.
I also recommend you check out MDN's article on SOP.
Of course, to fix all this.. install a web server(like xampp or wamp) on your machine(depending on your OS) or use a hosted web server, never open your html file by double clicking it, but by visiting its url(according to your webserver's directory(it differs per server)), and always make sure your domains and ports match.
1: Except in certain cases, such as here
Edit 1:
Don't know why I didn't see this before; we could have avoided headaches.. anyway, firstly, change the error catching you do here:
$dbs = mysql_select_db($databaseName, $con);
echo mysql_errno($con) . ": " . mysql_error($con). "\n";
To:
$array = array('mysql' => array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con)));
And then, change your array set after your db handling to this:
$result = mysql_query("SELECT * FROM $tableName"); //query
$array['mysql'][] = array('errno' => mysql_errno($con), 'errtxt' =>mysql_error($con));
$array['data'] = mysql_fetch_row($result);
To explain what I've changed, and why.. Your first echo was causing the json parser to fail when parsing your echoed json. If you didn't have your console open during your refresh, you wouldn't have seen that it did in fact execute the ajax request. You also do not define an error handler, so you would have never known. In order to parse the new json I just created above, modify your success handler's variable declarations above into this:
var id = data.data[0]; //get id, data['data'][0] works here as well
var vname = data.data[1]; //get name
Of course, if your mysql causes any errors, you can then access those errors with the following:
console.log(data.mysql);
Again, in your success function. To see if you have any errors with the actual .ajax() method or such, you can just do this for your error handler:
error: function() {
console.log(arguments);
}
please you should start learning to PDO or Mysqli real fast, mysql_* will soon be depreciated, that is soonest, let me rewrite your query for you using PDO and prepared statements, you can kick it off from there.
$connectionStr = 'mysql:host='.$host.';dbname='.$databaseName.'';
$driverOptions = array();
$dbh = new PDO($connectionStr, $user, $pass, $driverOptions);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$query = $dbh->prepare("SELECT * FROM $tableName");
$query->execute();
$array = fetch(PDO::FETCH_OBJ);
echo json_encode($array);

Categories

Resources