document.getElementById(..) gives null even though element is present - javascript

I have the following program in which a user can enter any name in a search box after which I redirect the user to a page called usernameSearchResults.php where I print a list of the usernames obtained in the form of an array from usernamesearch.php. Here is the javascript:
$(window).on('load', function() {
$(".searchBarForm").submit(function(e){
e.preventDefault();
var search=document.getElementsByClassName("search")[0].value;
$.ajax
({
type: 'POST',
url: 'usernamesearch.php',
data:
{
search:search
},
success: function (response)
{
window.location.href="usernameSearchResults.php";
response = JSON.parse(response);
var array_length = Object.keys(response).length;//getting array length
for(var i=0;i<array_length;i++){
if(i==0){
document.getElementById("searchResults").innerHTML=""+response[0].username+"<br>";//i=0
}else{
document.getElementById("searchResults").innerHTML+=""+response[i].username+"<br>";
}
}
window.stop();//stops page from refreshing any further(put here to fix a bug that was occuring)
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
})
});
This is usernameSearchResults.php(inside tags):
<h1>Username Search Results</h1>
<p id="searchResults"></p>
But the problem is that whenever I go to any other page say index.php and enter the username to be searched, the page redirected to is indeed usernameSearchResults.php but the page is blank and error in the console shown says document.getElementById("searchResults") is null.But if I stay at the page usernameSearchResults.php and refresh it and then search any name again, then the results are correctly obtained. What is the problem here?

I would say that the user is being redirected to usernameSearchResults.php but the JavaScript code is still being executed from the current page, which have no element with id "searchResults" defined.
As #Kashkain said, one way to achieve what you want is to pass your response variable in your redirection url and process it then into your other page.

I think the problem here is that the new document could very well still not have been loaded when you call getElementById.
You could add a listener on your target element which would trigger on the load event. In this event's handler you could execute the operations that are now giving you an error.
I have never done or tried this, but maybe something like this would work:
$('#searchResults').on('load', function() {
//execute code here
});
Or you could add a form to the page with action="target_url" method="post" and send your response data through post by doing form.submit, and place the problematic code into usernameSearchResults.php, which will need to read data from POST - this way you can send your ajax data to the new page

Related

POST works with alert message but doesn't without it

I am making a post request to google app script with the code below
var url ="MY WEBAPP EXEC"
function submitForm() {
var postRequest = {}
postRequest.name = $("#inputName").val();
postRequest.email = $("#inputEmail1").val();
postRequest.message = $("#inputMessage").val();
alert(JSON.stringify(postRequest)); // this alert
$.post(url, postRequest, function(data,status){
alert('success')
});
}
I am very confused why the post is working with the alert but doesn't work without it. Thank you.
===
OK I guess my question was not clear enough sorry.
I have a form accessing GAS remotely. I assumed the url implied that I was accessing GAS remotely. At the moment I am working on my localhost and on my JS above it works if the alert statement is present and does not do anything if alert is not there.
I was watching the execution list on GSuite Developer Hub to see if the request failed or completed. I observed if the alert statement is in the script the execution status is completed but if the alert statement is not there nothing happens. I assume that my post script is not working if alert is not there. Any idea why?
You haven't shown exactly how that function is called, but it's likely to be because, if this is truly a "form submit" action, the result of submitting a form is to "load a new page" (which can be the same page you're on, and is so by default with no action attribute in the form tag
Since you want to perform AJAX on form submit, you need to "prevent" the "default" form submit action - this can be achieved as shown in the second and third lines below
var url ="MY WEBAPP EXEC"
function submitForm(e) { // if this function is called using an event handler, it gets an event as the first and only argument
e.preventDefault(); // prevent the "default" form submit action
var postRequest = {}
postRequest.name = $("#inputName").val();
postRequest.email = $("#inputEmail1").val();
postRequest.message = $("#inputMessage").val();
alert(JSON.stringify(postRequest)); // this alert
$.post(url, postRequest, function(data,status){
alert('success')
});
}

jQuery .post() not seeming to work, no error

I've seen several questions here with the similar subject but I can't find anything which is relevant to my situation. I am trying to build jQuery code that is able to build a list of items to save it in an inventory database and I am using .post() those to a additems.php that will add them to that database (after sensitization), as well as the current path name so the .php can send the user back to the same page.
The behavior I am getting is nothing whatsoever with no console error (except the 'this works' alert when I leave that in.) The behavior I am looking for is, the page should redirect to additems.php as an html form action would, execute the code there and redirect back to this page.
Here is my piece of code:
$(document).ready(function(){
$("#button").click(function(){
alert("this works");
var itemsarray = ['itemname'];
var itemattributesarray = ['itemattribute'];
var quantitiesarray = ['1'];
$.post('additems.php', {
items:{items: itemsarray},
itemattributes:{itemattributes: itemattributesarray},
quantities:{quantities: quantitiesarray},
returnpath: window.pathname
});
});
});
Thank you for your time and any suggestions. I've never used this site so please let me know how I can improve my question as well, if you have the time.
An alternative way is,
$.ajax({
'url':'additems.php',
'method' : 'POST',
'data':{
'items':itemsarray,
'itemattributes':itemattributesarray,
'quantities' : quantitiesarray
},
success: function(data){
//here you will get ajax response
console.log(data);
}
});

Stop jQuery from returning entire page into my div

So I've got a form that has the action of 'create_topic_parse.php', it sends the input values to that from 'create_topic.php', then they are inserted into the database. I am able to send any errors from the 'create_topic_parse.php' file to the 'message' div in my 'create_topic.php' page using the following code:
$("#submit").click( function() {
// I've tried e.preventDefault(); here ^ but it's giving the same result.
$.post( $("#topic_form").attr("action"),
$("#topic_form :input").serializeArray(),
function(info) {
$("#message").empty();
$("#message").html(info).css('color','#be4343');
});
$("#topic_form").submit( function() {
return false; // Not working
});
});
When the form is CORRECTLY input, and no errors are to be passed from the PHP file, the PHP script is supposed to redirect the user to 'view_topic.php?cid=".$cid."&tid=".$new_topic_id."&page=1'. If I don't include the jQuery above, this works fine.
Problem: If I include the jQuery script, it returns the entire 'view_topic.php/etcetc' page into '', which is bad.
So the question is, does anyone know how to prevent the entire page from being posted into this div, and actually redirect the user to 'view_topic.php' page when the form is correctly submitted?
Note: I've tried window.location, however I've then the issue of the concatonated variables from my PHP file that are input into the 'view_topic.php/etcetc' url. I am trying to get it to work with header('location:...'), like it does when the jQuery file isn't included.
Thanks in advance,
Richie
Solution:
jQuery + Ajax to PHP:
if($('#topic_title').val() == ''){
$('#message').html("You need to give your topic a title.");
}
Using this code I was able to check whether each data entry existed, when all of the data values were existing I'd run the AJAX script within the same file passing each value into a variable like so:
var submit = $('#submit').val();
var topic_title = $('#topic_title').val();
$.ajax({
type: "POST",
url: "create_topic_parse.php",
data: {submit:submit, topic_title:topic_title),
etc etc.
Try this one. It'll work
when form is correctly submitted then only send some string like "correct", and in jquery let you check the ouput string. if it's "correct" then redirect it to view topic via javascript.
if you want to redirect the user to an specific page sent from server, then send from server something like this in json format.
write code on server something like this.
if ($condition==true) {
$ajax_return = array(
'message' => 'correct',
'url' => 'your_redirect_url'
);
}
else
{
$ajax_return = array(
'message' => 'your user defined error message',
'url' => 'leave it blank'
);
}
$ajax_return = json_encode($ajax_return);
echo $ajax_return;
and now jquery on create_topic.php page
$("#topic_form").submit( function(e) {
e.preventDefault();
$.post(
$("#topic_form").attr("action"),
$("#topic_form :input").serializeArray(),
function(info) {
info= JSON.parse(info);
if(info.message="correct"){
window.location=info.url;
}
else{
$("#message").html('');
$("#message").html(info).css('color','#be4343');
}
});
});
I'm sure now it'll work. If not, let me know.

Display user profile in div using ajax

I want to display user profile when admin mouser over on username link. If this is first time, user profile is displayed; then next time ajax should not fire and display user profile without ajax fire.
To implement the functionality proceed step by step:
On mouseover of the username, implement an ajax call that renders user profile in html near the username
Through javascript, implement functionality such that when user leaves the username/userprofile, the user profile div is now hidden
While making ajax calls in #1 above, check if the div already exist which contains user profile for the userid which you are trying to request. This can be easily achieved by having some id in the user profile part and checking if that #user_profile_#{id} div exists.
Your requirement is too broad to be able to provide any code...
If you have problem in implementation of any of the above parts, post them as question separately one by one..
You need to know the id and the class of the username link.
You can make jQuery listen to the hover, when that event occurs you can call the function which will do the ajax.
But, you need to know the id of the user, the best way to do that is to do something like
<a href='user123.php' class='userHref' id='user_123'>I want to be hovered</a>
Now you have a link to hover over.
$('.userHref').live("hover", function()
{
var userHrefId = $(this).attr('id');
var userHrefIdSplit = userHrefId .split('_');
var userId = userHrefIdSplit[1];
useAjax(userId);
});
Now you have listened to the hover by listening to any hovering over a link of the class userHref, jquery has responded by taking the id of the a element, splitting the id into 2 seperate items, where the second one indicates the user Id.
Now we have also called with useAjax function and we have sent the id of the user. Now you can POST the userId to a known backend site (rails in your example), which will query the database and return the url to the user image. We then only have to know the id of the div element which you want the image to appear in.
function useAjax(userId);
{
var id = userId;
var select = true;
var url = '../scripts/ajax.php';
$.ajax(
{
// Post select to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'select' : select, // the variable you're posting.
'userId' : id
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array
var userUrl, userImg, message;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
userUrl = data[i].userUrl;
message = data[i].message;
userImg = "<img src='"+userUrl+"' alt='' title='' />";
$('#someDiv').html(userImg); // Here's your image.
}
},
complete : function(data)
{
// do something, not critical.
}
});
}
I'm not familar with rails but you can probably program the backend in a similar wasy as I exmplained here: Javascript function as php?
Search for my answer, it should give you a very detailed example.
I hope this helps.
Tip for the future: Try and google first :)
Assuming you're using jQuery, bind a hover event to the user name link. As so:
$('.username').hover(function (e) {
console.log("i'm hovering!! on id: "+$(this).attr('data-user-id')); //See the next step for where this came from
}
Next, add the user's id to the username element, perhaps in a data attribute:
<span class="username" data-user-id="1234567890">Username</span>
Next, keep a record of which users are already loaded, perhaps by id. When you fetch something new, add it to the object. I like to keep objects like this on the window.
window.loadedUserInfo = {};
On hover check if the userId key exists in this object. If it does, user it. If not, use an ajax call to get it:
$.ajax({
url : "path/to/userinfo"+userid, //I'm assuming you're using restful endpoints
type : "GET",
success : function (res) {
window.loadedUserInfo[userid] = res;
//Format your popover with the info
},
error: function (jqxhr) {
//something went wrong
}
})
As for the popover itself, you could probably use a bootstrap popover.
Putting it all together:
$(".username").hover(function (e) {
console.log("i'm hovering!! on id: "+$(this).attr("data-user-id")); //See the next step for where this came from
if (typeof window.loadUserInfo[$(this).attr("data-user-id")] == 'undefined') {
$.ajax({
url : "path/to/userinfo"+userid, //I'm assuming you're using restful endpoints
type : "GET",
success : function (res) {
window.loadedUserInfo[userid] = res;
//Format your popover with the info
},
error: function (jqxhr) {
//something went wrong
}
})
} else {
//populate popover with info in window.loadUserInfo[$(this).attr('data-user-id')]
}
}

How do I make a jQuery POST function open the new page?

I know that a submit button in HTML can submit a form which opens the target page, but how do I cause a jQuery ajax call to POST information to a new page and also display the new page. I am submitting information that is gathered by clicking elements (which toggle a new class called "select") and then identifiers from these items with the new class are added to a string and POSTed to the new page. This new page will use this data to provide a summary of the selections from the previous page. I currently can get it to POST the data to a new PHP page but it seems to be the ajax function simply remains on the current page (which is great for some things, just not this), not redirecting to the new page. how might I go about doing this?
here's the script section:
//onload function
$(function() {
//toggles items to mark them for purchase
//add event handler for selecting items
$(".line").click(function() {
//get the lines item number
var item = $(this).toggleClass("select").attr("name");
});
$('#process').click(function() {
var items = [];
//place selected numbers in a string
$('.line.select').each(function(index){
items.push($(this).attr('name'));
});
$.ajax({
type: 'POST',
url: 'additem.php',
data: 'items='+items,
success: function(){
$('#menu').hide(function(){
$('#success').fadeIn();
});
}
});
});
return false;
});
any pointers would be great!! thanks
edit:
thanks for the help, I've changed my script to :
//onload function
$(function() {
//toggles items to mark them for purchase
//add event handler for selecting items
$(".line").click(function() {
//get the lines item number
var item = $(this).toggleClass("select").attr("name");
});
$('#process').click(function() {
var items = [];
//place selected numbers in a string
$('.line.select').each(function(index){
items.push($(this).attr('name'));
});
$('#items').attr('value',items);
$('#form').submit()
});
return false;
});
First of all I discourage using ajax here as you are not using it for the purpose for which it is intended to, and you are forcing it to do a reload.
You can do something like this in the success of ajax
success: function(){
window.location = "the new url you wanted to load";
}
Edit:
Why not do a normal post with form action attribute set to the page you want to post to and you can access all the variables of the form in that posted page, or alternatively you can concatenate or store in array all your values and store this array in a hidden variable and access this variable in the posted script.
Ajax posts by definition won't to a page load. But you can do whatever you want in your success handler. So just change the document location there:
success: function(){
$('#menu').hide(function(){
$('#success').fadeIn();
});
window.location = 'http://www.example.com/elsewhere';
}
Oftentimes a POST will return a HTTP 301 or 302 redirect. In that case, you can get the returned header information from the XHR object, which is passed into the callback functions.
complete: function( xhr ) {
// assume we got a redirect; the new URL will be in the Location header
window.location = xhr.getResponseHeader( 'Location' );
}

Categories