sending variables to php via ajax and jquery - php

i want to request the users geolocation via html5-geolocation and send it to the next page
I've been told that i've to use ajax/jquery, so this is my code:
<form action="response.php">
<button onclick="getLocation()">Start</button>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function successFunction(position) {
var lat = position.coords.latitude;
var longi = position.coords.longitude;
$.ajax({
type: "POST",
url: "response.php",
data: { latitude: lat, longitude: longi }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
</form>
and now i want to "echo" the latitude and longitude on my response.php page
but i have no idea how to do :'(
I tried this:
$latitude = $_POST["latitude"];
echo $latitude;
but the page is blank

Try This:
index.html:
<html>
<head></head>
<body>
<form action="response.php" method="post">
<input type="hidden" id="latitude" name="latitude" value="" />
<input type="hidden" id="longitude" name="longitude" value="" />
<input type="submit" value="Start" />
</form>
</body>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function getLocation() {
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
successFunction(pos);
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error,options);
} else {
//x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function successFunction(position) {
var lat = position.coords.latitude;
var longi = position.coords.longitude;
$('#latitude').val(lat);
$('#longitude').val(longi);
}
getLocation();
</script>
</html>
response.php:
<?php
$latitude = $_POST["latitude"];
$longitude = $_POST["longitude"];
echo "Latitude:".$latitude."</br>";
echo "longitude:".$longitude;
?>
Just create index.html copy and paste this code and make sure that response.php like this.
/yourprojectdirectory/index.html
/yourprojectdirectory/response.php

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function successFunction(position) {
var lat = position.coords.latitude;
var longi = position.coords.longitude;
$.ajax({
type: "POST",
url: "response.php",
data:"data="+ '{ "latitude":"'+ lat+'", "longitude": "'+longi+'" }'
}).done(function(msg) {
alert( "Data Saved: " + msg );
});
}
</script>
$location =json_decode( preg_replace('/\\\"/',"\"",$_POST['data']));
print_r($location);
$lat=$location->latitude;
echo $lan=$location->longitude;

Related

How to show error message when the values was not in mysql database?

I have fetch(placing in inputboxes) the customer name and Dob from database through Customer phone . I am done the work but if I put the wrong customer number(there is no number in database) there will be show a alert box...that didn't know to me for how to do that...Can you please anyone solve my code...
<input type="text" class="search">phone
<input type="text" id="cname">name
<input type="text" id="cdob">date of birth
This is the script tag
<script>
$(document).ready(function() {
$('.search').keyup(function() {
var mobile_no = $(this).val();
$.ajax({
url: "get_customer_info.php",
method: "POST",
dataType: "json",
data:{
search : mobile_no
},
success:function(data){
$.each(data,function(id, val){
$("#cname").val(val.cname);
$("#cdob").val(val.cdob);
});
}
});
});
});
</script>
and this is query page
<?php
include("config.php");
$mobile=$_POST['search'];
$sql="SELECT * FROM `cm` WHERE cphone ='$mobile'";
$result = mysqli_query($conn,$sql,true);
if($result===true)
{
$mainarray=array();
while($row=$result->fetch_assoc())
{
$row['cm_id'];
$row['cname'];
$row['cdob'];
array_push($mainarray, $row);
}
echo json_encode($mainarray);
}
else
{
echo 'There is no data';
}
?>
Front end file:
<input type="text" class="search">phone
<input type="text" id="cname">name
<input type="text" id="cdob">date of birth
Your Script file:
<script>
$(document).ready(function() {
$('.search').keyup(function() {
var mobile_no = $(this).val();
if(mobile_no.length >= 10 ){
$.ajax({
url: "get_customer_info.php",
method: "POST",
dataType: "json",
data:{
search : mobile_no
},
success:function(responce){
if($.trim(responce)){
$.each(responce,function(id, val){
$("#cname").val(val.cname);
$("#cdob").val(val.cdob);
});
} else{
alert("no data");
}
}
});
}
});
});
</script>
This is your get_customer_info.php file
<?php
include("config.php");
$mobile=$_POST['search'];
$sql="SELECT * FROM `cm` WHERE cphone ='$mobile'";
$result = mysqli_query($conn,$sql,true);
if($result==true)
{
$mainarray=array();
while($row=$result->fetch_assoc())
{
$row['cm_id'];
$row['cname'];
$row['cdob'];
array_push($mainarray, $row);
}
echo json_encode($mainarray);
}
else
{
echo 'There is no data';
}
?>

Trying to post json content with button in php

I'm trying to post new data into my json file by using jquery by entering the values of the input but nothing happens when I do. I apologize in advance for this slightly dumb question and I'm very grateful for any help!
I'm very new to programming but I have no clue if this is even possible to do. Below is my 'index.php' file where my jquery and button is to add new data.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
<input type="text" id="name">
<input type="text" id="grade">
<button id="btn">Add</button>
</body>
<script>
$(document).ready(function(){
$.getJSON('http://localhost/mytest/json.php', function(data) {
for (i=0; i < data.length; i++) {
if (data[i].grade < 5) {
document.write("<p style='color: red;'>Name: " + data[i].name + "<br>Grade: " + data[i].grade + "</p>");
} else {
document.write("<p style='color: green;'>Name: " + data[i].name + "<br>Grade: " + data[i].grade + "</p>");
}
}
});
// posting the orders
$('#button').on('click', function() {
var order = {
name: $('#name').val(),
grade: $('#grade').val(),
}
$.ajax({
type: 'POST',
url: 'http://localhost/mytest/json.php',
data: order,
success: function(newStudent) {
}
})
});
});
</script>
</html>
Here below is the JSON file I created with PHP (json.php):
<?php
$student1 = array(
"name"=>"ali",
"grade"=>"7"
);
$student2 = array(
"name"=>"John",
"grade"=>"4"
);
$student3 = array(
"name"=>"Martha",
"grade"=>"2"
);
$student4 = array(
"name"=>"Jullie",
"grade"=>"8"
);
$student5 = array(
"name"=>"Morgan",
"grade"=>"4"
);
$students = array($student1, $student2, $student3, $student4, $student5);
$j = json_encode($students); // we 'encode' the array into a JSON format
echo $j;
?>
Hello this is a fixed version of your code
Persisten data
Remove dumplicate code for pass grade
Create a div with students data(json content)
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
Name: <input type="text" id="name"><br>
Grade: <input type="text" id="grade"><br>
<button id="button">Add</button>
<div id="students">
</div>
</body>
<script>
$(document).ready(function () {
// fill students div content with document ready
updateStudents();
$('#button').on('click', function () {
var order = {
name: $('#name').val(),
grade: $('#grade').val(),
}
$.ajax({
type: 'POST',
url: 'json.php',
data: order,
success: function (newStudent) {
console.log("Success");
$("#students").append(setStudents($('#name').val(), $('#grade').val()));
}
})
});
function updateStudents() {
$.getJSON('students.json', function (data) {
for (i = 0; i < data.length; i++) {
$("#students").append(setStudents(data[i].name, data[i].grade));
}
});
}
function setStudents(name, grade) {
var color = 'green';
if (grade < 5) {
color = 'red';
}
return "<p style='color: " + color + ";'>Name: " + name + "<br>Grade: " + grade + "</p>"
}
});
</script>
</html>
json.php
<?php
$file = "students.json";
$content = file_get_contents($file);
if ($content == null) {
$data[] = $_POST;
$jsonData = json_encode($data);
file_put_contents($file, $jsonData);
} else {
$data = $_POST;
$tempArray = (array) json_decode($content);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents($file, $jsonData);
}
echo $jsonData;
students.json
Note: the file could be empty this is just some data
[{"name":"Pedro","grade":"10"},{"name":"Juan","grade":"10"},{"name":"Lopez","grade":"10"},{"name":"Maria","grade":"5"},{"name":"Miguel","grade":"5"},{"name":"Juana","grade":"4"},{"name":"hugo","grade":"8"},{"name":"Nano","grade":"2"}]
If nothing is happening, it may be that you need to change
$('#button')
to
$('#btn')
And, no dumb questions! We're all in this together. Best of luck to you.

PHP code to insert data into mysql database is not working

I'm trying to insert data without refreshing the page using ajax and php, but the data is not getting inserted into the database.
Here is my code
<?php
require 'validation_class.php';
$obj_menufacture = new Validation_Class();
if (isset($_POST['btn'])) {
$menufacture = $obj_menufacture->menufacture_add($_POST);
}
?>
<!DOCTYPE html>
<html>
<head>
<script src='js/jquery-3.0.0.js'></script>
</head>
<body>
<div id='form_id'>
<form action='' method='post'>
<input type='text' class='m_name' name='m_name' id='m_name' onchange="names('m_name')" onkeyup="names('m_name')"/>
<span style='color:red;' id='m_name_error'></span>
<input type="submit" name='btn' value="submit" id='save'/>
</form>
</div>
<div id='cool'></div>
<style>
.border_input{
border-color:red;
}
.border_input1{
border-color:green;
}
</style>
<script>
$(document).ready(function () {
$('#save').on('click', function (e) {
e.preventDefault();
var m_name = $.trim($('#m_name').val());
var dataString = 'name='+ m_name;
if (m_name === '') {
if (m_name == '') {
$('#m_name_error').html('Please enter your name');
$('#m_name').addClass('border_input');
}
} else {
$.ajax({
url: 'validation.php',
method: 'post',
data:dataString,
success: function () {
$("#form_id").slideUp("slow");
}
});
}
});
});
function names(id) {
var val = $.trim($('#' + id).val());
if (val === '') {
$('#' + id + '_error').html('');
$('#' + id).addClass('border_input');
} else {
$('#' + id + '_error').html('');
$('#' + id).addClass('border_input1');
}
}
</script>
</body>
</html>
Here is my insert code
<?php
class Validation_Class{
public $link;
public function __construct() {
$HOST = "localhost";
$USER = "root";
$PASS = "";
$DATABASE = "store";
$this->link = mysqli_connect($HOST, $USER, $PASS, $DATABASE);
if (!$this->link) {
die('database query problem' . mysqli_error($this->link));
}
}
public function menufacture_add($data) {
$sql = "INSERT INTO menufacture(m_name)VALUES('$data[m_name]')";
if (mysqli_query($this->link, $sql)) {
$menufacture = "Menufacture insert successfully";
return $menufacture;
} else {
die('menufacruere query problem' . mysqli_error($this->link));
}
}
}
please help me what can i do to solve this
<form name="signup" id="reg" action="" method="post"enctype="multipart/form-data">
<input type='text' class='m_name' name='m_name' id='m_name' onchange="names('m_name')" onkeyup="names('m_name')"/>
<span style='color:red;' id='m_name_error'></span>
<input type="submit" name='btn' value="submit" id='save'/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#save").submit(function () {
var form_data = $('#reg').serialize();
$.ajax({
type: "POST",
url: 'setting.php',
data: $('#reg').serialize(),
success: function (data) {
alert('Data save Successfully');
}, error: function () {
alert('Some Internal Error.');
}
});
});`
</script>
settting.php
<?php
include("db_connection.php"); // include connection file
if(isset($_POST)) {
$fname = $_POST['m_name'];
$insert = "INSERT INTO `table_name`(`column_name`)VALUES('".$fname."')";
$insertion = mysqli_query($conn, $insert);
}
?>
$("#save").on("click", function () {
var form_data = $('#reg').serialize();
$.ajax({
type:"POST",
url:'setting.php',
data: $('#reg').serialize(),
success: function(data){
alert("Data save Successfully");
},error: function () {
alert('Some Internal Error.');
}
});
});

How to pass variables through ajax?

I want to pass variables from post.php to addcomment.php through the AJAX request. I have tried the code below but it does not seem to work. It reloads the page but nothing happens nor is data inserted in database
post.php
//variables to pass
$userid = $row['userid'];
$uid = $row['uid'];
$postid = $row['postid'];
<form method='post' name='form' action='' class='commentbox'>
<textarea name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit' class='comment_button'/>
</form>
<script type="text/javascript" >
var userfrom = '<?php echo $uid ?>';
var userto = '<?php echo $userid ?>';
var postid = '<?php echo $postid ?>';
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
dataString: dataString,
userfrom: userfrom,
userto: userto,
postid: postid
}
cache: false,
success: function(html){
$(".display").show(html);
}
});
}
return false;
});
});
</script>
addcomment.php
if (isset($_POST['dataString'], $_POST['userto'], $_POST['userfrom'], $_POST['postid'])) {
$userid = $_POST['userto'];
$uid = $_POST['userfrom'];
$postid = $_POST['postid'];
$comment = $_POST['dataString'];
$com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, post) VALUES (:comment, :userto, :userfrom, :post)");
$com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':post'=>$postid));
}
Create hidden fields for userid, uid and postid and assign the values.
Get the values as var userfrom = $("#uid").val(); in script (post.php). It will Work
Please try below code, just replace below code.
your page is reloaded because of add button type submit, for ajax event you need to set type button, Please check below code :
<?php
//variables to pass
$userid = $row['userid'];
$uid = $row['uid'];
$postid = $row['postid'];
?>
<form method='post' name='form' action='' class='commentbox'>
<textarea name='content' id='content'></textarea><br />
<input type='button' value='Comment' name='submit' class='comment_button'/>
</form>
<script type="text/javascript" >
var userfrom = '<?php echo $uid ?>';
var userto = '<?php echo $userid ?>';
var postid = '<?php echo $postid ?>';
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
dataString: dataString,
userfrom: userfrom,
userto: userto,
postid: postid
},
cache: false,
success: function(html){
$(".display").show(html);
}
});
}
return false;
});
});
</script>

using ajax to load from a database

every type i run this it calls the error: OnError function and i can't see why it doesn't call the success: OnSuccess,
JS:
$(document).ready(function () {
// retreving data on button click
$("#data-submit").click(LoadDataThroughAjaxCall);
//loading screen functionality - this part is additional - start
$("#divTable").ajaxStart(OnAjaxStart);
$("#divTable").ajaxError(OnAjaxError);
$("#divTable").ajaxSuccess(OnAjaxSuccess);
$("#divTable").ajaxStop(OnAjaxStop);
$("#divTable").ajaxComplete(OnAjaxComplete);
//loading screen functionality - this part is additional - end
});
// ajax call
function LoadDataThroughAjaxCall() {
$.ajax({
type: "POST",
url: "Ajax/dataloader.php",
data: '{}',
dataType: "json",
success: OnSuccess,
failure: OnFailure,
error: OnError
});
// this avoids page refresh on button click
return false;
}
// on sucess get the xml
function OnSuccess(response) {
//debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var tweets = xml.find("Table");
showOnATable(tweets);
}
// show data on a table
function showOnATable(tweets) {
//debugger;
var headers = [];
var rows = [];
// header section
headers.push("<tr>");
headers.push("<td><b>tweets</b></td>");
headers.push("<td><b>created</b></td>");
headers.push("<td><b>source</b></td>");
headers.push("</tr>");
// rows section
$.each(tweets, function () {
var tweets = $(this);
rows.push("<tr>");
rows.push("<td>" + $(this).find("tweet_text").text() + "</td>");
rows.push("<td>" + $(this).find("created_at").text() + "</td>");
rows.push("<td>" + $(this).find("source").text() + "</td>");
rows.push("</tr>");
});
var top = "<table class='gridtable'>";
var bottom = "</table>";
var table = top + headers.join("") + rows.join("") + bottom;
$("#divTable").empty();
$("#divTable").html(table);
}
// loading screen functionality functions - this part is additional - start
function OnAjaxStart() {
//debugger;
//alert('Starting...');
$("#divLoading").css("display", "block");
}
function OnFailure(response) {
//debugger;
alert('Failure!!!' + '<br/>' + response.reponseText);
}
function OnError(response) {
//debugger;
var errorText = response.responseText;
alert('Error!!!' + '\n\n' + errorText);
}
function OnAjaxError() {
//debugger;
alert('Error!!!');
}
function OnAjaxSuccess() {
//debugger;
//alert('Sucess!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxStop() {
//debugger;
//alert('Stop!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxComplete() {
//debugger;
//alert('Completed!!!');
$("#divLoading").css("display", "none");
}
PHP:
<?php
//if(isset($_POST['data'])==true&&empty($_POST['data'])==false){
require_once('../connection.php');
function clean($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
//Sanitize the POST values
//$username = clean($_POST['data']);
//$result=sqlsrv_query($conn,"execute sp_ORDER_BY_name '$username'");
$result=sqlsrv_query($conn,"select tweet_text,source from tweets");
if($result) {
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
echo $row['tweet_text'].", ".$row['source']."<br />";
}
}else {
//Login failed
echo 'Name not found';
}
}
//}
?>
HTML FORM:
</head>
<body>
<div id="banner">
<h1>P-CAT version 0.1</h1>
</div>
<div id ="content">
<h2>Sreach Catigroies</h2>
<select id="data2">
<option value="">Plece select one of the follwing</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input name="data" id="data" type="text" />
<input type="submit" id="data-submit" value="Grab">
<div id="divTable">
</div>
</div>
<div id="divLoading" style="display: none; position: absolute; top: 50%; left: 40%;
text-align: left;">
<span>
<img src="Images/ajax-loader.gif" alt="Image not found." /></span>
<br />
<span style="text-align: left; padding-left: 8px;">Loading ...</span>
</div>
<div id="navbar">
<input type="button" value="EDIT">
<input type="button" value="HISTORY">
<input type="button" value="SETTINGS">
<input type="button" value="SEARCH">
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/global.js"></script>
</body>
You have to response a json from php like,
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
$xml='<Table>';
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
$xml.='<tweet_text>'.$row['tweet_text'].'</tweet_text>';
$xml.='<source>'.$row['source'].'</source>';
// create xml tag for created_at
}
$xml.='</Table>';
echo json_encode(array('d'=>$xml));
return TRUE;
} else {
//Login failed
echo json_encode(array('d'=>'Name not found'));
}

Categories