How to access array in another page after sending through ajax - javascript

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

Related

Flask page not refreshing in the browser after xmlHttpRequest() send

I am using an event listener to intercept a form submission, wait for a confirmation and then submit the form using xmlHttpRequest. The POST to my page seems to be working (meaning I can detect all the form fields I would expect) however, at the end of the Flask view handler code, the redirect does not cause the browser to refresh the page. In the view handler I try to redirect the page using return redirect('/pagename')
The positive outcome in my event listener handler code is:
// The positive action was chosen
.then(() => {
url = event.submitter.formAction
submit_element = event.submitter;
len = event.srcElement.length
const formData = new FormData();
for (i = 0; i < len; i++) {
formData.append(event.srcElement[i].name, event.srcElement[i].value )
}
const request = new XMLHttpRequest();
request.open("POST", url, true);
request.send(formData);
})
In my flask app I also have:
#app.after_request
def after_request(response):
"""Ensure responses aren't cached"""
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
response.headers['Cache-Control'] = 'public, max-age=0'
return response
If I don't intercept the form submission with the event listener then the form submission and page redirect works as expected.
Is there something else I need to include in my xmlHttpRequest.send() call to fully simulate the form submission? Any ideas about what might be going on here much appreciated.
Using the JavaScript fetch() instead of the XMLHttpRequest() worked for me to solve my issue. The fetch() function POSTS the data and I can use the .then() clause to redirect to the location after the fetch().
I was able to use code like below to POST all the fields from the form submit, intercepted by my event listener; and then force a page reload of the page that the form was submitted from.
.
.
// get url of submitting page
url = event.submitter.formAction;
// work out how many fields we have
len = event.srcElement.length;
// add each field to a formData object
const formData = new FormData();
for (i = 0; i < len; i++) {
formData.append(event.srcElement[i].name, event.srcElement[i].value );
}
// post the data
response = fetch(url,
{
body: formData,
method: "post"
});
response.then(response => {
console.log(response);
// reload the page
document.location = response.url;
.
.

how to ajax for chatting website without page reload

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

Dynamic Form Action URL

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)

How to use ajax to use post and locate it's url

What I want to achieve:
I need to use POST method then after success, it will locate to another url of ajax along with the POST data.
This is what I have done so far:
<script>
$("#btnSubmit").click(function(){
var ddate = $("#ddate").val();
var empid= $("#empid").val();
$.ajax({
type:'POST',
url:'../PaySlip/view_payslip.php',
data:{numnumnum:empid,dateito:ddate},
success:function(){
window.location ="../PaySlip/view_payslip.php";
}
});
});
Problem:
Upon success, the view_payslip cannot gather the POST data that I have transferred. I know what I did was wrong. That is why I'm asking for help to how to get this right.
Thank you in advance.
What you need to do is to post dynamic form in success callback.
I have also similar requirement in one of my project and for that I have created a method similar to shown below.
In this method you need to pass URL, windows option and params which is your data object, name is the window name, if you want to open in same window then instead of opening a new window you can pass blank in name param and omit the window.open() statement. You can modify it as per your requirement.
function submitDynamicForm(url, windowoption, name, params)
{
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", url);
form.setAttribute("target", name);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = params[key];
form.appendChild(input);
}
}
document.body.appendChild(form);
window.open("", name, windowoption);
form.submit();
document.body.removeChild(form);
}

how do you connect an ajax post to a specific conditional in PHP file?

So i have written a function that is called onclick in my html file that uses AJAX, but i would like for this post to go to a specific table in mysql.
$('#submitIFC').click(function(e) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var opinionIFC = $('ul.sort').sortable('toArray').join(',');
request.onreadystatechange = function() {
if ((request.readyState===4) &&(request.status===200)) {
var return_data = request.responseText;
document.getElementById('rank_ul').innerHTML= 'return_data';
// Preventing the default action triggered by clicking on the link
e.preventDefault();
e.preventDefault();
}//end of if
}//end of onreadystatechange function
//send requested movie to php file which will send to the external server
request.open("POST", "results.php", true);
request.send(opinionIFC);
document.getElementById('rank_ul').innerHTML='<img src="ajax-loader.gif">';
});
however there seems to be an issue with connecting this to my php if conditional, i tried copying the contents on my request.send(), like so
if($_POST['opinionIFC'])
{echo
// The data arrives as a comma-separated string,
// so we extract each post ids:
$data=explode(',',str_replace('li','',$_POST['sortdata']));
// Getting the number of objects
list($tot_objects) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM sort_objects"));
if(count($data)!=$tot_objects) die("Wrong data!");
foreach($data as $k=>$v)
{
// Building the sql query:
$str[]='('.(int)$v.','.($tot_objects-$k).')';
}
$str = 'VALUES'.join(',',$str);
// This will limit voting to once a day per IP:
mysql_query(" INSERT INTO `sort_votes` (ip,date_submit,dt_submit)
VALUES ('".$_SERVER['REMOTE_ADDR']."',NOW(),NOW())");
// If the user has not voted before today:
if(mysql_affected_rows($link)==1)
{
mysql_query(' INSERT INTO `sort_objects` (id,votes) '.$str.'
ON DUPLICATE KEY UPDATE votes = votes+VALUES(votes)');
}
}
why isnt the ajax post request filtering through to my php file?
thank you so much, any help is much appreciated.
You're not sending opinionIFC parameter, try:
request.send('opinionIFC=' + opinionIFC);
You also need to set Content-type
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");

Categories

Resources