Jquery/AJAX populated HTML form when dropdown selected - javascript

I am trying to populate a form on my page. The information required to populate the form is pulled from a MySQL database using the ID of the drop down option as the ID in the SQL statement. I was thinking that I can store the information in $_SESSION['formBookings'] and on a refresh this will populate the form (this is already happening as I am using the session variable to populate the form after a submit.
I can not have a submit button attached to the form as I already have one and the boss doesn't want another. I would like the form to eventually automatically refresh the page on the selection of an option. If the data from the SQL statement has been stored in the session array then the form will be populated.
Here is what I have so far:
The JQuery:
<script>
$(document).ready(function(){
$('select[name=recall]').on('change', function() {var recall = $(this).val()
//$(function ()
//{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'recall.php', //the script to call to get data
data: "recall: recall", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('div#box1').load('DFBristol.html');//html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome
// http://api.jquery.com/category/selectors/
//}
});
});
});
});
</script>
The HTML:
<select name='recall' id='recall'>
<option selected></option>
<?php
session_start();
$user = 'root';
$pass = '';
$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$recall = $DBH->prepare('SELECT * FROM bookings WHERE dateInputted >= now() - INTERVAL 2 DAY');
$recall->execute();
$recallResult = $recall->fetchALL(PDO::FETCH_ASSOC);
foreach ($recallResult as $key) {
echo '<option id='.$key["ID"].'>'.$key['ID'].' - '.$key['branch'].' - '.$key['title'].' '.$key['firstName'].' '.$key['lastName'].'</option>';
}
?>
</select><br />
The SQL file (recall.php):
<?php
$user = 'root';
$pass = '';
$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$recall = $DBH->prepare("SELECT * FROM bookings WHERE ID = '%$recall%'");
$recall->execute();
$recallFormResult = $recall->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($recallFormResult);
?>
I have tried to pass the variable 'recall' from the jquery into the SQL statement using the data argument but nothing happens.
Could someone please help me understand what I am doing wrong and how I can resolve it.

On a quick glance there seems to be two issues with the code you've posted so far:
The AJAX request
Even though $.ajax() defaults to a request type of GET by default, it's good to specify it. There is also a syntax error in your request — you have closed the success callback with a }); where it should be a } only:
$.ajax({
url: "recall.php",
data: {
recall: recall
},
type: "GET", // Declare type of request (we use GET, the default)
dataType: "json",
success: function(data)
{
var id = data[0];
var vname = data[1];
$('div#box1').load('DFBristol.html');
} // The problematic closure
});
Even better: instead of using the deprecated jqXHR.success() function, use the .done() promise object instead, i.e.:
$.ajax({
url: "recall.php",
data: {
recall: recall
},
type: "GET", // Declare type of request (we use GET, the default)
dataType: "json"
}).done(function() {
// Success
var id = data[0],
vname = data[1];
$('div#box1').load('DFBristol.html');
});
Fixing the file recall.php
When you make an AJAX GET request to recall.php, the file needs to know what variables you intend to pass, which you have not defined. You can do that using $_GET[] (see doc), i.e.:
<?php
// Assign the variable $recall with the value of the recall query string from AJAX get request
// I recommend doing a check to see if $_GET['recall'] is defined, e.g.
// if($_GET['recall']) { $recall = $_GET['recall']; }
$recall = $_GET['recall'];
// The rest of your script, unmodified
$user = 'root';
$pass = '';
$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$recall = $DBH->prepare("SELECT * FROM bookings WHERE ID = '%$recall%'");
$recall->execute();
$recallFormResult = $recall->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($recallFormResult);
?>
Note: However, if you choose to make a POST request, then you should use $_POST[] (see doc) instead :)

Related

php file's code not executing through ajax call

I have a button in my PHP file, and when I click on that button, I want another PHP file to run and save some data in a MySQL table. For that I am using AJAX call as suggested at this link (How to call a PHP function on the click of a button) which is an answer from StackOverflow itself.
Here is my show_schedule file from which I am trying to execute code of another PHP file:
$('.edit').click(function() {
var place_type = $(this).attr("id");
console.log(place_type);
$.ajax({
type: "POST",
url: "foursquare_api_call.php",
data: { place_type: place_type }
}).done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
});
});
here 'edit' is the class of the button and that button's id is being printed in the console correctly.
here is my foursquare_api_call.php file (which should be run when the button is clicked):
<?php
session_start();
include('connection.php');
if(isset($_POST['place_type'])){
$city = $_SESSION['city'];
$s_id = $_SESSION['sid'];
$query = $_POST['place_type'];
echo "<script>console.log('inside if, before url')</script>";
$url = "https://api.foursquare.com/v2/venues/search?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&v=20180323&limit=10&near=$city&query=$query";
$json = file_get_contents($url);
echo "<script>console.log('inside if, after url')</script>";
$obj = json_decode($json,true);
for($i=0;$i<sizeof($obj['response']['venues']);$i++){
$name = $obj['response']['venues'][$i]['name'];
$latitude = $obj['response']['venues'][$i]['location']['lat'];
$longitude = $obj['response']['venues'][$i]['location']['lng'];
$address = $obj['response']['venues'][$i]['location']['address'];
if(isset($address)){
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude, address) VALUES ($name, $latitude, $longitude, $address)");
$result = $statement->execute();
}
else{
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude) VALUES ($name, $latitude, $longitude)");
$result = $statement->execute();
}
}
}
?>
none of the console.log is logged in the console and also the 'temp' table is not updated. Can anyone tell me where I am making mistake? Or is it even possible to execute the code of a PHP file like this?
Your JavaScript is making an HTTP request to the URL that executes you PHP program.
When it gets a response, you do this:
.done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
}
So you:
Alert something
Show a model
At no point do you do anything with data, which is where the response has been put.
Just sending some HTML containing a script element to the browser doesn't cause it to turn that HTML into a DOM and execute all the script elements.
You'd need to do that explicitly.
That said, sending chunks of HTML with embedded JS back through Ajax is messy at best.
This is why most web services return data formatted as JSON and leave it up to the client-side JS to process that data.
to return the contents of php code you can do something like this
you can use any call to this function
function check_foursquare_api_call(place_type) {
var place_type= encodeURIComponent(place_type);
var xhttp;
//last moment to check if the value exists and is of the correct type
if (place_type== "") {
document.getElementById("example_box").innerHTML = "missing or wrong place_type";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("example_box").innerHTML = xhttp.responseText;
$('#userModal_2').modal('show');
}
};
xhttp.open("GET", "foursquare_api_call.php?place_type="+place_type, true);
xhttp.send();
}
this will allow you to send and execute the code of the foursquare_api_call file and return any elements to example_box, you can return the entire modal if you want,
you can use any POST / GET method, monitor the progress, see more here
XMLHttpRequest

How to get variable value from PHP to Java Script via AJAX?

I have created a chat website. I send the message with AJAX to PHP and the MySql Database. The messages are fetched using AJAX which runs per second. But this lead to fetch of all the messages (from starting to end). I came with an solution that I will pass the last message ID to the AJAX/JAVA SCRIPT and then fetch only the messages which are more than that.
Here is the Java Script / AJAX
function fetchdata(){
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
data : {cuser:cuser, ouser:ouser},
success: function(read){
$("#readarea").html(read);
}
});
}
Here is the PHP code to get messages:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
$result = mysqli_query($conn, $sql) or ("Query Failed");
while($row=mysqli_fetch_assoc($result)){
if($row["fromid"]==$_POST['cuser']){
echo "<div class='cuser'>".$row["message"]."</div>";
}else{
echo "<div class='ouser'>".$row["message"]."</div>";
}
}
Here I want to get the ID (message) in the Java Script function back from the PHP and use it as a variable for fetching the messages which will be more than it.
You should return JSON from the PHP, instead of HTML. That way you can return an object with properties such as ID, message, etc. Then you can use Javascript to store the latest ID, and also to put the message into your page with the relevant HTML.
Something like this:
PHP:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
if (!empty($_POST["lastid"]) $sql .= " AND id > {$_POST['lastid']}";
$result = mysqli_query($conn, $sql) or ("Query Failed");
$messages = array();
while($row=mysqli_fetch_assoc($result)){
$messages[] = $row;
}
echo json_encode($messages);
JS:
//make this global so it persists beyond each call to fetchdata
var lastMessageID = null;
function fetchdata()
{
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
dataType: "json",
data : { cuser: cuser, ouser: ouser, lastid: lastMessageID },
success: function(read) {
for (var i = 0; i < read.length; i++)
{
var className = "ouser";
if (read[i].fromid == cuser) classname = "cuser";
$("#readarea").append("<div class='" + className + "'>" + read[i].message + "</div>");
lastMessageID = read[i].id;
}
}
});
}
P.S. Please also take note of the comment about about SQL injection and fix your query code, urgently. I haven't done it here for the sake of brevity, but it must not be ignored.

How to call php function from html select option onChange?

So Ive been struggling with this problem all day and can't seem to get around it.
I need to call a php query whenever an option from a dropdown menu is selected.
<select class="selectpicker" id="headSelector">
<?php
$cname = $_GET['cname'];
$linkID = mysql_connect("localhost","USER","PASS");
mysql_select_db("USR", $linkID);
$SQLCurr = "SELECT `AName` FROM `Char-Armor` WHERE `CName` = '$cname' AND `AType`= 'Head'";
$currHeadValues = mysql_query($SQLCurr, $linkID);
$currRow = mysql_fetch_row($currHeadValues);
$curr = $currRow[0];
if($curr == '' || $curr == NULL){
$curr = 'None';
}
$SQLHead = "SELECT AName FROM `Armor` WHERE AType = 'Head'";
$allHeadValues = mysql_query($SQLHead, $linkID);
echo "<option>".$curr."</option>";
while($row = mysql_fetch_assoc($allHeadValues)){
echo "
<option>".$row['AName']."</option>
";
}
?>
</select>
The php part needs to take the 'AName' from the option and use it to insert into a table.
I have done a lot of reading about AJAX but I do not quite understand how it is supposed to work. I think it is like html -> js -> Ajax -> php
I need it to stay on the same page when an option is selected.
Any explanation would be great, thanks!
Here's what you can do.
1). As soon as an option is selected, run a jquery onchange event and get the value of the selected option.
2). Now, run an ajax request with the value of the selected value and post this data to a backend php file.
3). Now on this backend php file, receive data and process (run the query).
Code Sample.
Change your option line in this way.
<option value="$row['AName']">".$row['AName']."</option>
jQuery-Ajax
$("#headSelector").change(function(e){
//get the value of the selected index.
value = $(this).val();
//make an ajax request now
$.ajax({
url: 'yourPhpBackendScript.php',
type: 'POST',
data: {value: value},
success:function(response)
{
alert(response);
}
})
})
yourPhpBackendScript.php
//You can now receive the selected value as $_POST['value'];
//get the value now
$value = $_POST['value'];
//you can apply validations if you want.
//Now, run the query and send a response. Response can be a simple message like data submitted etc. So
runQueryHere
echo "inserted"; //response returned to ajax rquest
First of all, return the string like this:
$options_arr = '';
while($row = mysql_fetch_assoc($allHeadValues)){
$options_arr .= "<option>".$row['AName']."</option>
";
}
echo $options_arr;
Use the change event like this:
$("#headSelector").change(function(){
$.ajax({
data: '',
url: 'your_url',
type: 'POST',//Or get
success: function(options_array){
$("#headSelector").empty().append(options_str);
}
});
});

Getting a value from Javascript in PHP [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am not very experienced in web programming and am attempting to run a script which updates my database.
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts)
<?php
include_once 'accounts/config.php';
$text = ...;
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
}
</script>
I have no idea what to put in the $text section as shown with $text = ...; in order to get the variable texts from above.
EDIT
I have updated my code but the function does not seem to be accessing the PHP file. I am using a button to call the function and I have also tested it so i know the function is being called. My file is called update.php and is in the same directory as this file.
<button onclick="myFunction()">Click This</button>
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: "update.php",
type: "POST",
data: {texts:texts},
success: function(response){
}
});
}
</script>
you can post your $texts value to other php page using ajax and get the variable on php page using $_POST['texts'] and place update query there and enjoy....
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: 'update.php',
type: "POST",
data: {texts:texts},
success: function(response)
{
}
});
And your php file will be named as update.php
<?php
include_once 'accounts/config.php';
$text =$_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE `enemies` SET `text`='".$text."' WHERE `id`=1";
$result = mysql_query($query) or die(mysql_error());
?>
PHP runs on the server and then generates output which is then returned to the client side. You can't have a JavaScript function make a call to inlined PHP since the PHP runs before the JavaScript is ever delivered to the client side.
Instead, what you'd need to do is have your function make an AJAX request to a server-side PHP script that then extracts the data from the request body and then stores it in the database.
PHP: "/yourPhpScript.php"
<?php
include_once 'accounts/config.php';
$text = $_POST['data'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text='".$text.'" WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
JavaScript:
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts);
// append data as a query string
var params = 'data='+texts;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
// when server responds, output any response, if applicable
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
// replace with the filename of your PHP script that will do the update.
var url = '/yourPhpScript.php';
xmlhttp.open("POST", url, true);
xmlhttp.send(params);
}
A word of caution: This is not a safe, production-friendly way of updating data in your database. This code is open to SQL injection attacks, which is outside the scope of your question. Please see Bobby Tables: A guide to preventing SQL injection if you are writing code that will go into production.
You are wrong in approach
You should use ajax to post 'texts' value to your php script
https://api.jquery.com/jquery.post/ and create separate php file where you will get data from ajax post and update DB
javascript:
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
type: "POST",
url: "update.php",
data: "texsts=" + texts,
success: success
});
}
</script>
update.php
<?php
include_once 'accounts/config.php';
$text = $_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
i will use PDO if i was you, what you do mysql_query are outdated, if you use my framework https://github.com/parisnakitakejser/PinkCowFramework you can do the following code.
<?php
include('config.php');
$text = $_POST['text'];
$query = PinkCow\Database::prepare("UPDATE enemies SET text = :text WHERE id = 1");
$bindparam = array(
array('text', $text, 'str')
);
PinkCow\Database::exec($query,$bindparam);
$jsonArray = array(
'status' => 200
);
echo json_encode($jsonArray);
?>
place this code in jsonUpdateEnemies.php file and call it width jQuery
<script>
function myFunction(yourText) {
$.post( 'jsonUpdateEnemies.php', {
'text' : yourText
}, function(data)
{
alert('Data updated');
},'json');
}
</script>
its a little more complex then you ask about, but its how i will resolved your problem, :)

Ajax call posting duplicates in DB

I am using to Fullcalendar jquery with php for event management. I using ajax call for adding events. The call works fine for the first event entry after refresh. But for the following event entries duplicate events are created for each entry. Not sure what causing this.
This is the error:
This is the jquery call:
Jquery
$('#evesav').bind('click',function(){
$('#evesav').attr('disabled','disabled');
var title = $('#evename').val();
var edes = $('#evedes').val();
var everegion = $('#everegion').val();
var eveserv = $('#eveserv').val();
$.ajax({
url: 'add_events.php',
data: 'title='+ title+'&start='+ start +'&end='+ end +'&edes='+ edes +'&everegion='+ everegion +'&eveserv='+ eveserv,
type: "POST",
success: function(json) {
$('#myModal').modal('hide');
$('#alertcon').html(json);
$('#alert').modal('show');
$('#evename').val("");
$('#evedes').val("");
$('#evesav').removeAttr('disabled');
$('#calendar').fullCalendar( 'refetchEvents' );
}
});
$('#calendar').fullCalendar( 'rerenderEvents' );
});
This is the PHP Code:
PHP
<?php
if(($_POST['title'] && $_POST['start'] && $_POST['end'] && $_POST['edes'] && $_POST['everegion'] && $_POST['eveserv'])!= NULL)
{
// Values received via ajax
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
$edes = $_POST['edes'];
$region = $_POST['everegion'];
$server = $_POST['eveserv'];
//echo $title."".$start."".$end."".$edes."".$region."".$server;
// connection to the database
include('includes/db.php');
// insert the records
$sql = "INSERT INTO evenement (title, start, end, edes, region, server) VALUES (:title, :start, :end, :edes, :region, :server)";
$q = $bdd->prepare($sql);
$q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server));
if($q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server))){
var_dump($q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server)));
}
$eveid=$bdd->lastInsertId();
// Get array of all source files
$files = scandir("uploads/");
// Identify directories
$source = "uploads/";
$destination = "evedata/".$eveid."/";
mkdir("evedata/".$eveid);
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file) {
unlink($file);
}
echo "Added Successfully";
}
else {
echo "Please Fill the data";
}
?>
Some one please help me with this.
I'd give each event addition form a control, for instance a dynamic GUID, which then can be used to save to DB. This way you have a GUID to work with in dealing with CalDAV protocol, if you ever choose to do as such with your calendar, as well as have a way to make certain nothing is duplicated by chance in your database.
Now, do keep in mind this is simply a patch, not a fix. Therefore, you'll do yourself a lot of good to find a way to stop the multiple attempts to add an event to your DB. Regardless of your success in finding your bug, using a control mechanism or unique identifier is a good idea.

Categories