I want to send a section of html content (not a form data) through AJAX.
I know how to do this in jQuery but i want to achieve with javascript.
HTML (I want to send content who has id=stack)
after clicking on SEND button button, response must be loaded in id=target
<div id='stack'>
<ol>
<li>stack 1</li>
<li>stack 2</li>
<li>stack 3</li>
</ol>
</div>
<button id='btn'>SEND</button>
<article id='target'></article>
AJAX
var btn = document.getElementById('btn');
var target = document.getElementById('target');
// Function for AJAX
function stack(){
var main = document.getElementById('stack');
var xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
xhr.onreadystatechange = function(){
if(xhr.readyState ==4 && xhr.status == 200){
target.innerHTML = xhr.responseText;
}
}
xhr.send(main);
}
// Bind with the onclick event
btn.addEventListener('click',stack,false);
process.php
<?php
$div = $_POST;
print_r($div);
?>
After running my above code it is just displaying Array()
because Ajax method is not sending the div.
Please help me using Javascript instead of jQuery
Do not send the element reference itself, get the outerHTML property and send that one like so: xhr.send(main.outerHTML);
This sends a string version of the element including its descendants.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML
okay guys !
I asked the above question and finally successfully solved my problem.
So I am going to share my solution with you (love).
SOLUTION :
AJAX
There is one line of code i missed in ajax.
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
So the full Ajax code will be -
var btn = document.getElementById('btn');
var target = document.getElementById('target');
// Function for AJAX
function stack(){
var main = document.getElementById('stack');
//*****new line added
var data = 'key' + '=' + main.outerHTML;
var xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
//*****(new line added) must add when working with POST data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function(){
if(xhr.readyState ==4 && xhr.status == 200){
target.innerHTML = xhr.responseText;
}
}
xhr.send(data);
}
// Bind with the onclick event
btn.addEventListener('click',stack,false);
process.php
<?php
$div = $_POST;
echo $div['key'];
?>
Thank You !
Related
I'm trying to use ajax to parse data to be processed on a php page and have php echo a javascript redirect to another page but it is not working. I have read that js does not work after running an ajax call so I will like to know if there s a way around it. This is my code:
html
<form>
<div class="depart_time bottom_white w-40 ml-auto">
<p>Time</p>
<input type="time" name = "return_time" id = "rt">
</div>
<div class = "search_button r_search">
<button id = "r_search" onclick = "return false" onmousedown = "rent()">SEARCH</button>
</div>
</form>
ajax call is a normal xhttp request that gets sent to php for processing after which a redirection should occur:
if(isset($_POST['return_time'])){
echo '<script type="text/javascript">window.location.href="link.html"</script>';
}
Please an help is appreciated. I'm new to using ajax.
EDIT
the ajax code:
gid("r_search").addEventListener("mousedown", rent);
function rent(){
rt = gid('rt').value;
r_search = gid('r_search').value;
form_array = '&rt=' + rt +
'&r_search=' + r_search;
send_data = form_array;
ajax_data('app/rent.php', 'error', send_data);
//gid('error').innerHTML = send_data;
}
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
gid(getId).innerHTML = xhttpReq.responseText;
}
};
xhttpReq.send(send_data);
}
please note that 'gid' is for getelementbyid
You have to make bit alteration to your way of redirection.
First you need to make changes in your PHP response
if(isset($_POST['return_time'])){
...
// If you get your process success return 1
if(success) {
echo 1; die();
} else {
// else set some flag that you could get on your AJAX response
echo 0; die();
}
}
Now, get this flag on your AJAX and make changes to your below functions:
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if( xhttpReq.responseText == 1 ) window.location.href="URL where you wish to redirect page";
}
};
xhttpReq.send(send_data);
}
I've written this answer for others who come here for help.
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();
I am trying to send post id in js. I can send the first post id but how can I send each post's id. inspect element looks like this
<div data-id="post_1"></div>
<div data-id="post_2"></div>
<div data-id="post_3"></div>
<script type="text/javascript" >
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.querySelector('[data-id=post_1]').innerHTML = req.responseText;
}
}
req.open('GET','chat.php?id=1>',true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
here is the code
<div data-id="post_<?php echo $post_id;?>"></div>
<script type="text/javascript" >
function ajax(){
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(req.readyState == 4 && req.status == 200){
document.querySelector('[data-id=post_<?=$post_id?>]').innerHTML = req.responseText;
}
}
req.open('GET','chat.php?id=<?=$post_id?>',true);
req.send();
}
setInterval(function(){ajax()},1000);
</script>
All the posts are on the same page. But I am able to get only one post's id. How can I get id post_2 and post_3 in js?
The js shows comment for each post. Only first post is showing comments cause js is getting only the first post's id. Rest are not showing anything.
How can I do the same for every post ?
querySelector will never give you more than 1 element. If you need all elements that satisfy your query, use querySelectorAll.
Using PHP in your JS code means that it will only ever use 1 post_id
Easiest way to do this would be to add a class or other data-attribute to your divs:
<div data-type="post" data-id="1">a</div>
<div data-type="post" data-id="3">b</div>
<div data-type="post" data-id="2">c</div>
You can use the new attribute to get them all and iterate over them.
var elements = document.querySelectorAll('[data-type="post"]')
for (var i = 0; i < elements.length; i++) {
var postId = elements[i].getAttribute('data-id')
// do ajax stuff
// ... then
elements[i].innerHTML = 'ajax response'
}
https://jsfiddle.net/w6kazkm1/4/
edit: Misunderstood your question. Answer is now updated.
I came across the question : How do I load an HTML page in a <div> using JavaScript?
I want to basically do the same thing with POST data but I'm not sure where to start.
The existing script works with get requests only?
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
I would like to avoid using jQuery if I can avoid it.
You can use the same ajax example you had posted in your comment, by changing the http://www.yoursite.com/home.html to home.html
Similar to below
In Javascript,
<script>
function load_home(e, getwhat){ // <--- send which html file to get and display the content in argument 'getwhat'
e.preventDefault();
var con = document.getElementById('content');
var xhr = new XMLHttpRequest();
xhr.open("POST", getwhat, true); // <-- this is post request
//xhr.open("GET", getwhat, true); // <-- this is get request
xhr.setRequestHeader('Content-type', 'text/html');
xhr.onreadystatechange = function(e) {
if(xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.send();
}
</script>
In HTML,
HOME
ABOUT US
SERVICE
<div id="content"></div>
The best aproach is to use jquery like this working demo
html
<nav id="menu" class="menu-side">
About
Help
Contact
</nav>
<div id="target">
<!-- content is being loaded here from other .html files -->
</div>
javascript
$(function() {
var $menu = $('#menu'),
$target = $('#target');
$menu.on('click', '> a', function(event) {
var $this = $(this);
event.preventDefault();
$target.load($this.attr('href'));
});
})
So I am trying to create an addFriend() function that only activates when an li tag within the HTML is clicked. This is my very simple HTML block that is relevant to the question:
<li id="add_friend" onclick="addFriend();">Add friend</li>
This is my javascript function that is called when the li tag is clicked. I am using a get request for the ajax response.
function addFriend() {
document.getElementById("add_friend").innerHTML = "please wait...";
//ajax
var ajax = new XMLHttpRequest();
ajax.open("GET", "php/friend.php", true);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById("add_friend").innerHTML = ajax.responseText;
}
};
ajax.send();
}//END addFriend
This is what friends.php looks like. It just a temporarily test function
<?php
echo "This is a test";
?>
I just threw an echo within the php script to check if there was a response. However every time I click on the li tag I receive a 500 error on the ajax.send(); line of code in the javascript. What am I doing wrong?