I'm trying to create a form on my website where a user has a text field that they can use to enter a registration number. I want the registration number to be added to the end of the action URL so when that page loads I can use PHP to explode the URL and grab the number. Here's an example of what I'm looking for...
<form action="http://mywebsite.com/registrations/123456789">
<input type="text" name="registrationnumber">
<input type="Submit" value="Submit">
</form>
Is it possible to take whatever is entered into the text field called registrationnumber and have it passed to the URL the form directs to? Maybe an easier way is to create a text field that has a button, when the button is clicked the URL is links to is dynamically created by adding the registrationnumber to the end.
Anyone know of a way to do this?
Indeed you don't need a form to make an AJAX call. A simple input and button will suffice.
I have made a function that will make AJAX call, it will convert the object params containing all key/value pairs of the parameters you want to send to PHP, and concatenates it into a URL string:
function ajax(file, params, callback) {
var url = file + '?';
// loop through object and assemble the url
var notFirst = false;
for (var key in params) {
if (params.hasOwnProperty(key)) {
url += (notFirst ? '&' : '') + key + "=" + params[key];
}
notFirst = true;
}
// create a AJAX call with url as parameter
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
Assuming you have an input field:
<input id="code" type="text">
<button id="sendData">Send</button>
Here's how we can use the function ajax:
function sendData() {
parameters = {
inputValue: document.querySelector('#code').value
};
ajax('target.php', parameters, function(response) {
// add here the code to be executed when data comes back to client side
// e.g. console.log(response) will show the AJAX response in the console
});
}
You can then attach the button to sendData using an event listener:
document.querySelector('#sendData').addEventListener('click', sendData)
Related
i have problem figuring out a solution . i am developing a chatbot .
this is my html where i print all the discussion , its just one :
<div id="divChat"> </div>
i want to add typing indicator to it .here is how it works on each message:
1)User types his message (exemple : Hello), and click on a button
<button onclick="sendMessage()" id="btn1" > Send </button>
2) i read his message and i sent it to mybackend application to receive the response and print it in the chat element.
function sendMessage(){
var url = "http://localhost:3000/api/v1/bots/renault/converse/user1";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var reponseBot= JSON.parse(xhr.responseText);
if(reponseBot!='undefined'){
$("#divChat").append(reponseBot+"</br>");
}
}
}
};
var values = {
type: "text"
}
values.text=$("#userMessage").val();
var data= JSON.stringify(values);
xhr.send(data);
}
the chat works fine , now i want to add typing indicator which is this element (u dont need see css of it):
<div class="typing-indicator"></div>
i want When the user send his message i Append the typing indicator to the chat , show it for 2sec then hide it and append then response bot : like this
if (xhr.readyState === 4 && xhr.status === 200) {
var reponseBot= JSON.parse(xhr.responseText);
if(reponseBot!='undefined'){
$("#divChat").append("<div class='typing-indicator' ></div>");
/// I WANT TO HIDE IT AFTER 2SEC THEN APPEND THE USER RESPONSE
$("#divChat").append(reponseBot+"</br>");
}
}
Please any idea how to achieve this and thanks
You can use setTimeout to delay an action.
Also note that if you've already included jQuery in the page you may as well use its AJAX methods to simplify the code. Try this:
let $divChat = $('#divChat');
function sendMessage() {
$.post('http://localhost:3000/api/v1/bots/renault/converse/user1', {
type: 'text',
text: $('#userMessage').val()
}, function(response) {
$('#userMessage').val(''); // empty the typed message
let $indicator = $('<div class="typing-indicator"></div>').appendTo($divChat);
setTimeout(() => {
$indicator.remove();
$divChat.append(response + "</br>");
}, 2000);
});
};
Also note that from the response to your AJAX request it looks like you're returning a plain text response which is not ideal, as it can be affected by whitespace. I'd suggest you amend your server side logic to return a serialised format, such as JSON or XML.
I have a array student. I need to pass this array in another php page via POST, not from GET, because it can contains thousands of characters.
I am trying to open new page sheet.php and echo the array student, I do simply checking echo $_POST['mnu'], but it is showing undefined index error.
var http = null;
if(window.XMLHttpRequest){
http = new XMLHttpRequest();
}
else{
http = new ActiveXObject('Microsoft.XMLHTTP');
}
http.open('POST','sheet.php',true);
http.setRequestHeader('Content-type','application/x-www-form-urlencoded');
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==200){
window.open('sheet.php','_blank')
}
}
http.send('mnu='+JSON.stringify(student));
Like #RamRaider commented.. you're making two requests to sheet.php. The first being a "silent" POST request and the second being a GET request after the first POST request has successfully completed.
The second request won't share the payload of the first.
If I under stand correctly the below code should do what you are wanting...
// Create a form element
// <form action="sheet.php" method="post"></form>
var tempForm = document.createElement('form');
tempForm.setAttribute('action', 'sheet.php');
tempForm.setAttribute('method', 'POST');
tempForm.setAttribute('target', '_blank'); // Open in new tab
// Create an input field
// <input name="mnu" value="...">
var tempInput = document.createElement('input');
tempInput.setAttribute('name', 'mnu');
tempInput.setAttribute('value', JSON.stringify(student)); // Set field value
// Add the input to the form
tempForm.appendChild(tempInput);
// Add the form to the body in order to post
document.body.appendChild(tempForm);
// Submit the form
tempForm.submit();
// Remove the form
document.body.removeChild(tempForm);
And if you're using jQuery you can simplify the above code..
$('<form>', {
action: 'sheet.php',
method: 'POST',
target: '_blank',
html: $('<input>', {
name: 'mnu',
value: JSON.stringify(student)
}).prop('outerHTML')
}).appendTo($('body')).submit().remove();
Change http.send('mnu='+JSON.stringify(student)); to http.send(JSON.stringify(student));
And then in your sheet.php use json_decode($_POST) to fetch your POST data
want to create a fully dynamic chat UI for my website, But it reloads the whole page if a person submits the button page should not reload like many chat website.
<form action="action.php" method="post" id="formpost">
<input type="text" id="input" value="php echo">
<input type="submit" value="send">
</form>
I want to submit this form through ajax and show the last xml <message> containing <message>talk 123<message>
<messages category="short">
<person1>
<time>
r
<message>Djssjs</message>
</time>
</person1>
<person2>
<time>
r
<message>1234fdg</message>
</time>
</person2>
<person1>
<time>
r
<message> talk 123</message>
</time>
</person1>
</messages>
i want to show that talk 123 in the html document bit confused how to do that
//for form submit
$("#formpost").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: action.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
//for xml
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "name.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var msg = "";
//how to select the last person's of the <messages> child
msg = getElementsByTagName("messages").lastChild.childNodes[1].nodeValue ;
document.getElementById("demo").innerHTML = msg;
}
$("#formpost").on('submit', function(event){
event.preventDefault();
// rest of your ajax code here...
});
Points to note
1. Make sure you have also added JQuery script source on the head tag of your chat page.
2. Make sure to put preventDefault() immediately before any other code is executed.
You can use reverse ajax method pulling data from the server.
In reverse ajax a request is auto-generated at a certain time interval or hold the request for fetching new message.
There are three technologies for reverse ajax:-
Piggyback
Polling
Comet
I currently have a servlet setup to send over a list of our active servers. The method grabs the servlet data, processes it, then injects the html into the datalist tag. HTML injection process works, but when I'm splitting the array by the concat separator (which I've done before), I get no values. Below I'll explain with code examples:
HTML:
<label for="server_id_text">Server ID: </label>
<input id="server_id_text" list="server_names" name="server_id" required>
<datalist id="server_names">
<!--This gets injected with the active servers grabbed through a get request-->
</datalist>
Javascript connecting to server to get data:
Note: serverList is a global variable.
var serverList = "";
function setupAutoComplete() {
$.get(baseURL + "/SupportPortal", function (data, status) {
console.debug("Status with auto comp id: " + status);
serverList = data;
console.debug("server list auto comp at post mailing: " + serverList);
});
}
This method is called in the function that is called when the onload event is called in the body tag
Here are the two methods that inject the html:
function setupServerName() {
document.getElementById("server_names").innerHTML = getServerListHTML();
}
function getServerListHTML(){
console.debug("Autocomplete process running...");
var servArr = String(serverList).split('*');
var html = '';
var temp = '<option value="{serverName}">';
console.debug("Array:" + servArr.toString());
if (serverList == 'undefined' || servArr.length == 0){
console.debug("serverList is empty...");
return '';
}
for (var i =0; i < servArr.length; ++i){
html += temp.replace("{serverName}", servArr[i]);
}
console.debug("html: " + html);
console.debug("ServList size " + servArr.length);
return html;
}
When the page loads, setupAutoCompelte() is called first. Then, setupServerName() is called.
My issue is that after I load the page, I get the correct response from the server. For instance, I'll get server1*server2 as a response to the jQuery $.get(...) call. Then I go to split the string into an array, and I get back an empty html tag (<option value="">);
Also, the debug console info are as follows:
Autocomplete process running...
Array:
html: <option value="">
ServList size 1
Status with auto comp id: success
server list auto comp at post mailing: server1*server2
Thanks for the help!
I believe that your setupServerName() function is being called before the AJAX request in setupAutoComplete() returns, so your serverList is an empty string at that point. What you need to do is populate your <datalist> from inside your AJAX callback in setupAutoComplete().
// setup autocomplete datalist
function setupAutoComplete() {
var $datalist = $('#server_names');
$.get(baseURL + '/SupportPortal').then(function (data) {
// update datalist
if (!data || !data.length) {
// no servers, empty list
$datalist.html('');
} else {
// create options html:
// reduce array of server names
// to HTML string, and set as
// innerHTML of the dataset
$datalist.html(data.split('*').reduce(function (html, server) {
return html + '<option value="' + server + '">\n';
},''));
}
});
}
// on page load, setup autocomplete
$(function () {
setupAutoComplete();
});
As you can see from "debug console info":
the get function is asyncrhonous so you need to change your setupAutoComplete get part to:
$.get(baseURL + "/SupportPortal", function (data, status) {
console.debug("Status with auto comp id: " + status);
serverList = data;
setupServerName();
console.debug("server list auto comp at post mailing: " + serverList);
});
On page load try to call directly the setupServerName function within the success event of get function. A different approach is to divide the setupServerName function so that the part related to the serverList variable becomes part of another function.
The serverList variable is global but its content is filled after the setupServerName is executed.
I'm working on an application that should be sending a post request to an internal page that does a certain calculation
When pressing a button, the page(dashboard.php) prints the content of the other page(calculate_salary.php)
here's my js code so far:
<script language="JavaScript" type="text/javascript">
function getXmlHttpRequestObject() {
return new XMLHttpRequest();
}
var receiveReq = getXmlHttpRequestObject();
function sayHello() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
var start_date = $("#start_date").val();
var end_date = $("#end_date").val();
receiveReq.open("GET", 'calculate_salary.php', true);
receiveReq.onreadystatechange = handleSayHello;
receiveReq.send(null);
}
}
function handleSayHello() {
if (receiveReq.readyState == 4) {
document.getElementById('span_result').innerHTML = receiveReq.responseText;
}
}
</script>
I want to send over the values in start_date and end_date to the calculate_salary.php page
I will use that calculate page to perform some sql statements and return the result back.
How can I create this request?
POST is not an absolute necessity, I'm willing to use other techniques (js, php) to get the job done
thanks
You can use ajax instead
$.ajax({
url:"calculate_salary.php",
type:"POST",
data:{
start_date = $("#start_date").val(),
end_date = $("#end_date").val()
},
success:function(response){
$('#span_result').html(response);
}
});
You can read more about $.ajax and $.post
You have to generate querystring with url like so:
var url = 'calculate_salary.php?start_date='+start_date+'&end_date='+end_date;
receiveReq.open("POST", url, true);
Because you are not sending values that is why you are not receiving values on server side.
Another example you can find here:
How do I pass along variables with XMLHTTPRequest
Also check into this:
http://devzone.co.in/jquery-serialize-function-ajax-post-bigger-html-forms/