PHP-AJAX-JSON Notice: Undefined index : - php

I'm trying to make a test page for sending google map cordinates to populate a mysql database. I'm using ajax to send data to php. Firebug shows that the data is sending. But this php error comes out. And the mysql database is populating without the map cordinates.
Here's the Ajax function:
function sendData(geodata){
var hr = new XMLHttpRequest();
hr.open("POST","getdata.php",true);
hr.setRequestHeader("Content-type","application/json");
if(hr.readyState==4 && hr.status==200){
var data = JSON.parse(hr.responseText);
alert("Data received about "+data);
}//end if
hr.send("geodata="+geodata);
}//close sendData
This is the PHP page.
<?php
header("Content-Type : application/json");
$loc = $_POST["geodata"];
$username="root";
$password="";
$database="location";
$connection = mysql_connect('localhost',$username,$password);
if(!$connection){
die('Unable to connect to the server '.mysql_error());
}
$selectdb = mysql_select_db($database);
if(!$selectdb){
die('Unable to connect to database'.mysql_error());
}
$query = "INSERT INTO `location_data`(`ltlng`) VALUES ('".$loc."')";
$result = mysql_query($query);
if(!$result){
die('Invalid query : '.mysql_error());
}
?>
Then the following errors comes out.
( ! ) Notice: Undefined index: geodata in C:\wamp\www\IndustryProject\SampleDataGen\getdata.php on line 4
Any help would be appreciated.Thanks.

When you're POSTing the data as a query-string, try using the application/x-www-form-urlencoded Content-type, not the application/json one that you currently are:
hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");

Related

Retrieve ID number from MYSQL using AJAX & PHP then hashchange URL using retrieved ID

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
}
});

SQL Server Database Query with PHP

I need to get some data from a Microsoft SQL Server database at work. When I have the data I need, I need to make an Excel spreadsheet that can be saved locally on my computer.
I found PHPExcel which seems to do the job on the Excel part, but what about getting the data from the Database?
I can't seem to find anything that's recent. Only old tutorials.
Use this way to Fetch the Records :
<?php
$hostname = "192.168.3.50";
$username = "sa";
$password = "123456";
$dbName = "yourdb";
MSSQL_CONNECT($hostname,$username,$password) or DIE("DATABASE FAILED TO RESPOND.");
mssql_select_db($dbName) or DIE("Database unavailable");
$query = "SELECT * FROM dbo.table";
$result = mssql_query( $query );
for ($i = 0; $i < mssql_num_rows( $result ); ++$i)
{
$line = mssql_fetch_row($result);
print( "$line[0] - $line[1]\n");
}
?>
This will fetch each rows from the Data Retrieve and Print on the Page. Use your Required format into that. I mean, Use html Table to show the data in well format.
Use this code to get an data from Database.
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = '192.168.3.50';
// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'sa');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else{
echo "connected ";
mssql_select_db('Matrix') or die("Wrong DATAbase");
//mssql_query("SELECT Seq_no from dbo.Trans_R WHERE Seq_no = 000001",$link) or die("cannot execute the query");
$query = mssql_query("SELECT Tr_Date,Tr_Time,Tr_Data from Matrix.dbo.Trans_R");
$f = mssql_fetch_array($query);
echo $f['Tr_Date'];
}
?>
Can i know why Negative Vote??
He asked me to :
" but what about getting the data from the Database?"

Try to return JSON data generated with SQL statement from PHP script to JS webpage but get null instead

I want to return JSON data from a resulted SQL statement in a PHP script upon pressing Submit button, but I receive null instead.
I'll be using the returned JSON to filter-show markers on my Google Map, but for now I just want to get the data back across to my jQuery page from PHP script so I can manipulate/use it.
Submit button:
HTML
<input type="submit" id="filter" value="Filter" />
JS
$('#myform').on('submit', function(e) {
e.preventDefault();
var myData = $('#myform').serializeArray();
$.getJSON('myscript.php', myData, function(json){
alert(json);// actually filter for later
});
});
PHP script:
// action is a hidden form control I use to check if form was submitted
if(isset($_POST["action"])){
if(isset($_POST["color"]) && isset($_POST["zipcode"])){
// try to open a connection to a MySQL server
$connection = mysql_connect($host, $username, $password) or die("Could not connect" . mysql_error());
// select the active MySQL database to work with
$db_selected = mysql_select_db($database, $connection) or die("Can\'t use db:" . mysql_error());
$query = 'sql statement to return resutls based on what color and zipcode was provided';
$result = mysql_query($query) or die("Can\'t do that: " . mysql_error());
}
// close connection to the database
echo json_encode($result);
mysql_close($connection);
}
You can't return the result object of a mysql_query call directly. You first have to parse it with functions like mysql_fetch_array or alike (PHP docu).
...
$result = mysql_query($query);
if ( $result === false ) {
die("Can\'t do that: " . mysql_error());
}
$retVal = array();
while( $row = mysql_fetch_array( $result ) ) {
$retVal[] = $row;
}
...
echo json_encode( $retVal );
EDIT
According to the jQuery spec for getJSON (link), the data is sent using GET parameters and not using POST. So you would have to change all the $_POST appearances in your PHP code to either $_GET or $_REQUEST.
Besides this, you should return some error messages if your variables are not set. Right now (according to your code) just an empty document is returned.
Before the echo you should declare the returned content type:
header('Content-Type: application/json');
If you want to check for the receival of the data you can use:
$.ajax({
url: url,
data: myData,
success: function(json) {},
error: function(json) {} // this should allow you to check if data is received (but since the content type is set to text/html and $.getJSON expectr application/json it won't be a success)
});

How to return an error message when connecting to my sql database useing jquery post

I am trying to return an error using jquery post function to retrieve the error.
So far I have written in php
$connect = mysql_connect("localhost","username","password") or die("Error connecting to the database.");
but i want to retunrn the message like so
$connect = mysql_connect("localhost","username","password");
if(!$connect){
$data['error'] = true;
$data['message'] = "Error connecting to the database.";
echo json_encode($data);
};
Help!!
Try this:
$connect = mysql_connect("localhost","username","password") or die(json_encode(array('error' => true, 'message' => mysql_error())));
This will encode the error to a json string

asynchronous data with mysql php?

I do have a code which shows number of data in database. I want to send this data to browser in real time or in between couple of seconds using ajax or any other method...
My code:
$db = mysql_connect($db_host, $db_username, $db_password) or die("Could not connect.");
mysql_select_db($databse_name,$db)or die(mysql_error());
$result = mysql_query("SELECT * FROM table")or die(mysql_error());
$num_rows = mysql_num_rows($result);
echo "$num_rows\n";
If you're using jQuery and that php code is in a file called your_code.php, you could do something like this:
$('#my_button').click(function() {
$.ajax({
url: "your_code.php",
success: function(data) {
$('#my_div').html(data);
}
});
}

Categories