- 724 Posts
- 3 Reply Likes
Posted 4 years ago
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
But several issues are notable:
var image = $("#smallImage").val();
What does this variable contain after this statement?
$.post("postcomplaintinfo.php", {
We have discussed this before. The statement can never work as expected, because it points to a local file within your assets, not a file on your server.
if (!filter_var($emailphn2, FILTER_VALIDATE_EMAIL)) {
This validation is different from your client-side Regexp. Are you intentionally using different validations, or wouldn't you rather use the same client-side validation with a Regexp in your PHP script?
Also, if this field contains a valid phone number, the validation will return false, which is not what you want.
if (empty($_POST["complaintlist1"])) {
$complaintlistErr = "Please Chose Complaint type!";
if (empty($_POST["otherdescription1"])) {
$otherdescriptionErr = "Please Specify other complaint type!";
I thought you wanted either one, not both?
if($con)
echo $complainno;
else
echo "Insertion Failed";
In your php script, you have collected several error messages in various variables, like $nameErr, $statusErr, etc. Now, at the end of the script, you seem to ignore all those errors and just return a complaint number or an fixed error message.
Why? Wouldn't you rather return a json object with all relevant messages and values?
(I suggest you correct these issues (and test thoroughly) first, before going to the other script)
- 724 Posts
- 3 Reply Likes
Thanks to point out all those mistakes, yes some was in my knowledge that Err variable i didn't printed and some was not. Thank you I will correct them first.
- 724 Posts
- 3 Reply Likes
Means, How i can return multiple variable values from php? I also googled but not special result found. All depreciated posts.
When i am returning values of all the error variables, the same error printing on all the <div>..
Like Name is missing, in email and other fields.
and when i am doing like this:
So in one field all variable values are showing,
Just a little hint petra, that how i can print different variable's values in different <div> element with different ids?
function(data) {
$('#response').html(data);
$('#phpnameErr').html(data);
$('#confirmation').show();
.
.
data is holding all the php result. how i can show one variable values at one time?
I tried like this:
But it's wrong i think.
function(data) {
$('#response').html(data.complainno);
$('#phpnameErr').html(data.nameErr);
$('#confirmation').show();
sorry i felt shame to ask u again n again.... :(
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
At the server side, you create an array with the name/value pairs that you would like to keep. Then convert the array to JSON.
Something like:
$arr = array(
"errName"=>"The name is wrong",
"errPosition"=>"Position not numeric",
"complaintNo"=>3345529,
...);
$jsonOutput = json_encode($arr);See http://php.net/manual/en/function.json-encode.php
Then in the client, you loop through the JSON object and set the values wherever you like:
http://api.jquery.com/jquery.ajax/
Make sure both server and client are configured to work with JSON.
http://stackoverflow.com/questions/19155192/jquery-ajax-call-to-php-script-with-json-return
- 724 Posts
- 3 Reply Likes
- 724 Posts
- 3 Reply Likes
GOOD DAY
See I did like this:
But because I hard coded the error messages to array. It'ss showing all error messages when i m submitting the form.
SEe:
.
.
, function(data) { $('#phpnameErr').html(data.nameErr);
$('#phpemailErr').html(data.emailphnErr);
$('#phpemailformatErr').html(data.emailformatErr);
$('#phplocationErr').html(data.locationErr);
$('#phpcomplaintlistErr').html(data.complaintlistErr);
$('#phpotherdescriptionErr').html(data.otherdescriptionErr);
$('#response').html(data.complaintNo);
$('#confirmation').show();
$('#myForm')[0].reset();
},"json")
.fail(function() {
alert( "Posting failed." );
});
return false;
});
});
</script>
</body></html>

and here is php:
<?php$con = mysqli_connect("localhost","root","","amroclean");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$otherdescription2=$smallImage2=$personname2=$emailphn2=$locationtxt2=$complaintlist2=$complainno="";
$error_report = false;
$nameErr=$emailphnErr=$locationtxtErr=$complaintlistErr=$otherdescriptionErr=$imageErr="";
$arr = array('nameErr'=>'Please Enter Your Name!',
'emailphnErr'=>'Please Enter Your Email or Phone Number!',
'emailformatErr'=>'Please Enter Valid Email or Phone Number!',
'locationErr'=>'Please Enter location!',
'complaintlistErr'=>'Please Select Complaint Type',
'complaintNo'=>$complainno
);
$jsonOutput = json_encode($arr);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["personname1"])) {
$error_report = true;
}else {
$personname2 =test_input($_POST["personname1"]);
}
if (empty($_POST["emailphn1"])) {
$error_report = true;
}else {
$emailphn2 =test_input($_POST["emailphn1"]);
}
// check if e-mail or phone is well-formed
if (!preg_match('/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|([7-9]{1}[0-9]{9})+$/',
$emailphn2)){
$error_report = true;
}
else {
$emailphn2 =test_input($_POST["emailphn1"]);
}
if (empty($_POST["locationtxt1"])) {
$error_report = true;
}
else {
$locationtxt2 =test_input($_POST["locationtxt1"]);
}
if (empty($_POST["complaintlist1"])) {
$error_report = true;
}else {
$complaintlist2 = test_input($_POST["complaintlist1"]);
}
if ($_POST["complaintlist1"]=="Other" && empty($_POST["otherdescription1"])) {
$error_report = true;
}else {
$otherdescription2 = test_input($_POST["otherdescription1"]);
} }
if($error_report != true) {
$complainno=mt_rand(10000000,99999999);
mysqli_query($con,"INSERT INTO `complaint` (`peresonname`,`emailphn`,`locationtxt`,`compltypeid`,`otherdescription`,`image`,`complainno`) values('$personname2','$emailphn2','$locationtxt2','$complaintlist2','$otherdescription2','$smallImage2','$complainno')");
}
if($con)
{
echo $jsonOutput;
}
else
{
echo "Insertion Failed";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
mysqli_close($con);
?>
Now where I should use if-else construct? in serverside or client side?
Can i use like this:
in Client side?
, function(data) {
if($('#peresonname').val()=="" || $('#personname').val()==null)
{
$('#phpnameErr').html(data.nameErr);
}
if($('#emailphn').val()== "" || $('#emailphn').val()==null)
{
$('#phpemailErr').html(data.emailphnErr);
}
.
.
.
.
$('#confirmation').show();
$('#myForm')[0].reset();
},"json")
.fail(function() {
alert( "Posting failed." );
});
return false;
});
});
hmmm it's wrong because it's still client side validation right?
so
should i use like this?
if (empty($_POST["emailphn1"])) {
echo $arr['nameErr'];
}
at serverside
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
Here a couple of thoughts:
1.
echo "Failed to connect to MySQL: " . mysqli_connect_error();
Do you really want this to be echoed? What should the app do with this message, if it occurs?
Wouldn't YOU (the developer) rather receive such message, instead of the user?
2.
$jsonOutput = json_encode($arr);
You are echoing this $jsonOutput, which is the full set of error messages.
But you only want to output the error messages that apply. So, you should start with an empty output array:
$outArr = array();then add each error message to that array if applicable, for instance:
if (empty($_POST["personname1"])) {$error_report = true;
$outArr['emailphnErr'] = arr['emailphnErr'];
}Finally, use that array to create the JSON:
$jsonOutput = json_encode($outArr);
3.
if($('#peresonname').val()=="" || $('#personname').val()==null)
{
$('#phpnameErr').html(data.nameErr);
}
You should not check the field value client side, again. Once the server has done the validating, it supplies the appropriate error messages in the json object. All you need to do client side is:
- see if there is an applicable error message for that field
- display that error message.
4.
(about the screen shot)
Apparently, you are displaying the error messages inside the input field. That would be problematic if the field was merely incorrectly entered by the user.
For instance, if he typed a mail address like abc%mydomain.com, you would write "Please enter a valid Mail Address". But....how does the user now know what he did wrong? How can he correct his error? He can't even see what he entered anymore.
So, you should make sure that the already entered data are still visible when displaying an error message.
- 724 Posts
- 3 Reply Likes
Whatever you are, my brother, father, friend, Teacher, you are awesome. My eyes are wet now, and also dark circles to code aagain n agian. :D I don't kno hus is behind this bot, but really u r .....i havn't words, again thank you Petra, Salute to u.
- 724 Posts
- 3 Reply Likes
But I found that I am still stand there.
It's now headache.
You please just tell me that how i can loop json objects at my client side please, with an example.
Please......
see:
it's returning empty array like []
<?php$con = mysqli_connect("localhost","root","","amroclean");
// Check connection
if (mysqli_connect_errno())
{
echo "Error: OOPS!, there was an error in connection " . mysqli_connect_error();
}
$otherdescription2=$smallImage2=$personname2=$emailphn2=$locationtxt2=$complaintlist2=$complainno="";
$error_report=false;
$arr = array('nameErr'=>'Please Enter Your Name!',
'emailphnErr'=>'Please Enter Your Email or Phone Number!',
'emailformatErr'=>'Please Enter Valid Email or Phone Number!',
'locationErr'=>'Please Enter location!',
'complaintlistErr'=>'Please Select Complaint Type',
'complaintNo'=>$complainno
);
$outArr = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["personname1"])) {
$error_report = true;
$outArr['nameErr'] = $arr['nameErr'];
}
else {
$personname2 =test_input($_POST["personname1"]);
}
if (empty($_POST["emailphn1"])) {
$error_report = true;
$outArr['emailphnErr'] = $arr['emailphnErr'];
}else {
$emailphn2 =test_input($_POST["emailphn1"]);
}
// check if e-mail or phone is well-formed
if (!preg_match('/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|([7-9]{1}[0-9]{9})+$/',$emailphn2)){
$error_report = true;
$outArr['emailphnformatErr'] = $arr['emailphnformatErr'];
}
else {
$emailphn2 =test_input($_POST["emailphn1"]);
}
if (empty($_POST["locationtxt1"])) {
$error_report = true;
$outArr['locationErr'] = $arr['locationErr'];
}
else {
$locationtxt2 =test_input($_POST["locationtxt1"]);
}
if (empty($_POST["complaintlist1"])) {
echo $arr['complaintlistErr'];
clear();
}else {
$complaintlist2 = test_input($_POST["complaintlist1"]);
}
if ($_POST["complaintlist1"]=="Other" && empty($_POST["otherdescription1"])) {
$error_report = true;
$outArr['otherdescriptionErr'] = $arr['otherdescriptionErr'];
}else {
$otherdescription2 = test_input($_POST["otherdescription1"]);
}
}
if($error_report!=true)
{
echo $jsonOutput = json_encode($outArr);
}
else
{
$complainno=mt_rand(10000000,99999999);
mysqli_query($con,"INSERT INTO `complaint` (`peresonname`,`emailphn`,`locationtxt`,`compltypeid`,`otherdescription`,`image`,`complainno`) values('$personname2','$emailphn2','$locationtxt2','$complaintlist2','$otherdescription2','$smallImage2','$complainno')");
}
if($con)
{
echo $complainno;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
mysqli_close($con);
?>
and at form it's showing posting failed.
I tried by many type, but cudn't
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
So, the server isn't reached at all? Your PHP script isn't executed?
Well, then of course no JSON object is returned.
But on the other hand, you said that the full error message array was returned, so the server DOES return a JSON object. It's just the contents of that object that wasn't correct. Are you saying that the server is now returning nothing at all?
And also, this is not a JSON object:
echo $complainno;Steps to check in your app:
1. Display the data that are returned from the server
2. Check if the object structure is what you expect from that JSON object
3. If no object is returned, check at the end of your script (before anything is echo'ed) what it is about to send.
How to loop through a json object? See
http://stackoverflow.com/questions/20772417/how-to-loop-through-json-array-in-jquery
- 724 Posts
- 3 Reply Likes
I have change my script see:
<?php
$con = mysqli_connect("localhost","root","","amroclean");
// Check connection
if (mysqli_connect_errno())
{
echo "Error: OOPS!, there was an error in connection " . mysqli_connect_error();
}
$complainno=$complainno=mt_rand(10000000,99999999);
$dataArr=array('complaintNo'=>$complainno);
$empty_errors=array('nameErr'=>'Please Enter Your Name',
'emailphnErr'=>'Please Enter your Email or Phone Number',
'locationtxtErr'=>'Please enter location',
'complaintlistErr'=>'Select Complaint Type',
'otherdescriptionErr'=>'Please Specify other problem');
$exp_errors=array('emailphnformatErr'=>'You have entered an invalid Email or Phone Number');
$jsondataArr=json_encode($dataArr);
$jsonemptyErr=json_encode($empty_errors);
$jsonexpErr=json_encode($exp_errors);
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$personname2=mysqli_real_escape_string($con,$_POST['personname1']);
$emailphn2=mysqli_real_escape_string($con,$_POST['emailphn1']);
$locationtxt2=mysqli_real_escape_string($con,$_POST['locationtxt1']);
$complaintlist2=mysqli_real_escape_string($con,$_POST['complaintlist1']);
$otherdescription2=mysqli_real_escape_string($con,$_POST['otherdescription1']);
$smallImage2=$_POST['image1'];
$sql="INSERT INTO `complaint` (`peresonname`,`emailphn`,`locationtxt`,`compltypeid`,`otherdescription`,`image`,`complainno`) values('$personname2','$emailphn2','$locationtxt2','$complaintlist2','$otherdescription2','$smallImage2','$complainno')";
foreach($_POST as $val)
{
if(trim($val)=='' || empty($val))
{
echo $jsonemptyErr;
}
if (!preg_match('/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|([7-9]{1}[0-9]{9})+$/',$emailphn2))
{
echo $jsonexpErr;
}
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo $jsondataArr;
}
}
else
{
echo "Insertion Failed";
}
mysqli_close($con);
?>
Can you tell me why it's showing Insertion failed when I am browsing it on browser?
And it's showing an alert of "Posting Failed".
, function(data) { $('#phpnameErr').html(data.nameErr);
$('#phpemailErr').html(data.emailphnErr);
$('#phpemailformatErr').html(data.emailphnformatErr);
$('#phplocationErr').html(data.locationErr);
$('#phpcomplaintlistErr').html(data.complaintlistErr);
$('#phpotherdescriptionErr').html(data.otherdescriptionErr);
$('#response').html(data.complaintNo);
$('#confirmation').show();
$('#myForm')[0].reset();
},"json")
.fail(function() {
alert( "Posting failed." );
});
return false;
});
});
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
And while validating: are you echo'ing every error message as a String immediately, without collecting them in the array $outArr first? After all, you want a json object with all applicable error messages, right?
Now, the part
else
{echo "Insertion Failed";
}is the else branch of the
if ($_SERVER["REQUEST_METHOD"] == "POST")so it seems your server script is called without anything being posted.
- 724 Posts
- 3 Reply Likes
How are you today?
Yes i was wrong i just saw a stckover flow code.
now see i again did old coding.
<?php$con = mysqli_connect("localhost","root","","amroclean");
// Check connection
if (mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_error();
}
$validation=false;
$otherdescription2=$smallImage2=$personname2=$emailphn2=$locationtxt2=$complaintlist2="";
$complainno=mt_rand(10000000,99999999);
$arr=array('nameErr'=>'Name required!',
'emailphnErr'=>'Enter Email or phone Number',
'emailphnformatErr'=>'Enter valid Email or Phone Number',
'locationErr'=>'Enter location',
'complaintlistErr'=>'Select Complaint Type!',
'otherdescriptionErr'=>'Please Specify Other Problem!',
'complaintNo'=>$complainno
);
$OutArr=array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["personname1"])) {
$validation=true;
$OutArr=$arr['nameErr'];
}else {
$personname2 =test_input($_POST["personname1"]);
}
if (empty($_POST["emailphn1"])) {
$validation=true;
$OutArr=$arr['emailphnErr'];
}else {
$emailphn2 =test_input($_POST["emailphn1"]);
// check if e-mail address is well-formed
if (!filter_var($emailphn2, FILTER_VALIDATE_EMAIL)) {
$validation=true;
$OutArr=$arr['emailphnformatErr'];
}
}
if (empty($_POST["locationtxt1"])) {
$validation=true;
$OutArr=$arr['locationErr']; }
else {
$locationtxt2 =test_input($_POST["locationtxt1"]);
}
if (empty($_POST["complaintlist1"])) {
$validation=true;
$OutArr=$arr['complaintlistErr'];
}else {
$complaintlist2 = test_input($_POST["complaintlist1"]);
}
if (empty($_POST["otherdescription1"]) && ($_POST["otherdescription1"]=="Other") ){
$validation=true;
$OutArr=$arr['otherdescriptionErr']; }else {
$otherdescription2 = test_input($_POST["otherdescription1"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($validation!=true)
{
mysqli_query($con,"INSERT INTO `complaint` (`peresonname`,`emailphn`,`locationtxt`,`compltypeid`,`otherdescription`,`image`,`complainno`) values('$personname2','$emailphn2','$locationtxt2','$complaintlist2','$otherdescription2','$smallImage2','$complainno')");
}
else
{
json_encode($OutArr);
}
if($con)
echo json_encode($arr);
else
echo "Insertion Failed";
mysqli_close($con);
?>
in this coding $OutArr[] is not returning any data.
Just like:

petra please clear me client side cding for this, i hope server side is ok now.
after lots of trials, i coudn't printed json values properly.
Please Petra, i want o complete it soon now. It's not m not trying, Realy day and night foind this, but json data can't show according to conditions/
Please give some code hint, yes u did, u also linked coding, but all they are relation to any single array element returned i want to print many array elements retrurned from server but at dfferent conditions............
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
This will never become an array with a collection of strings, but rather just a single string.
$OutArr=$arr['nameErr'];
As a result, your json object will be empty.
But Saba, these are very simple things to test. All you need to do is add a display statement for $OutArr before it's being sent, run your script and see what the json object contains. If it is empty, you need to find the error server side, and not focus on the client.
- 724 Posts
- 3 Reply Likes
- 724 Posts
- 3 Reply Likes
Everything is working as I am expecting in both scripts, now what i want:
A Confirmation page, I have already created with confirmation message and complaintNo, certainly i can return complaintNo from json array.
But problem is that when i am hitting the submit button in the form whenever with it's empty fields or filled, it's showing confirmation page instantly.
How i prevent this(to showing confirmation page) untill all fields are not filled out?
json array is returning all values.
But quick page flip to another page e.g. confirmation page.
I tried with two following method:
$('#page2).hide();
$('#confirmation).show();
&
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#confirmation", {transition:'flip' } );
Both are behaving same.
see:
function(data) { for(var i = 0; i < data.length; i++){
$("#" + data[i].id).show();
$("#" + data[i].id).html(data[i].message);
}
$('#page2).hide();
$('#confirmation).show();
},"json").fail(function() {
alert( "Posting failed." );
});
and also
7 days ago u wrote:
var image = $("#smallImage").val();
What does this variable contain after this statement?
so should i use
$('#smallImage').attr('src');
this one?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
Secondly, look what you are doing:
function(data) {
for(var i = 0; i < data.length; i++){
$("#" + data[i].id).show();
$("#" + data[i].id).html(data[i].message);
}
In the above part, you get the datafields and appropriate error messages returned, and you place them in the html elements as identified by $("#" + data[i].id).
You are still in the form page, which is OK.
So, this will display the form again, with possible error messages.
You tell your DOM that the fields (as returned by your server) must be shown, but you don't say that anything must be hidden, so there will be no difference for the user.
Then you add this:
$('#page2).hide();
$('#confirmation).show();
It tells your script to hide the form (which you just filled with messages) and show a confirmation page (which might be a separate html document or a div within the form page).
This part will always be executed after receiving the post response, regardless of the result.
That's why you always see the confirmation page.
Instead, you should first check if error messages exist. If so, you should display the form with messages. If not, you should show the confirmation.
And then you have this:
.fail(function() {
alert( "Posting failed." );
Suppose you are a user and you receive this alert box, what would you do?
And is that what you, the developer, really want to happen?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
var image = $("#smallImage").val();
What does this variable contain after this statement?
Have you checked what it contains?
(And: now that you have posted something, did the image data actually make it to your database? Can you retrieve and display such image?)
so should i use
$('#smallImage').attr('src');
No, I didn't say that. You should use what you need in yur database to be retrieved and displayed. If you are expecting base-64 data from your database, you should post them. If yu expect the base64-url from your database, yu should post that. And if yu want a file to be posted instead of base64 data, you need the file transfer plugin, not ajax.
So, you should take yur pick, then implement that throughout the whole client server process.
- 724 Posts
- 3 Reply Likes
Firstly, the code that you posted is probably part of a larger statement, since the block as shown doesn't validate. Probably you picked a fraction of a full method's call.The validation i used in server side, here i just call them into some particular <div> by their ids.
See server side scripting.
<?php
$con = mysqli_connect("localhost","root","","amroclean");
// Check connection
if (mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_error();
}
$otherdescription2=$smallImage2=$personname2=$emailphn2=$locationtxt2=$complaintlist2="";
$complainno=mt_rand(10000000,99999999);
//response array with id and message
$response_array = array();
$validation = true;
//validate the post form
//check the name field
if(empty($_POST['personname1'])){
$response_array[] = array('id'=>'phpnameErr','message'=>'Name is required!');
$validation = false;
}else{
$personname2 = test_input($_POST["personname1"]);
$response_array[] = array('id'=>'phpnameErr','message'=>'');
}
if (empty($_POST["emailphn1"])) {
$response_array[] = array('id'=>'phpemailphnErr','message'=>'Email is required');
$validation = false;
} else {
$emailphn2 = test_input($_POST["emailphn1"]);
// check if e-mail address is well-formed
if (!preg_match('/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})|([7-9]{1}[0-9]{9})+$/',
$emailphn2)) {
$response_array[] = array('id'=>'phpemailphnErr','message'=>'Invalid email or phone format');
$validation = false;
}else{
$response_array[] = array('id'=>'phpemailphnErr','message'=>'');
}
}
if(empty($_POST["locationtxt1"]))
{
$response_array[] = array('id'=>'phplocationErr','message'=>'Enter Location!');
$validation=false;
}
else
{
$locationtxt2=test_input($_POST["locationtxt1"]);
$response_array[] = array('id'=>'phplocationErr','message'=>'');
}
if(empty($_POST["complaintlist1"]))
{
$response_array[] = array('id'=>'phpcomplaintlistErr','message'=>'Select Complaint Type!');
$validation=false;
}
else
{
$complaintlist2=test_input($_POST["complaintlist1"]);
$response_array[] = array('id'=>'phpcomplaintlistErr','message'=>'');
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!$con){
$response_array[] = array('id'=>'connectErr','message'=>'Connection Error');
}
else if($validation!=false)
{
mysqli_query($con,"INSERT INTO `complaint` (`peresonname`,`emailphn`,`locationtxt`,`compltypeid`,`otherdescription`,`image`,`complainno`) values('$personname2','$emailphn2','$locationtxt2','$complaintlist2','$otherdescription2','$smallImage2','$complainno')");
}
echo json_encode($response_array);
?>
Suppose you are a user and you receive this alert box, what would you do? And is that what you, the developer, really want to happen?Then what i do Petra, What should i print else? or should show here another page with some error text?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
Yes, you could do that. At the same time, you want to post something to a script that mails you the status, date/time, error message and whatever is needed to take immediate action. You, or the person who is technically in charge of maintaining the app, should receive an alert, if possible.
The text for the user could be something like:
"Unfortunately, your complaint could not be posted right now, due to technical issues. The application administrator has been alerted.
In urgent cases, you may want to contact the office by phone: (phone number here)."
- 724 Posts
- 3 Reply Likes
Ha, one more favor added into my rock, which is stand on my head.
Cordially thanking you.
- 724 Posts
- 3 Reply Likes
:)
I hope you are well.
Petra, I want to ask that you suggested me that I should create an error page, on posting failed.
I have created it with same text u post.
NOw i want to ask that :
1) Should I use only javascript for this at client side on document load?
Like:

or Should I use mail() function of php at server side? And If I will use mail function of php, then it's needed again ajax json array data return?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
So, you need to work server-side, and yes, that requires an ajax process. Careful though: this message post might also fail. In that case, you cannot receive a mail about this event.
- 724 Posts
- 3 Reply Likes
BTW:
can i use in this way?
<?php
// Send error message to the server log if error connecting to the database
if (!mysqli_connect("localhost","bad_user","bad_password","my_db")) {
error_log("Failed to connect to database!", 0);
}
// Send email to administrator if we run out of FOO
if (!($foo = allocate_new_foo())) {
error_log("Oh no! We are out of FOOs!", 1, "admin@example.com");
}
?>
for this user's email id must be logged in phone??? what if user didn't logged in mobile?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
But what is $foo? What is the function allocate_new_foo()? And how can you be out of FOOs?
And no, nobody needs to be logged in phone. You are sending a mail to the administrator (which might be you, or anyone in charge of the application).
- 724 Posts
- 3 Reply Likes
means this email will go by admin@gmail.com to admin@gmail.com?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
Then why did you code it in your script?
Example:
if (!mysqli_connect("localhost","bad_user","bad_password","my_db")) {
error_log("Failed to connect to database!", 0);
mail(
'admin@gmail.com', 'Script error', 'mysqli connect failed');$response_array[] = array('id'=>'systemErr','message'=>'<code>mysqli connect failed');echo json_encode($response_array);}
In the app, if 'systemErr' is set, display the error page.
- 724 Posts
- 3 Reply Likes
Hehehe thank you.
one thing more vrba
u said In the app, if systemErr is set, means <div> element with id systemErr right?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
- 724 Posts
- 3 Reply Likes
I am stuck off here.
I have another form, complaintstatus.html and checkstatus.php files.
Same like complaints.html i added php server side validation, but the problem is that....this script is not responding here, it's working there, but here data is not returning, but also not showing posting failed...when i am hitting the button "GO" nothing happening, although i checked click event. It's working.
See html file and php script.
complaintstatus.html
<!doctype html><html>
<head>
<meta charset="utf-8">
<link href="jquery-mobile/jquery.mobile.theme-1.4.5.min.css" rel="stylesheet" type="text/css">
<link href="jquery-mobile/jquery.mobile.structure-1.4.5.min.css" rel="stylesheet" type="text/css">
<script src="jquery-mobile/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.4.5.min.js" type="text/javascript"></script>
<style>
.header
{
background-color:#F60;
}
.footer
{
background-color:#090;
}
</style>
</head>
<body>
<div data-role="page" id="page3">
<div class="header" data-role="header" data-position="fixed">
<h3><table width="100%" height="77"><tr><td width=32><a href="index.html" rel="external"><img src="images/back.png" width="30" height="30"></a></td>
<td width="585"><font color="white">Check Complaint Status</font></td></tr></table></h3>
</div>
<div id="contents">
<form method="post" name="form" id="form">
<input type="number" name="complaintno" id="complaintno" placeholder="Enter Complaint Number">
<div id="statusErr" style="display:none;color:red">Please Enter Complaint Number!</div>
<div id="validErr" style="display:none;color:red">You have entered an invalid Complaint Number!</div>
<div id="phpvalidErr"></div>
<br><br><button type="button" value="GO" id="checkstatusbtn" name="checkstatusbtn">Go</button></form>
</div>
<div class="footer" data-role="footer" data-position="fixed">
<br>
<h4><font color="white">NPP Community, Amroha</font></h4>
<br>
</div></div>
</div>
<!-- ====== Complaint status content starts here ===== -->
<div role="page" id="complaintstatus" name="complaintstatus">
<div data-role="header" name="hdrComplaintStatus" data-nobackbtn="true" style="background-color:green;text-align:center;color:white;">
<h2>Your Complaint Status</h2>
</div>
<div data-role="content" id="contentConfirmation" name="contentConfirmation" align="center" data-position="fixed">
<font color="#000066" face="Constantia, Lucida Bright, DejaVu Serif, Georgia, serif" size=5></font>
<br>
<br>
<div id="statusresponse"></div>
</font>
</div>
<div data-role="footer" data-position="fixed" id="ftrComplaintStatus" name="ftrComplaintStatus" style="background-color:orange;text-align:center;color:white;" >
<h3>NPP Community, Amroha
</h3>
</div></div>
<!-- ====== complaint status contents end here ===== -->
<script>
$(document).ready(function() {
$('#complaintstatus').hide();
$("#checkstatusbtn").click(function() {
var complaintno = $("#complaintno").val();
/*if (complaintno==null || complaintno=="")
{
$("#statusErr")
.slideDown("fast",function(){
$(this).delay(2000).slideUp("fast");
});
return false;
}
if (complaintno<=10000000 || complaintno>=99999999) {
$("#validErr")
.slideDown("fast",function(){
$(this).delay(2000).slideUp("fast");
});
return false;
}
else
{ */
// Returns successful data submission message when the entered information is stored in database.
$.post("http://localhost/AmroClean/checkstatus.php";, {
complaintno: complaintno,
}, function(data) {
for(var i = 0; i < data.length; i++){
$("#" + data[i].id).show();
$("#" + data[i].id).html(data[i].message);
}
}).fail(function() {
alert( "Posting Failed" );
});
return false;
});
});
</script>
</body></html>
</body>
</html>
and here is php file named checkstatus.php
<!doctype html><html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$con= mysqli_connect("localhost","root","","amroclean");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$complainno="";
$response_array = array();
$validation = true;
if (empty($_POST["complaintno"])) {
$response_array[] = array('id'=>'phpvalidErr','message'=>'Enter Complaint Number!');
$validation = false;
} else {
$complainno = test_input($_POST["complaintno"]);
// check if complaint number is well-formed
if ($complainno<=10000000 && $complainno>=99999999) {
$response_array[] = array('id'=>'phpvalidErr','message'=>'You have entered an Invalid Complaint Number!');
$validation = false;
}else{
$response_array[] = array('id'=>'phpvalidErr','message'=>'');
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!$con){
$response_array[] = array('connectErr'=>'Connection Error');
}
else if($validation!=false)
{
$sql = "SELECT peresonname, locationtxt, complainno,status FROM complaint where complainno='$complainno'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if($row["status"]==0)
echo "Dear " . $row["peresonname"]. " Your Complaint with Complaint Number " . $row["complainno"]. "is still in progress, thanks for patience"."<br>"."Regards: Nagar Palika, Amroha";
if($row["status"]==1)
echo "Dear " . $row["peresonname"]. " Your Complaint with Complaint Number " . $row["complainno"]. "has been solved"."<br>"."Regards: Nagar Palika, Amroha";
}}
else {
echo "Sorry, there is no complaint booked, with this Number, please check the Complaint Number and try again.";
}
}
echo json_encode($response_array);
mysqli_close($con);
?>
</body>
</html>
The php script's out as follows:

if your sharp eyes can see errors/bugs please tell me, I tried much, m not always say first to u...when after lots of trials i fail, then i tell u
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
$.post("http://localhost/AmroClean/checkstatus.php";, {
complaintno: complaintno,
}, function(data) {
First line: semicolon
Second line: comma
- 724 Posts
- 3 Reply Likes
This is actually print screen see:

it's miracle sir, i also note it before, whenever i post like this, this forum automatically add these symbols.
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
OK: here is something else:
you have
{complaintno: complaintno,}
Javascript would, of course, substitute bothe with the value of the variable complaintno. If that number was 123, it would send:
{123:123}
Instead, you want to be sent:
{'complaintno': 123}
or
{'complaintno': '123'}
- 724 Posts
- 3 Reply Likes
When I am showing an alert with data, it's showing all data in html format, see like this:
}, function(data) {
alert(data);
but now when i am adding datatype json in post method, it's showing ,"Posting Falied".

and when i am removing datatype json and showing data like this: data is returning but in this format, all validation is working fine but in following format.
Source Code:
$.post("http://localhost/AmroClean/checkstatus.php";, {'complaintno':complaintno
}, function(data) {
if(data){
$('#phpvalidErr').html(data);
}
}).fail(function() {
alert("posting failed");
});
return false;
});
});
and php code:
<!doctype html><html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$con= mysqli_connect("localhost","root","","amroclean");
// Check connection
if (mysqli_connect_errno())
{
echo "Connection Failed " . mysqli_connect_error();
}
$complainno="";
$min=10000000;
$max=99999999;
$response_array = array();
$validation = true;
if (empty($_POST["complaintno"])) {
$response_array[] = array('phpvalidErr'=>'Please Enter Complaint Number!');
$validation = false;
} else {
$complainno = test_input($_POST["complaintno"]);
// check if e-mail address is well-formed
if ($complainno<=$min || $complainno>=$max) {
$response_array[] = array('phpvalidErr'=>'Invalid complaint number!');
$validation = false;
}
else{
$response_array[] = array('phpvalidErr'=>'');
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(!$con){
$response_array[] = array('connectErr'=>'Connection Error');
}
else if($validation!=false)
{
$sql = "SELECT peresonname, locationtxt, complainno,status FROM complaint where complainno='$complainno'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if($row["status"]==0)
echo "Dear " . $row["peresonname"]. " Your Complaint with Complaint Number " . $row["complainno"]. "is still in progress, thanks for patience"."<br>"."Regards: Nagar Palika, Amroha";
if($row["status"]==1)
echo "Dear " . $row["peresonname"]. " Your Complaint with Complaint Number " . $row["complainno"]. "has been solved"."<br>"."Regards: Nagar Palika, Amroha";
}}
else
{
$response_array[] = array('phpvalidErr'=>'Complaint Number does not exists');
}
}
echo json_encode($response_array);
mysqli_close($con);
?>
</body>
</html>
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
Also, since you are not using jQuery's GetJSON() function, you need to parse the json object first, using JSON.parse()
- 724 Posts
- 3 Reply Likes
Posting failed........................one thing i can't understand that in same app when this code is working as expected in another form then why in this form not. :(
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
- 724 Posts
- 3 Reply Likes
HAVE a NICE Day
- 724 Posts
- 3 Reply Likes

1) which is better base64-url or base64 data to post?
2) Should i make image mandatory? Please don't say as u want. Suggest me better.
3) I think there is no validation required for image format? they are already added in photo library and capture photo pgb camera plugin?
4) Should i add image size validation, or it's also added in plugin?
Thankew
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
2. No. Image should not be necessary.
3. Correct. No validation required
4. You could set the attributes for 'quality' in the plugin's javascript call, so some devices and operating systems will rescale and deliver a smaller sized image.
- 724 Posts
- 3 Reply Likes
var pictureSource; // picture sourcevar destinationType; // sets the format of returned value
// Wait for Cordova to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);
// Cordova is ready to be used!
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64 encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageData) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// A button will call this function
//
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL });
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: Camera.DestinationType.DATA_URL });
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: source });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
In this script quality is already set.
Now, at client side, and server side what code i will add for images?'
Is this not correct?
var image = $("#smallImage").val();
.
.
.
.

and in server side:

what keyword i will use?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
var image = $("#smallImage").val();
No, that's not correct. Have you checked the value of the 'image' variable yourself, first?
In the above code, you have not set the value for the 'smallimage' object, but rather the 'src' attribute, so that's what you have to pick up before posting.
btw: I would not store the prefix 'data:image/jpeg;base64,' in my database, if I were you. It's just a prefix to make the browser understand what type of data are being fed, but it's not part of the real image data.
what keyword i will use?
Erm....for what functionality?
- 724 Posts
- 3 Reply Likes
No, that's not correct.
Then what is correct method Petra, please tell me, i checked but nothing is showing...it's value.
btw: I would not store the prefix 'data:image/jpeg;base64,' in my database, if I were you.Means I should use smallImage.src=imageData;
Instead of
smallImage.src = "data:image/jpeg;base64," + imageData;
?
Yes of course I also don't want to use this string prefix blob data.
what keyword i will use?means i want to say that should i use some keywords like:
Erm....for what functionality?
base64_encode($smallImage);
in php side? Sorry :D coool coool
- 724 Posts
- 3 Reply Likes
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
In the above code, you have not set the value for the 'smallimage' object, but rather the 'src' attribute, so that's what you have to pick up before posting.
2.
Means I should use smallImage.src=imageData;
Instead of
smallImage.src = "data:image/jpeg;base64," + imageData;
?
No, of course not. That code is the part where you display the small image. It needs a data url, because you are not setting a file as source.
However, you should not use such full data url when posting the image data to the server!
3.
should i use some keywords like:
base64_encode($smallImage);
in php side?
No, no. You are posting base64 data, which is simply a large string. There is nothing to convert, there. Simply store that string in your blob, and retrieve it when it needs to be displayed. Then add the prefix to place it in a mail or in a html document.
- 724 Posts
- 3 Reply Likes
<img id="smallImage" src="images/a1.jpg" style="display:none;width:220px;height:260px;">
Now I checked it's value by:
var image = $('#smallImage').attr('src');

When i post all information with image, database updated with following record:

all of this correct or not? Am i missing something?
and when i am displaying this image on webpage , only url images/a1.jpg is showing. Without decoding it.
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
You have now briefly been testing with a file url. The value of the src attribute of the image is the file location. The browser will pick up such file and display it.
However, in your app, you want the picture be captured as a base64 string. The src attribute of the image would then be the base64 string with the file type prefix. In your database, you want the base64 data, not the file url.
Alternatively, you could make the camera store the picture and deliver a file uri. The result would be a file, posted to your server. You could save the file in the file system and store its path/name in the database. In such case, you should - upon displaying the image - retrieve the file, not a base64 string.
As written months ago, you need to decide which way you want to go. In the past weeks, it looked like you wanted the base64 version. Actually, if you still don't know the difference, you should find some good articles about this topic and study them, first.
- 724 Posts
- 3 Reply Likes
The camera and library will capture image in base64 format.
This was not a base64 image it was only a test to check the value of image element.
So, now functionality is correct? I will remove hardcoded image.
What is the difference between base64 encoded string and URL?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
1. Your camera returns 'imageData', which is a base64 string.
2. In your app, you display it correctly with
smallImage.src = "data:image/jpeg;base64," + imageData;
3. You should be posting the contents of 'imageData' to the server
4. That string should be stored in the database
5. Upon retrieval, for instance in the app, on a web page or in a mail, you should get the imageData from the DB, and return a piece of html which contains (in js terms):
src = "data:image/jpeg;base64," + imageData;
- 724 Posts
- 3 Reply Likes
Can it post base64 imgData to db correctly? Retrieval i will think later/
- 724 Posts
- 3 Reply Likes
These are the two hidden elements in my form to store lat and lon values. To post in DB.
<input type="hidden" name="lat" id="lat" value="" />
<input type="hidden" name="lon" id="lon" value="" />
This is the script piece i am using to get current position.
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?mytimestamp="+new Date().getTime()
+"¢er="+latlon
+"&zoom=16&size=220x220&sensor=false&markers="+latlon
+"&size:mid%7Ccolor:0xff0000%7Clabel:%7Camroha,+uttar+pradesh&visual_refresh=true";
$("#mapholder").html("<img src='"+img_url+"'>");
}
I change this script into:(to store lat and lon values separately)
function showPosition(position) {
var lat=position.coords.latitude;
var lon=position.coords.longitude;var latlon = lat+ "," + lon;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?mytimestamp="+new Date().getTime()
+"¢er="+latlon
+"&zoom=16&size=220x220&sensor=false&markers="+latlon
+"&size:mid%7Ccolor:0xff0000%7Clabel:%7Camroha,+uttar+pradesh&visual_refresh=true";
$("#mapholder").html("<img src='"+img_url+"'>");
}
now how i can get these values in hidden fields?
- 724 Posts
- 3 Reply Likes
These are the two hidden elements in my form to store lat and lon values. To post in DB.
<input type="hidden" name="lat" id="lat" value="" />
<input type="hidden" name="lon" id="lon" value="" />
This is the script piece i am using to get current position.
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?mytimestamp="+new Date().getTime()
+"¢er="+latlon
+"&zoom=16&size=220x220&sensor=false&markers="+latlon
+"&size:mid%7Ccolor:0xff0000%7Clabel:%7Camroha,+uttar+pradesh&visual_refresh=true";
$("#mapholder").html("<img src='"+img_url+"'>");
}
I change this script into:(to store lat and lon values separately)
function showPosition(position) {
var lat=position.coords.latitude;
var lon=position.coords.longitude;var latlon = lat+ "," + lon;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?mytimestamp="+new Date().getTime()
+"¢er="+latlon
+"&zoom=16&size=220x220&sensor=false&markers="+latlon
+"&size:mid%7Ccolor:0xff0000%7Clabel:%7Camroha,+uttar+pradesh&visual_refresh=true";
$("#mapholder").html("<img src='"+img_url+"'>");
}
now how i can get these values in hidden fields?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
...or one of the hundreds of other tutorials online.
- 724 Posts
- 3 Reply Likes
But they are not posting into table.
what i did, I assign some values to variables lat and lon to check if they are setting into input hidden elements. But because variables are declared under show position call back of getCurrentLocation method. I coudn't post them into db by ajax.
When i declared then globally, input elements are getting variables's values, but not posting into table.
I did something like this:
I hardcoded these coordinator values just to check.
function showPosition(position) {
lat = 23.7878;
$('#lat').val(lat);
lon = 25.5625;
$('#lon').val(lon);
var latlon = lat+ "," +lon;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?mytimestamp="+new Date().getTime()
+"¢er="+latlon
+"&zoom=16&size=220x220&sensor=false&markers="+latlon
+"&size:mid%7Ccolor:0xff0000%7Clabel:%7Camroha,+uttar+pradesh&visual_refresh=true";
$("#mapholder").html("<img src='"+img_url+"'>");
}
When I declared variable outside showPosition() method's body, input element are getting values but not posting to table.
Can I use two posting methods in same page? Means i want to post lat and lon values to server from showPosition() method by ajax or post method. Can I?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
Why "can't you post to table"? What exactly is going wrong, and do you get an error message? Is the error to be found in the client or on the server?
- 724 Posts
- 3 Reply Likes
I checked by an alert(lat);
But it's not showing any value.
When i am declaring those variables outside from showPosition function, it's showing alert with it's value.
Can't I use like this?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
$.ajax({
type: "POST",
url: "locations-ajax.php",
data: {
x: position.coords.latitude,
y: position.coords.longitude
},
success: function (data) {
}
});
});
}
??
<br>Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
You can't store lat/lon without the rest of the mandatory fields and without either creating a Complaint or being passed an existing Complaint.
- 724 Posts
- 3 Reply Likes
How i can post lat and lon values to table?
See
when I m doing like this, input element can't pass coordinates value.
function showPosition(position) {
$("input[name='lat']").val(position.coords.latitude);
$("input[name='lon']").val(position.coords.longitude);
var latlon = position.coords.latitude+ "," +position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?mytimestamp="+new Date().getTime()
+"¢er="+latlon
+"&zoom=16&size=220x220&sensor=false&markers="+latlon
+"&size:mid%7Ccolor:0xff0000%7Clabel:%7Camroha,+uttar+pradesh&visual_refresh=true";
$("#mapholder").html("<img src='"+img_url+"'>");
}
and when i am doing like this:
Input elements getting variable values.
But i think It's wrong to keep those variables outside from showPosition method right. Secondly when i am declaring lat and lon variables null, data is not posting too the table.
.
.
.
.
$("input[name='lat']").val(position.coords.latitude);
$("input[name='lon']").val(position.coords.longitude);
function showPosition(position) {
var latlon = position.coords.latitude+ "," +position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?mytimestamp="+new Date().getTime()
+"¢er="+latlon
+"&zoom=16&size=220x220&sensor=false&markers="+latlon
+"&size:mid%7Ccolor:0xff0000%7Clabel:%7Camroha,+uttar+pradesh&visual_refresh=true";
$("#mapholder").html("<img src='"+img_url+"'>");
}
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
function showPosition(position) {
$("input[name='lat']").val(position.coords.latitude);
$("input[name='lon']").val(position.coords.longitude);
to set the input fields in your code. The jQuery typed form fields are global variables, so you should be able to set them from a function. It's no different from your last line:
$("#mapholder").html("<img src='"+img_url+"'>");
which is also just setting a value into DOM from within the (same) function.
So, why can't you use the first form you posted? What else is going wrong? Have you debugged?
- 724 Posts
- 3 Reply Likes
But still having problem, i was thinking to upload today, but what i do........whenever m posting data, it's not updating.
when lat and lon values are null, rows should be insert, but since i added those code snippet in my page, rows are not updating/inserting.
see:

---------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------
also see table structure:

Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
- aren't the lat and lon data stored in the DB?
- aren't the lat and lon data substiuted into your query?
- aren't the lat and lon data received through the $_POST global array?
- aren't the lat and lon data posted from the client?
WHAT?
With all those small snippets, I really can't check what is going on. I don't even have an idea whether or not you have html elements in the DOM with id=lat/lon at all. I can't see how these DOM elements are created. I have no idea whether or not the other data fields are set correctly prior to the post call. And if course, if they are, I can't check how these data arrive at the server, prior to handling them for the DB query.
You.need.to.debug.step.by.step! Display results of every single statement, and don't just run the whole application and be astonished that the DB remains empty at the end. Something in between goes wrong, and that's why you have to find out which step that is.
- 724 Posts
- 3 Reply Likes
document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
if(navigator && navigator.network && navigator.network.connection && navigator.network.connection.type == Connection.NONE) {
$( ":mobile-pagecontainer" ).pagecontainer( "load", "offline.html", {transition:'flip' } );
}
var x = $('p');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
else {
$("p").text("Geolocation is not supported by this browser.");
}
function showPosition(position) {
var latlon = position.coords.latitude+ "," +position.coords.longitude;var img_url = "http://maps.googleapis.com/maps/api/staticmap?mytimestamp="+new Date().getTime()
+"¢er="+latlon
+"&zoom=16&size=220x220&sensor=false&markers="+latlon
+"&size:mid%7Ccolor:0xff0000%7Clabel:%7Camroha,+uttar+pradesh&visual_refresh=true";
$("#mapholder").html("<img src='"+img_url+"'>");
$("#lat").val(position.coords.latitude);
$("#lon").val(position.coords.longitude);
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
$("p").text("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
$("p").text("Location information is unavailable.");
break;
case error.TIMEOUT:
$("p").text("The request to get user location timed out");
break;
case error.UNKNOWN_ERROR:
$("p").text("An unknown error occurred.");
break;
}
}
}
function onOnline() {
// Only go back if user went to offline.html
if ($.mobile.activePage[0].baseURI.indexOf("offline.html") > -1) {
$.mobile.back();
}
}
function onOffline() {
$( ":mobile-pagecontainer" ).pagecontainer( "change", "offline.html", {transition:'flip' } );
}
});
</script>
See this coding, after lots of trials, i found that everything is bound in the deviceready event.
So, neither map image nor lat lon values can be seen on local host.
Yesterday I build app to check image and lat and lon.
But unfortunately weather is bad here since some days.
Cloudy weather...
M I right...?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
1. var x = $('p');
How many P-elements do you have in your page? How many will you have after a year, when you made several changes? Is this variable 'x' supposed to be an array?
2.
$("#lat").val(position.coords.latitude);
$("#lon").val(position.coords.longitude);
This will be correct, unless you don't have any DOM elements in the current page with these id's.
- 724 Posts
- 3 Reply Likes
2. Yes, I also did like this. I have two input elements see:
<input id="lat" value="" type="hidden"><input id="lon" value="" type="hidden">
Cordially thanks :)
- 724 Posts
- 3 Reply Likes
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
- 724 Posts
- 3 Reply Likes
I was right lat and lon values are storing in those elements,, but when i build.

but image is not showing, let me catch mistake why is not loading............
- 724 Posts
- 3 Reply Likes
1) Petra, image is not loading
, map image....I don't know why?
see it's looking like this:
2) Can i remove getCurrentPosition from deviceReady Event?
Because, when app is starting gps is searching for location, sometime we are late to open post document page, so it's showing request for get location is timeout...can i give this on documentready function instead of deviceready?
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
No. You first need to let the cordova.js initialize the plugins bridge, otherwise the geolocation plugin will not be active.
- 724 Posts
- 3 Reply Likes
So Please Petra once check please if i have made some mistakes....please:
<script>
$(document).ready(function() {
document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
if(navigator && navigator.network && navigator.network.connection && navigator.network.connection.type == Connection.NONE) {
$( ":mobile-pagecontainer" ).pagecontainer( "load", "offline.html", {transition:'flip' } );
}
var x = $('#maperror');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError,{enableHighAccuracy: true, timeout: 20000});
}
else {
$("#maperror").text("Geolocation is not supported by this browser.");
}
function showPosition(position) {
var latlon = position.coords.latitude+ "," +position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?mytimestamp="+new Date().getTime()
+"¢er="+latlon
+"&zoom=16&size=220x220&sensor=false&markers="+latlon
+"&size:mid%7Ccolor:0xff0000%7Clabel:%7Camroha,+uttar+pradesh&visual_refresh=true";
$("#mapholder").html("<img src='"+img_url+"'>");
$("#lat").val(position.coords.latitude);
$("#lon").val(position.coords.longitude);
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
$("#maperror").text("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
$("#maperror").text("Location information is unavailable.");
break;
case error.TIMEOUT:
$("#maperror").text("The request to get user location timed out");
break;
case error.UNKNOWN_ERROR:
$("#maperror").text("An unknown error occurred.");
break;
}
}
}
function onOnline() {
// Only go back if user went to offline.html
if ($.mobile.activePage[0].baseURI.indexOf("offline.html") > -1) {
$.mobile.back();
}
}
function onOffline() {
$( ":mobile-pagecontainer" ).pagecontainer( "change", "offline.html", {transition:'flip' } );
}
});
</script>
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
If the image doesn't display, then most likely the url is incorrect. Have you debugged that?
- 724 Posts
- 3 Reply Likes
- 724 Posts
- 3 Reply Likes

Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
- 724 Posts
- 3 Reply Likes
- 724 Posts
- 3 Reply Likes
Can we make good friends :) although i am not able to be friend of adobe co. champion.
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
The picture indicates that an image element has been inserted into html, and the actual image could not be found online. So it must be either whitelisting or a wrong url.
Have you tried the whole app in a regular browser?
Have you tried retrieving and displaying the url from the img.src attribute after inserting it in your DOM?
- 724 Posts
- 3 Reply Likes
WHen I reset the APN settings as default. Image was showing :) :)
- 724 Posts
- 3 Reply Likes
Sorry, i am not ordering you, like always requesting you sir. with this busy schedule how i am creating this i really can't tell. With office full day duty. Mid night. sometime when i am so much tired, i sleep but when open my eyes, iquick open laptop and work..............
But Thank You after GOD. Because He make u interface for me to help.
And without irritating you are always here, i can't pay thanks Petra, :)
May GOD Bless YOu and your family
Is that Correct?
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown(e) {
e.preventDefault();
}Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
The same way you are handling the back button at your main (index) page. Catch the 'backbutton' event. In this case, in the callback function, call the event.preventDefault() method.
- 724 Posts
- 3 Reply Likes
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
I hope you coded it in such a way that it works differently on index, because otherwise the back button would always dismiss your app.
- 724 Posts
- 3 Reply Likes
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
That function could contain a switch, evaluating the current page. In semi-code:
function myBackButton(e) {
if (currentpage is 'index') {exitApp();}
elseif (currentpage is 'offline') {e.preventDefault();}
else {}
}
- 724 Posts
- 3 Reply Likes
- 724 Posts
- 3 Reply Likes
<script>
$(document).ready(function() {
document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);
document.addEventListener("backbutton", mybackButton, false);
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
if(navigator && navigator.network && navigator.network.connection && navigator.network.connection.type == Connection.NONE) {
$( ":mobile-pagecontainer" ).pagecontainer( "load", "offline.html", {transition:'flip' } );
}
var x = $('#maperror');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError,{enableHighAccuracy: true, timeout: 20000});
}
else {
$("#maperror").text("Geolocation is not supported by this browser.");
}
function showPosition(position) {
$("#lat").val(position.coords.latitude);
$("#lon").val(position.coords.longitude);
var latlon =position.coords.latitude+","+position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?mytimestamp="+new Date().getTime()+"¢er="+latlon+"&zoom=16&size=220x220&sensor=false&markers="+latlon+"&size:mid%7Ccolor:0xff0000%7Clabel:%7Camroha,+uttar+pradesh&visual_refresh=true";
$("#mapholder").html("<img src='"+img_url+"'>");
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
$("#maperror").text("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
$("#maperror").text("Location information is unavailable.");
break;
case error.TIMEOUT:
$("#maperror").text("Google Map couldn't loaded, Please reload the page to get user location");
break;
case error.UNKNOWN_ERROR:
$("#maperror").text("An unknown error occurred.");
break;
}
}
}
function mybackButton(e) {
if ($( ":mobile-pagecontainer" ).pagecontainer( "getActivePage" )[0].id=="page") {
exitApp();}
else if ($( ":mobile-pagecontainer" ).pagecontainer( "getActivePage" )[0].id=="offline") {e.preventDefault();}
}
function onOnline() {
// Only go back if user went to offline.html
if ($.mobile.activePage[0].baseURI.indexOf("offline.html") > -1) {
$.mobile.back();
}
}
function onOffline() {
$( ":mobile-pagecontainer" ).pagecontainer( "change", "offline.html", {transition:'flip' } );
}
});
</script>
Petra V., Champion
- 7794 Posts
- 1391 Reply Likes
Did you test it?
- 724 Posts
- 3 Reply Likes
Related Categories
-
PhoneGap Build
- 15111 Conversations
- 275 Followers
-
Plugins
- 1283 Conversations
- 38 Followers

