XMLHttpRequest response status based on posted value - javascript

I have my JavaScript function which does XMLHttpRequest. Here is my code.
function addbilldetails() {
// Cancel the form submit
event.preventDefault();
// The URL to POST our data to
var postUrl = 'http://example.com/post.php';
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed
var clientId = "clientid",
submittype = "a",
name = encodeURIComponent(document.getElementById('name').value),
billno = encodeURIComponent(document.getElementById('billno').value),
mobileno = encodeURIComponent(document.getElementById('mobileno').value),
phoneno = encodeURIComponent(document.getElementById('phoneno').value),
netAmount = encodeURIComponent(document.getElementById('netAmount').value);
var params = 'clientId=' + clientId +
'&billno=' + billno +
'&mobileno=' + mobileno +
'&phoneno=' + phoneno +
'&netAmount=' + netAmount +
'&type=' + submittype +
'&name=' + name;
// Replace any instances of the URLEncoded space char with +
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Saved!';
document.getElementById('save').disabled = false;
// window.setTimeout(window.close, 1000);
} else {
// Show what went wrong
statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
}
}
};
// Send the request and set status
xhr.send(params);
statusDisplay.innerHTML = 'Saving...';
document.getElementById('save').disabled = true;
}
Now, the above code works perfectly and returns 200 on POST. But I want it to return custom message on the UI based on the value posted.
If the value POSTed is less than the value in the database, I want it to give "Enter Valid number" or something like this.
I am quiet new to XMLHttpRequest . I do not know how to achieve that. Any help would be highly appreciated.

Instead of statusDisplay.innerHTML = 'Saved!'; have you considered:
statusDisplay.innerHTML = xhr.responseText;
If you do this, then your statusDisplay will be equal to whatever your post.php echos out.
For example, in post.php
<?php
//handling $_POST['clientId'] ... etc
if (error)
echo "Enter Valid Number";
else
echo "Saved!";

Related

How to bind parameter to URL

This is my jsp code. I want to bind the catid parameter to url when I call getproductsub() and send ajax request.
r.open("GET", "url?catid=" + catid,true);
above line seems an error of my code.How can I fix it.
<select class="form-control" id="pcategory" name="pcategory" onchange="getproductsub();">
<script>
function getproductsub() {
var catid = document.getElementById('pcategory').value;
var url = window.location.href;
var r = new XMLHttpRequest();
r.onreadystatechange = function() {
if (r.readyState === 4 && r.status === 200) {}
};
r.open("GET", "url?catid=" + catid, true);
r.send();
}
</script>
Note that window.location.href gives the complete location including the parameters in the url at the current time. So ? might be included in it.
You can either use
var url = window.document.location.pathname;
And concat the url to the String passed to open().
r.open("GET", url + "?catid=" + catid, true);
OR
Use getRequestURL() as you are coding in jsp.
r.open("GET", "<%= request.getRequestURL()%>?catid=" + catid, true);

pass two different variables in javascript?

this is my javascript of first page
<script>
function MessageDetailsById(id)
{
$("#active"+id).css({"color":"red"});
var http = new XMLHttpRequest();
var url = "Ajax.php";
var adm = "<?php echo $admno; ?>";
var params = "Id="+id;"adm="+adm;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//alert(http.responseText);
}
}
http.send(params);
window.location.href="#";
}
</script>
this is the coding of ajax.php
<?php
include("model.php");
$DB=new database;
if(isset($_POST["Id"]))
{
$DB->updateMassageTitleStauts($_POST["Id"],$_POST["adm"]);
}
else
{
header("Location:index.php?ajaxmas=wHgfghks^^%&fnjfskjdfb");
}
?>
i want to send one variable of php and another is id of a div... how to send two parameters and recieves them on other side ??? please correct this code in details i am not expert ???
For the post data encoding:
var params = "Id=" + id + "&adm=" + adm;
Use & for separator.

Lag for just part of AJAX response

I made a simple chat. It's working properly, but not behaving as expected. When a user submits a message, the user's name, time and message are supposed to display.
It so happens that the username and response appear first and the time seems to be inserting itself after a slight delay (that's the lag). I can't figure out why, especially since the response is (or at least seems to be) sent as a whole and nothing is being inserting once the response is sent from the server...
Here's the link to the chat. You can input dummy username and dummy messages.
And here are the important pieces of code:
PHP
while ($row = $result->fetch_assoc()) {
$time = date('g:ia', $row['time']);
echo "<p class=\"message\"><i>{$row['username']}</i> ($time): {$row['content']}</p>";
}
JavaScript
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
document.getElementById('messagesArea').innerHTML = ajax.responseText;
}
};
Your culprit is this section of the script:
var content = document.getElementById('messageBox').value;
if ( content === '') {
return;
} else {
var ajax = new XMLHttpRequest();
var username = document.getElementById('signedin').innerHTML;
document.getElementById('messageBox').value = '';
ajax.open('POST', 'postmessage.php', true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
// if there are errors echoed from the PHP file
if (ajax.responseText != "") {
document.getElementById('mysqliError').innerHTML = ajax.responseText;
return;
}
document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
}
};
ajax.send('username=' + username + '&content=' + content);
}
Notice this line: document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
You are inserting the message, without the time, into #messagesArea. Then, in getRecentMessages later, it is set to fetch the entire chat log from displaymessages.php and overwrite #messagesArea with the content of the output, which does have the time.

How to insert form into mysql without leaving the page (javascript+html)

I'm trying to insert a new user into mysql. I have tried to use jQuery, but it doesn't seem to be working. I tried to use pure javascript, but it's the same. It has no response after I click on the button. What's wrong?
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var shop = document.getElementById("shop");
var http = new XMLHttpRequest();
http.open("POST", "http://xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "ac=" + acR + "&pw1="+pw1 "&shop="+ shop;
http.send(params);
http.onload = function() {
alert(http.responseText);
};
}
There's a quite a few problems in your JS code, I've tidied it up here and run it locally to a page called xyz.php, so that'll get the AJAX call to work but you'll need to post your PHP code to get any help with your DB queries
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var http = new XMLHttpRequest();
// removed the http:// protocol, assuming you're going for a local AJAX call
http.open("POST", "xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// get values of the form fields, don't submit the full element
// also added the plus (+) character before the final pw1
var params = "ac=" + acR.value + "&pw1=" + pw1.value;
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I've attached a screen shot showing Chrome Dev Tools happily recording successful AJAX requests
Try to use a JQuery post.
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
$.post( "xyz.php", { ac: acR, pw1: pw1 })
.done(function( data ) {
alert( "Data inserted: " + data );
});
Backend handles this post and then implement the insert action for example in NodeJs(express)
app.post("/xyz", function(req, res, next) {
var obj = {};
obj[acR] = body.ac;
obj[pw1] = body.pw1;
mysql.insert(obj);
});

Trouble receiving Javascript variable when sent to PHP

Problem: Trouble receiving what is being sent to my PHP document.
Javascript:
$('#form_id').submit(function(event){
event.preventDefault();
event.stopPropagation();
var message;
var myRegExp = validation stuff
var urlToValidate = document.getElementById("url").value;
if (!myRegExp.test(urlToValidate)){
}else{
var code = (urlToValidate).slice(-22)
var request = new XMLHttpRequest();
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if (this.status ==200){
console.log (this.status);
}else{
console.log('Server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'php/submit.php', true);
request.setRequestHeader('Content-Type', 'text/plain');
request.send("code=" + code);
}
});
Then I'm using this code on my php/submit.php:
if (!empty($_POST['code'])) {
$code = $_POST['code'];
echo $code;
};
I feel like I'm not using the right tag names for PHP because I'm new to all of this. I'll note that I'm using form id but getting the value from an input.
Ramblings
I'm trying to send a user input that has been validated and sliced to mySQL database.
I achieved the string I wanted with javascript and passed it to a variable.
I'm trying to send it to a separate php file in another folder with a request.send(the_javaS_variable).
Now in the console I can see the variable holds the correct text value and I see it sending with state 4 and 200.
But it never shows up on the submit.php page.
try this and remove the console.log()
$('#form_id').submit(function(event){
var myRegExp = validation stuff
var urlToValidate = document.getElementById("url").value;
if (!myRegExp.test(urlToValidate)){
// failed
}else{
var code = 'code='+(urlToValidate).slice(-22);
$.post('php/submit.php', code, function() {
// success stuff
});
}
return false;
});

Categories