submit form php without refresh page - php

I'm working on a PHP application i want to submit form without refresh page. Actually, i want my php code to be written on the same page as the one containing html and jquery code.
In order to submit form using jquery i've written this code
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
$.post("php-opt.php", //Required URL of the page on server
{ // Data Sending With Request To Server
selectrefuser:vname,
},
function(response,status){ // Required Callback Function
//alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
});
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
//return false;
//e.preventDefault();
//$("#monbutton:hidden").trigger('click');
});
});
and my php code is :
<?php
$resclient_alt = 1;
$resclient_long = 1;
if(isset($_POST['selectrefuser'])){
$client = $_POST['selectrefuser'];
echo $client;
$client_valide = mysql_real_escape_string($client);
$dbprotect = mysql_connect("localhost", "root", "") ;
$query_alt= "SELECT altitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1_alt=mysql_query($query_alt, $dbprotect);
$row_ss_alt = mysql_fetch_row($query_resclient1_alt);
$resclient_alt = $row_ss_alt[0];
//echo $resclient_alt;
$query_gps= "SELECT longitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1=mysql_query($query_gps, $dbprotect);
$row_ss_ad = mysql_fetch_row($query_resclient1);
$resclient_long = $row_ss_ad[0];
}
?>
My form is as below
<form id="form1" name="form1" method="post" >
<label>
<select name="selectrefuser" id="selectrefuser">
<?php
$array1_refuser = array();
while (list($key,$value) = each($array_facture_client_refuser)) {
$array1_refuser[$key] = $value;
?>
<option value="0" selected="selected"></option>
<option value="<?php echo $value["client"];?>"> <?php echo $value["client"];?></option>
<?php
}
?>
</select>
</label>
<button id="btn">Send Data</button>
</form>
My code does these actions:
select client get its GPS coordinates
recuperates them in php variable
use them as jquery variable
display marquer on map
So since i do this steps for many clients i don't want my page to refresh.
When i add return false or e.preventDefault the marquer is not displayed, when i remove it the page refresh i can get my marquer but i'll lost it when selecting another client.
is there a way to do this ?
EDIT
I've tried using this code, php_query.php is my current page , but the page still refresh.
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Edit
When adding e.preventDfault , this code doesn't seem to work
$( "#monbutton" ).click(function() {
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
$('#myResults').html("je suis "+php_long);
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
});
This code recuperate this value var vname = $("#selectrefuser").val(); get result from sql query and return it to jquery .

It will refresh since you have not prvent default action of <button> in script
$("#btn").click(function(e){ //pass event
e.preventDefault(); //this will prevent from refresh
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Updated
Actually, i want my php code to be written on the same page as the one containing html and jquery code
You can detect the ajax call on php using below snippet
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special code here */
}

Related

How to fetch data from database based on user input and display as JSON array using asynchronous POST in php

I have 1 php page which establishes connection to the database and fetches data from the database using JSON array (this code is working fine).
index2.php
<?php
class logAgent
{
const CONFIG_FILENAME = "data_config.ini";
private $_dbConn;
private $_config;
function __construct()
{
$this->_loadConfig();
$this->_dbConn = oci_connect($this->_config['db_usrnm'],
$this->_config['db_pwd'],
$this->_config['hostnm_sid']);
}
private function _loadConfig()
{
// Loads config
$path = dirname(__FILE__) . '/' . self::CONFIG_FILENAME;
$this->_config = parse_ini_file($path) ;
}
public function fetchLogs() {
$sql = "SELECT REQUEST_TIME,WORKFLOW_NAME,EVENT_MESSAGE
FROM AUTH_LOGS WHERE USERID = '".$uid."'";
//Preparing an Oracle statement for execution
$statement = oci_parse($this->_dbConn, $sql);
//Executing statement
oci_execute($statement);
$json_array = array();
while (($row = oci_fetch_row($statement)) != false) {
$rows[] = $row;
$json_array[] = $row;
}
json_encode($json_array);
}
}
$logAgent = new logAgent();
$logAgent->fetchLogs();
?>
I created one more HTML page where i am taking one input (userid) from the user. Based on userid, i am fetching more data about that user from the database. Once the user enters userid and clicks on "Get_Logs" button, more data will be fetched from the the database.
<!DOCTYPE html>
<html>
<head>
<title>User_Logs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$uid =$_POST["USERID"];
}
?>
<form method="POST" id="form-add" action="index2.php">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
</body>
</html>
My script:
$(document).ready(function(){
$("#mybtn").click(function(){
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
})
This code is working fine. However it is synchronous POST & it is refreshing my page, However i want to use asynchronous POST. How can i do that? I have never done this asynchronous POST coding. Kindly help.
i tried this & it not throwing error but there is no output. Can someone please check what is wrong in my code.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.post("index2.php", {data :'<?php echo json_encode($json_array);?>'
})
});
})
I assume that index2.php is another php page (not the same) and it is returning the data that you want to update on the page where you run this code on.
$(document).ready(function(){
$("#mybtn").click(function(e){
e.preventDefault();
$.POST("index2.php", {
var myVar = "<?php echo json_encode($json_array); ?>";
});
});
})
you need to add preventDefault in your click handler to prevent the form from being submitted. This will stop the form to be submitted and the page to be reloaded. Inside the POST you can setup the logic to refresh the page with the updated data (without reloading)
Can you try this,
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
$.POST("index2.php", {
var myVar = <?php echo json_encode($json_array); ?>;
});
});
});
Also in HTML remove action in form
<form method="POST" id="form-add">
USER_ID: <input type="text" name="USERID"/><br>
<input type="submit" name="submit" id = "mybtn" value="Get_Logs"/>
</form>
Edit :
Can you try this please ? Second param for post takes an object .
$(document).ready(function(){
$("#mybtn").click(function(event){
event.preventDefault();
var myVar = <?php echo json_encode($json_array); ?>;
console.log(myVar);
$.post("submit.php", {
'id': myVar
},function(data){
console.log(data);
});
});
});

AJAX Form Submission Not Querying PHP

Trying to use AJAX to submit form data to a PHP file. Everything in the code seems to work except for a call to the PHP file.
I setup a Java Alert() on the PHP file and it never alerts.
I am sure it is an issue with the AJAX code but I don't know it well enough to figure out what is going wrong.
The AJAX Call:
$(document).on('click','.addItem',function(){
// Add Item To Merchant
var el = this;
var id = this.id;
var splitid = id.split("_");
// Add id's
var addid = splitid[1]; // Merchant ID
var additem = splitid[2]; // Item ID
// AJAX Request
$.ajax({
url: "jquery/addItem.php",
type: "POST",
data: { mid : addid , iit : additem },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(300, function(){
$(this).remove();
});
}
});
});
The HTML Form Call Within a Table:
<span class='addItem' id='addItem_<?php echo $m; ?>_<?php echo $list['id']; ?>' >Add Item</span>
Ok Simple PHP code that it calls to with some alerts for testing:
<?php
require_once("../includes/constants.php");
require_once("../includes/functions.php");
$iid = filter_input(INPUT_POST, 'iit', FILTER_SANITIZE_STRING); // Item ID
$mid = filter_input(INPUT_POST, 'mid', FILTER_SANITIZE_STRING); // Merchant ID
$slot = 0;
$slot = getMerchSlot($mid);
?>
<script>
alert ("Slot Value: <?php echo $slot; ?>");
</script>
<?php
$result = $pdoConn->query("INSERT INTO merchantlist (merchantid, item, slot)
VALUES
('$mid', '$iid', '$slot') ");
if ($result) {
?>
<script>
alert("Looks like it worked");
</script>
<?php
}
echo 1;
?>

Passing value correctly to PHP from AJAX Code

So I'm trying to pass a value from my AJAX code to my PHP code which connects to an API to get the weather. It works when just using PHP, but I want ajax to return the results to some div on the same page. My code looks correct when I compare it to other examples but it just doesn't work.
Code may not be written with security in mind, standard practice etc, I'm just trying to play around with API's and get the basics of AJAX.
api.php:
$city = $_POST['city'];
function getCityLat($x) {
$latUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $x .'APIKEY';
$latResponse = file_get_contents($latUrl);
$latArray = json_decode($latResponse, true);
$lat = $latArray['results'][0]['geometry']['location']['lat'];
echo $lat;
return $lat;
}
function getCityLng($y) {
$lngUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='. $y .'APIKEY';
$lngResponse = file_get_contents($lngUrl);
$lngArray = json_decode($lngResponse, true);
$lng = $lngArray['results'][0]['geometry']['location']['lng'];
echo $lng;
return $lng;
}
function getWeather($x, $y) {
$weatherUrl = 'https://api.darksky.net/forecast/APIKEY/' . $x . ',' . $y;
$weatherResponse = file_get_contents($weatherUrl);
$weatherArray = json_decode($weatherResponse, true);
$timeZone = $weatherArray['timezone'];
$locWeather = $weatherArray['currently']['temperature'];
$locFeelsLike = $weatherArray['currently']['apparentTemperature'];
$windSpeed = $weatherArray['currently']['windSpeed'];
$weatherSummary = $weatherArray['currently']['summary'];
$time = $weatherArray['currently']['time'];
$outputweather = '<p>Temp: '.$locWeather.'</p>';
echo $outputweather;
}
getWeather(getCityLat($city), getCityLng($city));
?>
index.php(html):
<h3 align="center">Weather</h3>
<form align="center" method="POST">
<input type="text" id="city" name="city" placeholder="Enter City">
<button class="btn btn-xs btn-success" name="city_go" id="city_go">Go</button>
</form>
<div id="weather"></div>
JQuery:
function getWeather(city) {
$.ajax({
url: "api.php",
method: "POST",
data: {city:city},
dataType: "text",
success: function(data) {
$('#weather').html(data);
}
});
}
$(document).on('click', '#city_go', function() {
var city = $('#city').val();
getWeather(city);
});
The problem is that you are submitting a form, which forces a page refresh. Everything else is working correctly, just the page is being refreshed. To fix that you need to update your click event to something like
$(document).on('click', '#city_go', function(e) {
e.preventDefault();
var city = $('#city').val();
getWeather(city);
});
the preventDefault() call will cancel the default action of the form (the page refresh) and allow the AJAX call to follow through and display the data.

echo data into drop list using AJAX

I have this code, where when I click on a value in my first drop list, I need to get new data from MySQL into my second drop list according to my selection.
I have this code here:
$('#sale_type').change(function() {
// get the form information
// this can be done in many ways but we are going to put the form
// data into a data object
var formData = {
'selectedValue' : $('#sale_type').val()
};
// send the data via Ajax
$.ajax({
type : 'POST', // the method we want to use to send the data
url : 'getTypeDetails.php', // the url where we want to
// send the data
data : formData, // the data object we created
dataType : 'json', // what type of data we want to get back
encode : true
})
// execute function when data has been sent and server
// code is processed
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
});
});
And here is getTypeDetails.php:
<?php
require_once('../include/global.php');
$data = $_POST['selectedValue'];
// Connect to database
// Use the data to get the new information
$query = "SELECT * FROM purchases WHERE sale_type = :data";
// MySQL
$results = $conn->prepare($query);
$results->bindValue(":data", $data);
$exec = $results->execute();
$res = $results->fetchAll();
$data = array();
$i = 0;
foreach($res as $row){
$data[i] = $row['sale_details'];
$i++;
}
echo json_encode($data);
?>
the problem is that I can't get the $data[i] into my new drop list with an id=sale_details
So I don't know what to put here:
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
EDIT
Those are my HTML drop lists:
<label for="sale_type" class="col-lg-1 control-label" style="float:right">النوع</label>
<select id="sale_type" name="sale_type" class="dropdown-header" style="float:right">
<option value="undefined">اختر</option>
<?php
foreach($fetchType as $ft){ ?>
<option value="<?php echo $ft['sale_type'] ?>"><?php echo $ft['sale_type'] ?></option>
<?php } ?>
</select>
<label for="sale_details" class="col-lg-1 control-label" style="float:right">الصنف</label>
<select id="sale_details" name="sale_details" class="dropdown-header" style="float:right">
</select>
It should be something like this:
.done(function(data) {
var secondDropdown = $("#second-dropdown");
secondDropdown.empty();
$.each(data, function(index, value) {
secondDropdown.append("<option>" + value + "</option>");
});
return;
}
Replace your js code with my code
<script>
$(document).ready(function() {
$('#sale_type').change(function() {
var formData = { 'selectedValue' : $( "#sale_type option:selected" ).val() };
console.log(formData);
$.ajax({
type: 'POST',
url: 'getTypeDetails.php',
data: formData,
success: function(data){
var obj = jQuery.parseJSON(data);
var secondDropdown = $("#sale_details");
secondDropdown.html('');
for (var prop in obj) {
secondDropdown.append("<option>" + obj[prop] + "</option>");
}
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
});
});
</script>
and add jquery link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
in your <head> tag

Select Dropdown onChange options

I have a question that I am designing a webpage to process database. So the idea is,
I have a dropdown
When user click on of the options,
Directly open a new window containing another webpage
On the new page, getting the value from the dropdown on the new page for the database monitoring with $_POST
The problem is, When I click the option, it redirects to that new page but not in the form of a new window.
And how do I send the selected value to be used on the new page with
$newVal = strval($_POST['PROJECT_NAME']);
My code is,
<script>
$(function(){
$('#cd-dropdown').bind('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = "monitorIndex.php"; // redirect
}
return false;
});
});
</script>
And the markups:
$projectParse = oci_parse($conn, 'SELECT DISTINCT PROJECT_NAME FROM MASTER_DRAWING '
. 'ORDER BY PROJECT_NAME ASC');
oci_execute($projectParse);
echo '<select name="cd-dropdown "id="cd-dropdown" class="cd-select">';
echo '<OPTION VALUE="">PROJECT SELECT</OPTION>';
while($row = oci_fetch_array($projectParse,OCI_ASSOC)){
$projectName = $row ['PROJECT_NAME'];
echo "<OPTION VALUE='$projectName'>$projectName</OPTION>";
}
echo '</select>';
Try this one.
$('#cd-dropdown').change(function(){
var id = $(this).val();
window.location = 'monitorIndex.php?id=' + id;
});
Try the below code
$('#cd-dropdown').change(function(){
var id = $(this).val();
$.ajax({
type: "POST",
url: "monitorIndex.php",
data: { PROJECT_NAME: id }
})
.done(function( msg ) {
var myWindow = window.open("", "MsgWindow", "width=800, height=800");
myWindow.document.write(msg );
});
});
This method should take you to new window with ProjectName in URL.
$('#dropdown').change(function(){
var id = $(this).val();
window.open ('monitorIndex.php?id=' + id ,'_blank');
});
Or another way is if you are using HTML5 , you can use local storage,
You can basically keep the value on client side localstorage and can access it on any other page.
// Store
localStorage.setItem("projectname", "abc");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("projectname");

Categories