Post form data to php without page refresh - javascript

I am trying to post form data, an array to php file without page refresh. I am using ajax which doesn't seem to be working. Below is form syntax and ajax. Can somebody please help me? Thanks.
<form name="postcontent" id="postcontent">
function[]; //just for an example of data
<button type="button" id="submitform" onclick="posttophp" >Send</button>
<script>
function posttophp() {
var xhttp = new XMLHttpRequest();
xhttp1.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("submitform").innerHTML = this.responseText;
}
};
xhttp.open("POST", "options.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("
function_Options1[]=function[]")
}
</script>
In php, I store function_Options1[] in another variable and use further.

Two ideas to try:
Maybe the script should be placed before calling the function, but not sure about this.
Try onclick="posttophp();"

Related

How can I retrieve data from a external URL to show in my webpage?

As a learning exercise I'm trying to retrieve the track_artist_name from a url used by a radio sation to show the song being played.
This could be a case of "Same-Origin-Policy" but I dont have enough knowledge to tell.
Could someone please help me to workaround the conflict ? Also, I know "this.responseText" will show everything, I will try to filter it once I can retrieve the Data, but if you feel generous and want to trow me also that bone, I will be really grateful to you. Thank you : )
<html>
<body>
<div id="data">
</div>
<button type="button" onclick="loadXMLDoc()">Get Data</button>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "http://np.tritondigital.com/public/nowplaying?mountName=XERC_FM&numberToFetch=1", true);
xhttp.send();
}
</script>
</body>
</html>

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

Javascript xmlhttp send api requests from forms

I have a server running locally which has an in built rest api. To login through this api, we need to send username, password and organization as parameters to url localhost:8090/ehr/api/v1/login via POST method and server returns an auth token as response. when I try to do this directly without user input from form through the following code:
<html>
<body>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=admin&password=admin&organization=123456");
</script>
</body>
</html>
It works perfectly fine and auth token is returned as json, but if I try to do the same through user form input via following code:
<html>
<body>
<form method="POST">
<input type="text" name="username" id="username" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<input type="text" name="organization" id="organization" placeholder="Organization">
<button id="submit" onclick="login()">Let me in!</button>
<br><br>
</form>
<script type="text/javascript">
function login() {
var user=document.getElementById("username").value;
var pass = document.getElementById("password").value;
var org = document.getElementById("organization").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param = "username="+user+"&password="+pass+"&organization="+org;
xhttp.send(param);
}
</script>
</body>
</html>
this code throws error
login.html:26 XHR failed loading: POST "http://localhost:8090/ehr/api/v1/login"
What is wrong with the second code and how to correct it?
send your params in this way
xhttp.send('username=user&password=pass&organization=org');
I figured it out myself, I just removed form tag from html and used simple input tags instead. This solved the problem maybe because forms on submission try to load a new page instead of staying on the same page, but the parameters were intended to get fetched from the original page. Which was not able to happen as new page got loaded every time submit button was clicked.

Ajax xmlhttprequest with POST to php file

Hello guys I am kina new in ajax and I have an issue, I want to call a php file to do some db queries from the javascript file. JS code
$(document).ready(function(){
$(".delete").click(function(){
var xhttp;
if(window.XMLHttpRequest)
xhttp = new XMLHttpRequest();
else
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
xhttp.onreadystatechange = function() {
if(xhttp.readyState==4 && xhttp.status==200){
$(".delete").css("color", "pink");
}
};
xhttp.open("POST","../admin-tasks/admin-delete-appointment.php",true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("date="+date+ "&hour="+time);
});
});
And php file.
<?php
session_start();
require_once("../connection.php");
if($_SESSION["password"]!=null)
{
if(!empty($_POST["date"]) && !empty($_POST["hour"])){
$_SESSION["msg"]= "<script type='text/javascript'> alert('The appointment has been removed!');</script>";
$date=$_POST["date"];
$hour=$_POST["hour"];
...
I would like to point that the request is going properly, the php file is running if I sent data through html form with post,the problem is when I try it through the js file. The status is 200 and the readyState is going to 4 eventually. Is this below right when I call it from js??
$_POST["date"]
$_POST["hour"]
Did you try to add some brackets ?
if(xhttp.readyState==4 && xhttp.status==200) {
$(".delete").css("color", "pink");
xhttp.open("POST","../admin-tasks/admin-delete-appointment.php",true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("date="+date+ "&hour="+time);
}
The code is completely right, I found the mistake on method date. If I give date("Y-m-d", strtotime($date)) and the var $date instead of - has / or w/e it wont change the date to the format you expect.

Submitting a form using AJAX

I've a JSP page which includes a checkbox, so when i try to submit the form using the conventional javascript way of document.forms[0].submit(); the form gets refreshed and the checkbox values are not getting retained.
Can anybody help me on how to send the form value using only AJAX. I don't need the way to send using JQuery.
This is the code I had used for sending using form submit:
function relatedAER(){
......
document.forms[0].literatureSelected.value = litNO + "&";
document.forms[0].opCode.value = "relatedAER";
document.forms[0].target='_self';
document.forms[0].action="<%=request.getContextPath()%>/litaer.do?selected="+selected;
document.forms[0].submit();
}
I hope next time, you'll put some effort, into creating even a simple code, and showing us instead of asking for a script.
Now, that bieng said: This will submit a username to a php file, called fetch.php
HTML
<input type='text' name='user' id='user' /><br/>
<input type='submit' name='submit' onclick='check()' />
<div id='output'></div>
Ajax:
function check(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('output').innerHTML = xmlhttp.responseText;
}
}
get_user = document.getElementById('user').value;
param = "name="+get_user;
xmlhttp.open('POST','fetch.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
</script>

Categories

Resources