So I built the code for a web application on WAMP (my first time using any server stuff) and a test database we made looking at the client's databases. When trying to implement, we have run into a lot of trouble. They are using an enterprise server (NOTE: I have no idea what I am talking about here) and MSSQL where I just used localhost, root, and no password on WAMP with MYSQL. I have no idea how to help them get the product implemented. It works fine on my computer but for them, it says Bad Request 400 when I have AJAX print out the error text.
ajax request
$.ajax({
type: "GET",
url: "getJobList.php",
data: "hline="+lineLabel[currentLine],
dataType: "json",
success: function(data){
//do successful stuff
}
}
php file
<?php
include "config.php";
$con = mysql_connect($host);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$hline=$_GET["hline"];
if (empty($hline)){
echo "1"; //default rate
}
else{
$db=mysql_pconnect($host, $user, $pass);//connect to local database
mysql_select_db($databaseName, $db);//select the database you want to use
if (!$db){
echo ("error connecting to database");
}
else{
//connection successful
$sql = " SELECT partparameters.cspc,processingrate,setuptime,lotsize,duedate,duetime,homeline
FROM jobs
INNER JOIN partcoding
ON jobs.partnumber=partcoding.partnumber
INNER JOIN partparameters
ON partcoding.cspc=partparameters.cspc
WHERE homeline = '$hline'
ORDER BY duedate,duetime ASC";//sql string command
$result=mysql_query($sql) or die (mysql_error());//execute SQL string command
//result contains rows
$arr = array();
$num = 0;
while($rows = mysql_fetch_array($result))
{
$array[$num] = $rows;
$num++;
}
echo json_encode($array);
}
}
?>
php config file
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "gmdata1";
?>
Any ideas? Thanks in advance!
EDIT: Fixed a stray parenthesis that I mistyped when posting. Also if it makes a difference I developed on Chrome and the Users are using Firefox. I dont think it should make a difference though because they render the same.
EDIT 2:
Request URL:
http://usmmcsa0wwt01/ProdSched/getJobList.php?hline=G%20%201
Request Method:
GET
Status Code:
HTTP/1.0 400 Bad Request
Request Headers
15:24:24.000
X-Requested-With:XMLHttpRequestUser-Agent:Mozilla/5.0 (Windows NT 6.1; rv:20.0) Gecko/20100101 Firefox/20.0Referer:http://usmmcsa0wwt01/ProdSched/index.phpHost:usmmcsa0wwt01Connection:keep-aliveCache-Control:max-age=0Accept-Language:en-US,en;q=0.5Accept-Encoding:gzip, deflateAccept:application/json, text/javascript, */*; q=0.01
Response Headers
Δ2ms
Server:CIMPLICITY-HttpSvr/1.0Date:Mon, 22 Apr 2013 19:24:24 GMT
This is what I get in their firefox console inspect HTTP request
Your data is wrong. To pick up $_GET["hline"] you either want hline="+lineLabel[currentLine] in the URL (not recommended) or format the data correctly.
data: {"hline": lineLabel[currentLine]},
Try this -
$.ajax({
type: "GET",
url: "getJobList.php",
data: {"hline": lineLabel[currentLine]},
dataType: "json",
success: function(data){
//do successful stuff
}
}
Related
I'm trying to retrieve the latest video ID number from my database and then use that ID number to hashchange my URL and display the corresponding video. My PHP is working and returning a result but I'm not sure how to take that result and use it in jQuery so that I can use it for the hashchange. I haven't used jQuery much before so any detailed help would be amazing! Please find my current code below. The main question I have is how do I pass the $vidarray to jQuery so I can use that variable?
videoprocess.php
<?php
// Connect To DB
$hostname="localhost";
$database="MYDB";
$username="root";
$password="";
#$conn = mysqli_connect($hostname, $username, $password)
or die("Could not connect to server " . mysql_error());
mysqli_select_db($conn, $database) or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
// Display Error message if fails
echo 'Error, could not connect to the database please try again again.';
exit();
}
$query = "SELECT VIDEOID FROM JubileeTouchVideo ORDER BY ID DESC LIMIT 1";
$result = mysqli_query($conn, $query) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$vidarray = array();
while($row = mysqli_fetch_assoc($result))
{
$vidarray = $row;
}
echo json_encode($vidarray);
//close the db connection
mysqli_close($conn);
?>
videoprocess jquery
$.ajax({
url: "data.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//Not sure what to do after this
}
});
This is how you can pass data to ajax.
$.ajax({
type: "POST",
url: url,
data: <?php echo $vidarray["id"]; ?>,
dataType: "text",
success: function(result) {
//result downloaded so we call parseJSON function
//and pass downloaded result
var json = $.parseJSON(result);
//Not sure what to do after this
}
});
Basically I have a php script located on a sever that generates a JSON file listing places from a mysql database. Using jQuery Mobile I am developing an application to display these places. My code works in Chrome & Safari, however when I port it over to Phonegap it doesn't work. I have searched all over the internet but can't find an answer :(.
The php file for generating JSON (json.php):
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "xxx";
$password = "xxx";
$database = "xxx";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT * FROM places ORDER BY name ASC";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
My Javascript file located within my app (Loads JSON and displays it):
$('#places').bind('pageinit', function(event) {
getPlaces();
});
function getPlaces() {
var output = $('#placeList');
$.ajax({
url: 'http://www.mysite.com/json.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<li><a href="">'+item.name+'<span class="ui-li-count">'
+ item.checkins+'</span></a></li>';
output.append(place);
});
$('#placeList').listview('refresh');
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
The HTML looks like this:
<div data-role="content">
<h3>Places</h3>
<ul data-role="listview" id="placeList" data-inset="true">
</ul>
</div><!-- /content -->
This code works in Chrome & Safari, however when run in the xCode simulator with Phonegap it doesn't load the JSON.
Any help would be much appreciated :)
I don't think the problem has anything to do with the server code (PHP), unless you are producing invalid JSON. The question should be tagged with JavaScript rather than PHP. Anyway, there is an excellent article describing a very similar type of application. It even includes sample code. Have a look:
Sample Application using jQuery Mobile and PhoneGap
Dude,
That's server side script it won't run unless its hosted on a server with those languages implemented. I'm running into a similar problemn One suggestion was to implmented the AJAX to fetch the data from a php site an return the data. I'm look'n to just forward the whole page over too a Safari webview window (which you have to set in phonegap permissions). Problem there is I get all the Safari chrome on the top and bottom trying to figure out how to trim that so I don't have to recode with AJAX to pull PHP data server side.
Basically I have a php script located on a sever that generates a JSON file listing places from a mysql database. Using jQuery Mobile I am developing an application to display these places. My code works in Chrome & Safari, however when I port it over to Phonegap it doesn't work. I have searched all over the internet but can't find an answer :(.
The php file for generating JSON (json.php):
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "xxx";
$password = "xxx";
$database = "xxx";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT * FROM places ORDER BY name ASC";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
My Javascript file located within my app (Loads JSON and displays it):
$('#places').bind('pageinit', function(event) {
getPlaces();
});
function getPlaces() {
var output = $('#placeList');
$.ajax({
url: 'http://www.mysite.com/json.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<li><a href="">'+item.name+'<span class="ui-li-count">'
+ item.checkins+'</span></a></li>';
output.append(place);
});
$('#placeList').listview('refresh');
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
The HTML looks like this:
<div data-role="content">
<h3>Places</h3>
<ul data-role="listview" id="placeList" data-inset="true">
</ul>
</div><!-- /content -->
This code works in Chrome & Safari, however when run in the xCode simulator with Phonegap it doesn't load the JSON.
Any help would be much appreciated :)
This has probably something to do with the whitelisting, Apple has no faith in any type of uncontrollable data (like iframes or feeds). So they reject every external connection.
Take a look at phonegap.plist in your project rootfolder (xcode) and add your website url to the array 'ExternalHosts'. This will probably work fine after.
I am working on a PhoneGap with Android project. I have designed a login page in which I want to show an alert box for a valid and invalid user. I am using PHP for database validation.
This is my php page:
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id, name,password FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
This is my java script function:
function onDeviceReady(){
var output = $('#output');
var id = document.getElementById('userid').value;
var pass = document.getElementById('password').value;
// webcam.set_api_url( 'test.php?filename=' + escape(filename));
$.ajax({
url: 'http://192.168.1.214/sample/dologin.php?id='+id+'&password='+pass,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
console.log('entered success============');
$.each(data, function(i,item){
var logi=item.id;
if(logi!=null)
alert("valid user");
else
alert("invalid user");
});
},
error: function(){
console.log('entered success====================');
output.text('There was an error loading the data.');
}
});
}
This is not working properly for an invalid user. Whenever I enter a valid user name and password then it displays the valid user message box. When I enter an invalid user name and password then it doesn't display anything.
Thank you in advance...
Try debugging this in a browser and perhaps send the returned jsonp data to the console from within your ajax's success call console.log(data).
It's quite possible that your jsonp is returning some data as opposed to null... even if it is simply undefined or an empty string. Your conditional is most likely the culprit.
I am trying to pull latitude and longitude values from another server on a different domain using a singe id string. I am not very familiar with JQuery, but it seems to be the easiest way to go about getting around the same origin problem. I am unable to use iframes and I cannot install PHP on the server running this javascript, which is forcing my hand on this.
My queries appear to be going through properly, but I am not getting any results back. I was hoping someone here might have an idea that could help, seeing as I probably wouldn't recognize most obvious errors here.
My javascript function is:
var surl = "http://...omitted.../pull.php";
var idnum = 5a; //in practice this is defined above
alert("BEFORE");
$.ajax({
url: surl,
data: {id: idnum},
dataType: "jsonp",
jsonp : "callback",
jsonp: "jsonpcallback",
success: function (rdata) {
alert(rdata.lat + ", " + rdata.lon);
}
});
alert("BETWEEN");
function jsonpcallback(rtndata) {
alert("CALLED");
alert(rtndata.lat + ", " + rtndata.lon);
}
alert("AFTER");
When my javascript is run, the BEFORE, BETWEEN and AFTER alerts are displayed. The CALLED and other jsonpcallback alerts are not shown.
Is there another way to tell if the jsoncallback function has been called?
Below is the PHP code I have running on the second server. I added the count table to my database just so that I can tell when this script is run. Every time I call the javascript, count has had an extra item inserted and the id number is correct.
<?php
header("content-type: application/json");
if (isset($_GET['id']) || isset($_POST['id'])){
$db_handle = mysql_connect($server, $username, $password);
if (!$db_handle)
{
die('Could not connect: ' . mysql_error());
}
$db_found = mysql_select_db($database, $db_handle);
if ($db_found)
{
if (isset($_POST['id'])){
$SQL = sprintf("SELECT * FROM %s WHERE loc_id='%s'", $loctable, mysql_real_escape_string($_POST['id']));
}
if (isset($_GET['id'])){
$SQL = sprintf("SELECT * FROM %s WHERE loc_id='%s'", $loctable, mysql_real_escape_string($_GET['id']));
}
$result = mysql_query($SQL, $db_handle);
$db_field = mysql_fetch_assoc($result);
$rtnjsonobj -> lat = $db_field["lat"];
$rtnjsonobj -> lon = $db_field["lon"];
if (isset($_POST['id'])){
echo $_POST['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
}
if (isset($_GET['id'])){
echo $_GET['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
}
$SQL = sprintf("INSERT INTO count (bullshit) VALUES ('%s')", $_GET['id']);
$result = mysql_query($SQL, $db_handle);
$db_field = mysql_fetch_assoc($result);
}
mysql_close($db_handle);
} else {
$rtnjsonobj -> lat = 404;
$rtnjsonobj -> lon = 404;
echo $_GET['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
}?>
I am not entirely sure if the jsonp returned by this PHP is correct. When I go directly to the PHP script without including any parameters, I do get the following.
({"lat":404,"lon":404})
The callback function is not included, but that much can be expected when it isn't included in the original call.
Does anyone have any idea what might be going wrong here?
Thanks in advance!
Change this part of the code
jsonp: "jsonpcallback",
with:
jsonpCallback : "jsonpcallback",