I have been new to AJAX and i am unable to display the fetched data to 2 different elements of datepicker startdate and enddate but i was able to fetch only 1 value from ajax response.
My HTML is given below
<div class="control-group" id="startingdatee">
<label class="control-label" for="form-field-1">
Start Date
</label>
<div class="controls" style="width:265px;" id="startingdate">
<input class="span10 date-picker" id="startdate" value="" type="text" data-date-format="dd-mm-yyyy" name="startdate">
</div>
</div>
<div class="control-group">
<label class="control-label" for="form-field-1">
End Date
</label>
<div class="controls" style="width:265px;">
<input class="span10 date-picker" id="enddate" type="text" data-date-format="dd-mm-yyyy" name="enddate">
</div>
</div>
Java Script is given below which is used to get the response from the dateshow.php file and could update only 1 value that is startdate only. I used document.getElementById("startdate").value = response..
function showDate(str)
{
if (str=="")
{
return;
}
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("startdate").value = xmlhttp.responseText;
}
};
xmlhttp.open("GET","dateshow.php?q="+str,true);
xmlhttp.send();
};
and php file is dateshow.php used to get minimum date and maximum date.
<?php include('includes/db.php');
$q = $_REQUEST["q"];
//echo $q;
//$q = 41;
$query = "SELECT MIN(datetime) AS MIN,MAX(datetime) AS MAX
FROM transactions
WHERE farm_id = $q";
$run = mysqli_query($con, $query);
while($row = mysqli_fetch_array($run))
{
$mindate = $row['MIN'];
$maxdate = $row['MAX'];
}
$mindatefor = strtotime($mindate);
$startdate = date('d-m-Y',$mindatefor);
$maxdatefor = strtotime($maxdate);
$enddate = date('d-m-Y',$maxdatefor);
echo $startdate;//."#".$enddate;
?>
Try creating an array in the php script and json encoding it.
$returnData = ['start'=> $startDate, 'end'=> $endDate];
echo json_encode($returnData);
Then, when you retrieve the data using AJAX, do JSON.parse(xmlhttp.responseText)
This will return a javascript object that should look like this
{
start: some start data,
end: some end data
}
Is possibile achieve your goal using json response in example suppose that you have your page which return a json object in example :
<?php
/*do some stuff here and implementing you query, iteration and so on so
forth then provide a response with the result that you have from your
task and suppose in this case in example that $startdate="01-01-2015" and
$maxdatefor="02-02-2015"
*/
header('Content-Type: application/json');
echo json_encode(array('datepicker1' => $startdate,'datepicker2' => $maxdatefor,));
?>
it will return a json object into your javascript like
{datepicker1:01-01-2015,datepicker2=02-02-2015}
Now get those data is really simple and you can use jquery ajax request which, at my personl advice is more simple to use which use this schema
//Make your check in your function before make an ajax request in order to
//be sure that all the information, input or any other stuff is in the right
//place as well then make this call below
$.ajax({
type:"POST / GET", //IN YOUR CASE GET
url: "youurl" + "yourparamenter",//DONT FORGET TO ENCODE QUERY STRING
data: '', //NOT NECESSARY IN YOUR SPECIFIC CASE
success: function (data) {
//data is the json returned value within the reponse and you can access in this way
$("#startdate").val(data['datepicker1']);
$("#enddate").val(data['datepicker2']);
},
error: function () {
alert('Something is gone wrong!!!!');
}
});
Don't Forget: add jquery script reference in your page in head tag in order to be able to call Jquery function.
I hope that this could help you
Regards
Related
I'm creating a form to query some internal sources for some of our employees. The data received is coming back as JSON. But basically the flow is this:
HTML Form > to PHP > redirect data to HTML results page to be formatted nicely.
If there is a simpler way I am open for suggestions but I'm trying to pass the JSON that PHP script returns to the results page to be formatted nicely.
I tried using the example from w3schools but it's not working.
This is all on an internal Linux Web Server.
test.html
...
<form action="../dir/dir/xxx.php" method="GET">
IOC/Indicator:<input type="text" name="ioc">
<input type="submit" value="Submit"><br>
</form>
...
xxx.php
...
$result = print_r((curl_exec($ch)));
echo $result;
curl_close($ch);
header( 'Location: ../../dir/results.html' );
...
results.html
...
<p id="results"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("results").innerHTML = myObj;
}
};
xmlhttp.open("GET", "../dir/dir/xxx.php", true);
xmlhttp.send();
</script>
...
End results should be on the lines of:
user submits IOC,
IOC gets ran through the PHP script,
user gets redirected to the results page where data from PHP script would be displayed
My data is not inserting into database, I get a blank response from the console log and network. I'm kinda lost my javascript source code is mix with other stack overflow answers as well as my PHP code.
<form id="requestForm">
<input type="text" name="fName" id="name">
<input type="text" name="fAddress" id="address">
<input type="text" name="fComment" id="comment">
<input type="submit" value="Submit" name="nameSubmit">
</form>
<script>
document.querySelector('#requestForm').addEventListener('submit', postRequest);
function postRequest(e){
e.preventDefault();
const params = {
fName: document.querySelector('#name').value,
fAddress: document.querySelector('#address').value,
fComment: document.querySelector('#comment').value,
};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'addRequest.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function(){
console.log(this.responseText);
}
xhr.send(params);
}
</script>
</body>
Here's the PHP code:
require_once 'Database.php';
var_dump($_POST); // returns `array(0) {}`
if (isset($_POST['nameSubmit'])) {
var_dump($_POST); // shows no response
$r = $_POST['fName'];
$o = $_POST['fAddress'];
$p = $_POST['fComment'];
$query = "INSERT INTO user_request(name, address, comment) VALUES(?,?,?)";
$stmt = $db->prepare($query);
$insert = $stmt->execute([$r, $o, $p]);
if($insert){
echo 'Success';
}else{
echo 'Error';
}
}
I believe the post parameter nameSubmit does not exsist.
Use the var_dump() function for dump all $_POST
From my prespective, the only parameter given was
fName
fAddress
fComment
Why not check for request method instead?
This is better than checking if a variable exsisted or not.
You can do the checks for required parameter later after you're sure this is a POST request.
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// Do whatever you want when POST request came in
}
UPDATE :
Here is the answer you wanted!
<form id="requestForm">
<input type="text" name="fName" id="name">
<input type="text" name="fAddress" id="address">
<input type="text" name="fComment" id="comment">
<button onclick="sendData();" type="button">Submit</button>
</form>
<div id="testdiv"></div>
<script>
function sendData(){
var data = new FormData();
data.append('fName', document.getElementById("name").value);
data.append('fAddress', document.getElementById("address").value);
data.append('fComment', document.getElementById("comment").value);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test.php', true);
xhr.onload = function () {
if(xhr.status !== 200){
// Server does not return HTTP 200 (OK) response.
// Whatever you wanted to do when server responded with another code than 200 (OK)
return; // return is important because the code below is NOT executed if the response is other than HTTP 200 (OK)
}
// Whatever you wanted to do when server responded with HTTP 200 (OK)
// I've added a DIV with id of testdiv to show the result there
document.getElementById("testdiv").innerHTML = this.responseText;
};
xhr.send(data);
}
</script>
</body>
The PHP code :
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
var_dump($_POST);
}else{
header('HTTP/1.0 403 Forbidden');
}
?>
To add another field, add another data.append function below data var.
The submit button MUST BE CLICKED. To allow the use of enter, add an event listener for it!.
What it looks like on my end : https://image.ibb.co/gfSHZK/image.png
Hope this is the answer you wanted.
Two issues:
1.) Params not sent properly/at all because lack of serialization. When you use form content-type your params object need to be in a particular format name=value&name2=value2. So to facilitate that you need to transform your ojbect using something like:
function getReadyToSend(object) {
var objList = [];
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
objList.push(encodeURI(prop + '=' + object[prop]));
}
}
return objList.join("&");
}
So your sending becomes: xhr.send(getReadyToSend(params));
2) Your php is expecting the submit button to be sent. if (isset($_POST['nameSubmit'])) {
You don't have a variable being sent called nameSubmit you can fix this by either including it or check that each variable is set instead. I would suggest the latter that way you can error handle should 1 or more are not passed.
Suggestion: Update your onload to check status:
if (xhr.status === 200)
{
console.log(xhr.responseText);
}
else if(xhr.status !== 200)
{
console.log('Request failed. Returned status of ', xhr.status);
}
Example fiddle: http://jsfiddle.net/qofrhemp/1/, open network tab and inspect the call you will now see the params in form data for the call that fires when submit clicked.
In my HTML I have an article containing clickable lists. I also have a form that adds data to my database. Once it's done adding the data I want my PHP to send a new list based off the data given in the form to the article in my HTML with my other lists.
How can I do this? I know how to display data from PHP in HTML but I don't know how to display that data in existing articles in HTML.
My function that updates and refreshes my page after every click on a link is called MyFnc and this is the JavaScript for it:
function myFnc(x) {
if (x == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else { //if a link is clicked
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
//readyState = 4: request finished and response is ready
//status = 200: "OK"
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "get_data.php?q=" + x, true);
xmlhttp.send();
}
}
And get_data.php is where I display the data from the database to the webpage. I know that displaying the link must be done in get_data since that is where I display everything to the page. But for now I just want to know how to send the data retrieved from add_records and make a list out of it.
This is my article in my HTML:
<article>
<ul class="lists" style="list-style-type:none">
<li>Tiger</li>
<li>Hammerhead</li>
<li>Bull</li>
<li>Great White</li>
<li>Mako</li>
<li>Greenland</li>
<li>Whale</li>
<li>Thresher</li>
<li>Oceanic WhiteTip</li>
<li>Goblin</li>
</ul>
</article>
Here is my form in my HTML:
<form method="post" action="add_to_records.php">
<input type="hidden" name="addshark" value="true" />
<fieldset>
<label>Name:<input type="text" name="Name" /></label>
<label>SpeciesID:<input type="text" name="speciesID" /></label>
<label>Genus:<input type="text" name="genss" /></label>
<label>Family:<input type="text" name="famly" /></label>
<label>Order:<input type="text" name="ordr" /></label>
<label>Class:<input type="text" name="clss" /></label>
<label>Create New Shark</label>
<input type="submit" value="add shark" />
</fieldset>
<br />
</form>
Here is my add_to_records.php:
<?php
include 'connect.php';
if (isset($_POST['addshark']))
{
include 'connect.php';
$Namee = mysqli_real_escape_string($connect,trim($_POST['Name']));
$specID = mysqli_real_escape_string($connect,trim($_POST['speciesID']));
$gens = mysqli_real_escape_string($connect,trim($_POST['genss']));
$fam = mysqli_real_escape_string($connect,trim($_POST['famly']));
$ord = mysqli_real_escape_string($connect,trim($_POST['ordr']));
$cls = mysqli_real_escape_string($connect,trim($_POST['clss']));
if (!mysqli_query($connect, "INSERT INTO Species
(SpeciesID,Genus,Family,Order_,Class)
VALUES ('$specID','$gens','$fam','$ord','$cls')"))
{
die('error inserting new record');
}
//I would like the list it returns to look like this if the Name entered was Hello
//and the speciesID entered was Something
//<li>Hello</li>
//echo "shark was added";
header('Location: ProjectMainAdmin.html'); exit;
}
mysqli_close($connect);
?>
Just use jQuery's AJAX, it's a lot simpler and easier to implement. Data will be passed to server, then once completed you need to append the data into your list.
something like this:
$("form").submit( function(){
$.ajax({
url: "add_to_records.php",
success: function(result){
$(".lists").append("<li><a href=''>" + result.name + "</li>");
}
});
return false;
});
I am relatively new to PHP and I am (trying to) developing my first AJAX code...
I am trying to pass an attribute from a select with several options, each option with its very own unique attribute "values" that is a String.
The PHP file GETs the value and does something with it (for instance prints it out). And the generated file is then returned to my main HTML page.
Here is the source code...
Here is my javaScript:
function showUser(myElement) {
var str = myElement.options[myElement.selectedIndex].getAttribute("values");
if (str == "") {
document.getElementById("myResponse").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myResponse").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
}
My HTML is as following:
<form>
<select name="users" onchange="showUser(this)">
<option values="">Select a person:</option>
<option values="Rasmus Lerdorf">Creator of PHP</option>
<option values="Linus Torvalds">Developed Linux</option>
<option values="Dennis Ritchie">Developper of C</option>
</select>
</form>
<br>
<div id="myResponse"><b>Person info will be listed here...</b></div>
My PHP is:
<?php
$q = intval($_GET['q']);
echo $q;
?>
I get 0 instead of the text string, what is wrong with my code?
Silly me,
I copied and pasted a basic example from a tutorial and I did not realize that the PHP code was casting the string that was sent over the GET to an integer.
$q = intval($_GET['q']);
The code should be :
$q = $_GET['q'];
On my earlier stage of the development I was indeed passing an integer, so the code was working.
The code returned 0 instead of an error because the intval of a string is 0 on failure.
Writing down the question here I realized the mistake...
Below is my textbox code
<input id="society_name" onBlur="showsociety(this.value)" />
<input id="societyid" name="society" />
Below is my javascript which call addressdata.php page...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showsociety(str)
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();}
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("societyid").value = data[i].societyid;
}
}
}
xmlhttp.open("GET","addressdata.php?q="+str,true);
xmlhttp.send();
}
</script>
Addressdata.php page
<?php
require_once('includes/config.php');
$q = $_GET['q'];
$city = $database->getRows("SELECT SM.id AS societyid,SM.society from societymaster SM WHERE SM.society = :society", array(':society'=>"$q"));
$info = array();
foreach($city as $row)
{
$cID = $row['societyid'];
$info[] = array('societyid' => $cID);
}
echo json_encode($info);
?>
I need to fetch id in multiple textbox like above given ex...in my form.
So is this possible to convert all php code to function in addressdata.php and call this function only from javascript...
FOR EX - i need to make whole php code of addressdata.php file as it is in function and call tis with below javascript on textbox blur event..
If I understood you correctly you want to add more text input elements into your page and be able to use this whole process of showing society on each of this elements.
The problem is not converting php code into a function (which would bring nothing).
What you want is to be able to tell showsociety() function which input element should it work on.
In the easiest case you can add additional parameter to the fucntion:
showsociety(str, id) {...}
And use this ID to search for correct element on the page.
[...]
document.getElementById(id).value = data[i].societyid;
[...]
.
<input id="society_name" onBlur="showsociety(this.value, this.id)" />
It can be done better but I think with such simple solution you should not have much problems.
Hope it helped.