Webpage reloading on entering correct values - javascript

I've ran into an weird problem. I have created a login page which send data to a PHP page which return some response code like "00000" for ok "404" for not found etc. I have tested my server with Postman tool and found server is working perfectly fine. When my html send data to server server responds with response code. If the response code comes wrong html alert's it. However if I enter correct credentials and when server respond with success , My login page reloads for no reason.
Here's my javascript
function validatelog(){
var user_email_log=document.getElementById("user_email_log").value;
var user_pass_log=document.getElementById("user_pass_log").value;
if (user_email_log&&user_pass_log!=null)
{
var hr = new XMLHttpRequest();
var url = "../logic/login.php";
var vars =
"user_email_log="+user_email_log+"&user_pass_log="+user_pass_log;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var saman = hr.responseText.trim();
if(saman=="00000"){
alert(saman);
}else if (saman == "404"){
alert("Failed with 404");
}
else{
alert(saman);
}
}
}
hr.send(vars);
}
}
And my html looks like this
<input id="user_email_log"/>
<input id="user_pass_log"/>
<button onclick="validatelog();">Log in</button>

Add type="button" to the button:
<button type="button" onclick="validatelog();">Log in</button>
When it is not specified, it is the same as type="submit", and this will cause your page to reload.

if you use jquery you could do this.
$(document).on('click', 'button', function(e) {
e.preventDefault();
$.get('url')
})
I think the page is reloading because that is the default behavior.

Related

Why is my ajax request repeating same data from Laravel controller?

Goal: load more rows from the database to a view using an ajax request when a user clicks the "load more" button. I would like the data to load without a page reload.
Problem: The data being loaded via ajax keeps repeating the same rows on every request and doesn't paginate as per standard request.
Detail: I have a view that loads 4 rows from the database which I paginate using Laravel's built-in pagination. I've added an event listener on a "load more" button which successfully sends the request to the controller, which in turn successfully returns data. The controller returns a partial view of the data I want to display. However this data doesn't seem to increment properly and keeps repeating the records shown on each request. I am not sure what I am missing here, if the problem is in the controller or in the JS?
I am not very experienced with Laravel, PHP and JS since coming from more of a web designer and UI design background and would love to really understand what I am doing wrong here.
PLEASE NO JQUERY EXAMPLES.
Partial view:
#foreach ($products as $product)
<div style="background-color:pink; width: 200px;">
<p>{{ $product->title }}</p>
<img src="/images/product/{{ $product->img }}" alt="{{ $product->title }}" style="width: 50px;">
</div>
#endforeach
Javascript:
(I am updating the button href attribute so the request URL reflects the correct query)
const container = document.querySelector('#sandbox-container');
let button = document.getElementById('load-stuff');
let url = button.getAttribute('href'); // http://127.0.0.1:8000/sandbox?page=2
let pageNum = button.getAttribute('href').substr(35,1);
button.addEventListener('click', (event) => {
event.preventDefault();
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
// if page loads successfully, replace the number at the end of the url with the incremented page number
pageNum++;
newUrl = url.replace(/page=([^d]*)/, `page=${pageNum}`);
button.setAttribute('href', newUrl);
xhr.onload = function() {
if (xhr.status === 200) {
container.insertAdjacentHTML('beforeend', xhr.responseText);
}
else {
console.log(`Request failed, this is the response: ${xhr.responseText}`);
}
};
xhr.send();
})
Controller:
public function sandbox(Request $request)
{
$products = Product::orderBy('title', 'asc')->paginate(4);
if($request->expectsJson()){
return view('sandbox-more', compact('products'));
} else {
return view('sandbox', compact('products'));
}
}
Consider this snippet for your javascript
const container = document.querySelector('#sandbox-container');
let button = document.getElementById('load-stuff');
button.addEventListener('click', (event) => {
event.preventDefault();
const xhr = new XMLHttpRequest();
let url = button.getAttribute('href');
let pageNum = button.getAttribute('data-page-number') || 0;
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
// if page loads successfully, replace the number at the end of the url with the incremented page number
pageNum++;
newUrl = url + '?page=' + pageNum;
xhr.onload = function() {
if (xhr.status === 200) {
container.insertAdjacentHTML('beforeend', xhr.responseText);
button.setAttribute('data-page-number', pageNum);
}
else {
console.log(`Request failed, this is the response: ${xhr.responseText}`);
}
};
xhr.send();
})
What I've done here is to have the page number saved to a dedicated custom attribute "data-page-number". Doing "button.getAttribute('href').substr(35,1)" is inefficient. And then check the page number and increment it on the button's click event. Also, only update the "data-page-number" attribute when the request has been successful. I hope this helps
You should regenerate the pagination every time you make a request to get the correct data. Here is a very good example on doing it via jQuery. Should just adjust it to your needs since you are using pure Javascript.

PHP is shown on wrong page

I'm recently working on a website project. Therefor I have a website.php with all html code, a function.php and saveArray.js . In website.php I'm printing a html table with a button at the bottom. Through the button click I'm getting to the saveArray.js, where I save all the table data in an array.
With this code
var arrString = JSON.stringify(tableData);
var request = new XMLHttpRequest();
request.open('post', 'function.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-
urlencoded');
request.send('daten=' + arrString);
I post the JS array to function.php. In function.php I do something with the array and in an if statement I want to show a modal.
The modal itself works, but I want to show it on website.php page. Which doesn't happends, because I'm currently on function.php .
How can I solve this ?
EDIT: In my array is an ID and I want to check if this ID is already in my database or not. Depending on this result I want to show the modal and upload the data if necessary. All the checking is happening in function.php
I suppose you want to inject the string returned (the modal PHP code) by your function in function.php in your current page ('website.php').
To do this, you'll have to inject the response given by the XMLHttpRequest when the request is finished.
Let's suppose we want to add all the contents within
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
See, You are not handling the response of the request.So handle the response.and restuern the status of the request from function.php and if data is saved the open the model. You need not go to the function.php page. See the code
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this is response of the request //now check it
//Suppose you returned " data saved" as response from function.php
if(this.responseText='data saved'){
//Open model here
}
}
};
xhttp.open("POST", "function.php", true);
xhttp.send();

function works but don't alert and reload

I wrote a small form to log-in into my website :
<form id="log_form" onsubmit='return loginjs()' method="post">
<input type='text' placeholder="login" size='30' name='login' class='test'/>
<input type='password' placeholder="password" name='password' size='30'/>
<input type='submit' value='Connect' id='signin' />
</form>
and I wrote this Javascript function to send the form's data to a php page which going to check if everything is ok and make the session up.
function loginjs() {
'use strict';
var form = document.getElementById('log_form');
var btn = document.getElementById('signin');
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === XMLHttpRequest.DONE) {
if(request.status === 200) {
if (request.responseText != 'ok')
alert(request.responseText);
}
}
}
var post = "login=" + form.login.value + "&password=" + form.password.value;
request.open('POST', 'functions/func_login.php');
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(post);
location.reload();
};
My function is perfectly called each time I press ENTER or click on Submit, but sometimes the alert doesn't show up and the location.reload(); aren't called.
I don't have any error in my console... and if I manually reload the page, i'm logged so my ajax was sent.
I'm looking for 2 days to find the bug, and doesn't succeed to find. Could someone help me?
I can't use jQuery or another library I've to use JS Vanilla :)
Thank you
Try moving the location.reload(); code in the success block of the ajax, i.e. reload the page after the ajax response is received (if no error is received).

ReferenceError Cannot find variable createXMLHTTPRequestObject

I have a simple input box with a submit button which, when clicked, makes an XHR request to a server-side PHP for some information. In its simplest form, the markup looks like this:
<input type="text" id="word" class="form-control input-lg lookup-field" placeholder="Enter a Spanish or English word" oninput="deleteicon();" required>
<button class="btn btn-lg btn-brown lookup-submit" type="submit" id="lookup">Lookup</button>
The button's onclick event triggers a function that performs the XHR request:
$('#lookup').click(function(){ testlookup($('#word').val()); return(false); });
The testlookup() function is as below:
function testlookup(lookupword){
var mean = document.getElementById('meaning');
var waittext = '<div id="loading text-center"><i class="fa fa-4x fa-spinner fa-spin"></i></div>';
var hr = createXMLHTTPRequestObject();
var url = '/assets/engines/dictengine.php';
var vars = "lookup_word=" + lookupword;
document.getElementById('word').value = lookupword;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
mean.innerHTML = return_data;
else if(hr.status == 500){ mean.innerHTML = "Something went wrong! Please try again later..."; }
}
hr.send(vars);
mean.innerHTML = waittext;
}
I fail to see why this should ever refuse to work and would really appreciate some help seeing the issue. Every time I enter a value in the input box and click the button, the console briefly flashes a "Can't find variable createXMLHTTPRequestObject" error before the browser proceeds to refresh the page with a "?" appended to the URL. What could be the issue here and also why is the "?" getting appended to the URL if I have duly terminated my onclick function with a return(false) statement?
The code is implemented at peppyburro.com/test-dictionary.
You are trying to call a function named createXMLHTTPRequestObject, but it doesn't exist. The JS throws an exception and never reaches the return (false) statement.

Javascript code for handling Form behaviour

Here's how the situation looks :
I have a couple simple forms
<form action='settings.php' method='post'>
<input type='hidden' name='setting' value='value1'>
<input type='submit' value='Value1'>
</form>
Other small forms close to it have value2, value3, ... for the specific setting1, etc.
Now, I have all these forms placed on the settings.php subpage, but I'd also like to have copies of one or two of them on the index.php subpage (for ease of access, as they are in certain situations rather frequently used).
Thing is I do not want those forms based on the index.php to redirect me in any way to settings.php, just post the hidden value to alter settings and that's all.
How can I do this with JS ?
Cheers
Yes, you could use an ajax call to send a request to the settings.php file. You'd probably want that PHP code to return something that the JavaScript can use to know if the request was successful or not (for example, using JSON instead of HTML).
Here is an ajax getData function.
function getData(dataSource, targetDiv){
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject) {
var obj = document.getElementById(targetDiv);
XMLHttpRequestObject.open("GET", "settings.php?form="+dataSource+"&t="+new Date().getTime());
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
use this function to send the form to your setting.php file which should return confirmation message to index.php(inside targetDiv).
Parameters of the function
1) dataSource - is the variable value that you send to settings.php
2) targetDiv - is the div on index php that with display the response from settings.php
Hope it makes sense.

Categories