Use ajax to transport JavaScript data to PHP - javascript

raise.js:
window.onload=init;
function init(){
var submit=document.getElementById("submit");
submit.onclick=sub;
}
function sub(){
var url="raise.php";
var title=document.getElementById("title");//title of a question
var content=document.getElementById("inputContent");//content of a question
var checktype=document.getElementsByName("type");
var type;//type of a question
if(checktype[0].checked){
type="java";
}
else if(checktype[1].checked){
type="c++";
}
else{
type="html";
}
var point=document.getElementsByTagName("select");
var reward=point[0].value;//reward point
url=url+"?title="+title.value;
url=url+"?content="+content.value;
url=url+"?type="+type;
url=url+"?reward="+reward;
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
alert("asde");
}
}
xmlhttp.open("GET",url,true);
xmlhttp.setRequestHeader("Content-Type","utf-8");
xmlhttp.send();
}
raise.php:
<?php
echo "<script>alert('123')</script>";
$title=$_GET['title'];
$content=$_GET['content'];
$reward=$_GET['reward'];
$type=$_GET['type'];
?>
that confuses me alert('123') is not executed but alert("asde") is ,I want to know why..and am I right while trying to retrieve these data with php...I'm not very familiar with ajax...please show me some codes based on my data..thank you very much..

A script element won't do anything unless it is part of a rendered HTML document.
The server returns it to the browser, then it sits in xmlhttp.responseText where you are ignoring it.
(That said, even if you didn't ignore it, you might still have problems).

You simply not attaching the response body (the JavaScript) to your DOM, try:
// ...
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
alert("asde");
alert(xmlHttp.responseText);
// here you have to attach xmlHttp.responseText to your DOM
}
}
// ...
This should alert you "asde" and after that "script>alert('123')/script>"

You better use Jquery with Ajax to POST or GET data instead of only Ajax. You can have a look here jquery ajax. Here you will find out where alert should be used.

Related

How to load data from an XML file using php to show it in an html page with javascript

I'm doing an assigment for my programming class. I need to show a table with two columns (name and lastname) of a list of friends. This data is stored in a XML file like this:
<?xml version='1.0' standalone='yes'?>
<amigos>
<amigo>
<nombre>Alejandra</nombre>
<apellido>Ponce</apellido>
</amigo>
<amigo>
<nombre>Dalia</nombre>
<apellido>Gordon</apellido>
</amigo>
I retrieve this data with php, like this:
<table width="200" border="1">
<tr align="center">
<td>NOMBRE</td>
<td>APELLIDO</td>
</tr>
<?php
$amigos = simplexml_load_file('listaamigos.xml');
foreach ($amigos->amigo as $amigo) {
echo '<tr>';
echo '<td>',$amigo->nombre,'</td>';
echo '<td>',$amigo->apellido,'</td>';
echo '</tr>';
}
?>
I call this php file with a function written in javascript language. I'm using ajax for this homework. My javascript file is the one I'm showing below:
var xmlHttp;
function createXmlHttpRequestObject() {
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)
{
xmlHttp=false;
}
}
else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e)
{
xmlHttp=false;
}
}
if(!xmlHttp)
alert('Can't connect to the host');
else
return xmlHttp;
}
function cargarAmigos(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function cargar(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function procesarEventos()
{
if(xmlHttp.readyState == 4)
{
document.getElementById("listaAmigos").innerHTML= xmlHttp.responseText;
}
}
I use this javascript file in a html file. I call the function cargar () in the button's onclick event, like this:
<body>
<div id="listaAmigos" >
Lista amigos
</div>
<button onclick="cargarAmigos('procedimiento.php');">Lista Amigos Ajax</button>
</body>
The problem is that the code is not working. I mean that the names are not displaying at all in the table. Actually the table does not appear.
I'm pretty sure that the error is not in the code because it was working last week and I haven't changed the code since then. But today I loaded the html page just for "fun" and it wasn't showing my list of friends.
So I decided to open another project with uses the same algorithm and this one is not working too. I've checked that all the files are in the same folder. I've checked my xammp server and it's apache and mysql services are on. I have no idea what "thing" I could have done to cause this problem.
Any help will be really appreciated.
It looks like you should escape the ' character in this line:
alert('Can't connect to the host');
i.e. rewrite it like
alert("Can't connect to the host");
You can see that there's an error even just by looking at the formatting on Stack Overflow :)
Please refer to this question for the details on why it's working like that: When to use double or single quotes in JavaScript?

AJAX variable are not reading from PHP file?

This is my javascript that holds the function to save the file.
function saveMap()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
map = document.getElementById("sectorTableMap").innerHTML;
data = '<table id="sectorTableMap">';
data += map;
data += '</table>';
document.getElementById("sectorTableMap").innerHTML = data;
//alert("done");
//alert(data);
if(fileName=="lastSave - RENAME") {
return alert("Please set a file name under [CONFIG]");
}
else {
//alert(data);
//alert(user);
//alert(fileName);
xmlhttp.open("POST","http://pardustools.comuf.com/saveMap.php?t="+Math.random(),true);
xmlhttp.send('map='+data+'&user='+user+'&fileName='+fileName);
//alert(data);
//alert(user);
//alert(fileName);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//return alert("File has successfully been saved!");
return alert(xmlhttp.responseText);
}
}
}
This is my files that is posted too.
<?php
$user = strtolower($_POST['user']);
$map = $_POST['map'];
$fileName = "savedMaps/".$user."/".$_POST['fileName'].".html";
file_put_contents($fileName,$map);
echo $fileName."<br />".$map;
?>
This is the output I receive on the php file.
savedMaps//.html
It should be more like this
savedMaps/randomName/fileName.html
EDIT:
To set for the user.
user = "<?php $cookie = $_COOKIE['mapperlogauth']; echo strtolower($cookie['user']);?>";
To set for the data...
It is under the saveMap() function and starts with map.
You are using PHP's $_POST get, you're not posting any variables, you should use $_GET in your situation, or change your xmlhttp send to post properly. edit you are also missing the content type header to do a successful post
edit You should also be aware that there is a limit on how much you can send through using the technique you're using. (which is a get, not a post, even though you specify it)
I'd also recommend looking into jQuery for cross-browser compatibility and ease of use.
edit
Here's some code that will allow you to pick it up via POST:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
Have you tried to use :
xmlhttp.send('map=dummy&user='+user+'&fileName='+fileName);
I doubt it may be caused by the encoding.

Replacing content using AJAX when clicking a link

I want to use AJAX to replace the contents of a div. Although the application is fairly complex, I have tried to dumb it down in isolation so that I can get the basic concept working first.
For now, I just want to replace a div as per the PHP file...
<?php
$id = $_GET['id'];
if ($id = 1)
{
$text = 'This is some text';
}
elseif ($id = 2) {
{
$text = 'This is a lot more text than the first text!';
}
elseif ($id = 3) {
{
$text = 'This is a lot more text than the first text, and a load more than the third as well!!';
}
echo $text;
?>
Fairly simple stuff really. So here's my HTML file...
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">I want this content replacing</div>
ID: 1<br>
ID: 2<br>
ID: 3
</body>
</html>
I realise what is there will never work as I've modified some stuff I found online, but basically I'm looking to pass a variable such as the ID in the link to the AJAX script to replace the contents of the div.
How do I get this working? Is there a better alternative to using <a> tags?
Using jQuery
Your HTML
ID: 1
Javascript
// Delegate click event
$(document).on('click', 'a.ajax', function(){
var el = $(this);
$.ajax({
url: 'ajax.php',
data: {id: el.data('id')},
}).done(function(response){
$('#myDiv').html(response);
});
return false;
});
I'll answer your question using Vanilla JavaScript rather than using the jQuery AJAX Helper. Although it's very good - but learning the Vanilla way will give you a good idea of what the libraries do to aid you.
Firstly, you are making an Ajax call but albeit, an Empty one.
"Query" parameters is what $_GET is based on, are formated like:
?Key=Value&KeyTwo=SomeOtherValue
Which in PHP, Translates too:
Array
(
[Key] => Value
[KeyTwo] => SomeOtherValue
)
This'll need to be passed along with the xmlhttp.send() for it to make an successful ajax call, with Data.
But to collect this data in the first place, you must collect it with your HTML:
<!-- Notice how the <a> tags now have attributes attached, the id="" -->
ID: 1<br />
ID: 2
<script>
function loadXMLDoc( Id ) {
/**
* Id is the <a href="#" id="3" collected
* when onclick="loadXMLDoc()" is pressed
**/
var xmlhttp,
DataId = Id.attributes.id.value;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
/**
* Notice the ?id="+ dataId +"
* It's passing through the ID Collected
**/
xmlhttp.open("GET","ajax.php?id="+ dataId +"",true);
xmlhttp.send();
}
</script>
Although this code above is very inefficient, you would be much better in JavaScript & Programming in general to keep things generic. By modifying your code to:
ID: 1<br />
ID: 2
<script>
function getId() {
alert( this.attributes.id.value );
//Click on id="2", alerts '2'
}
/**
* We find all the HTML tags with the
* attribute that has 'class="idlistener"
* attached, we 'bind' it to a function called
* getId()
**/
var IdListener = document.getElementsByClassName('idlistener');
for( var x = 0; x < IdListener.length; x++ ) {
IdListener[x].addEventListener( 'click', getId, false );
}
</script>
Demo: Fiddle
Lastly, It does look to me you've discovered this AJAX Code from W3Schools.com. I think you'll find every StackOverflow Web Developer that would agree with me - Don't learn from this Site!
General format for replacing html content with the response from an ajax call:
$.ajax({
url: yourUrl,
method: 'get', // or 'post'
success: function (response) {
$('#myDiv').html(response);
}
// other ajax options here if you need them
});
You dont need to use ajax for that. Just use the following in the condition. Dont forget to call the jquery js file on the header. Otherwise jquery wont work:
echo '<script>$("#myDiv").html("This is some text")</script>';

Getting the responseText from XMLHttpRequest-Object

I wrote a cgi-script with c++ to return the query-string back to the requesting ajax object.
I also write the query-string in a file in order to see if the cgi script works correctly.
But when I ask in the html document for the response Text to be shown in a messagebox i get a blank message.
here is my code:
js:
<script type = "text/javascript">
var XMLHttp;
if(navigator.appName == "Microsoft Internet Explorer") {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
XMLHttp = new XMLHttpRequest();
}
function getresponse () {
XMLHttp.open
("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
XMLHttp.send(null);
}
XMLHttp.onreadystatechange=function(){
if(XMLHttp.readyState == 4)
{
document.getElementById('response_area').innerHTML += XMLHttp.readyState;
var x= XMLHttp.responseText
alert(x)
}
}
</script>
First Names(s)<input onkeydown = "javascript: getresponse ()"
id="fname" name="name"> <br>
Surname<input onkeydown = "javascript: getresponse();" id="sname">
<div id = "response_area">
</div>
C++:
int main() {
QFile log("log.txt");
if(!log.open(QIODevice::WriteOnly | QIODevice::Text))
{
return 1;
}
QTextStream outLog(&log);
QString QUERY_STRING= getenv("QUERY_STRING");
//if(QUERY_STRING!=NULL)
//{
cout<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<< QUERY_STRING.toStdString()<< "\n";
outLog<<"Content-type: text/plain\n\n"
<<"The Query String is: "
<<QUERY_STRING<<endl;
//}
return 0;
}
I'm happy about every advice what to do!
EDIT: the output to my logfile works just fine:
Content-type: text/plain
The Query String is: fname=hello&sname=world
I just noticed that if i open it with IE8 i get the query-string. But only on the first "keydown" after that IE does nothing.
You don't have to use javascript: in on___ handler, just onkeydown="getresponse();" is enough;
IE>=7 supports XMLHttpRequest object, so directly checking if XMLHttpRequest exists is better than checking whether navigator is IE. Example:
if(XMLHttpRequest) XMLHttp=new XMLHttpRequest();
else if(window.ActiveXObject) XMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
inside your getresponse() function, try to add below code at the beginning (before open):
try{XMLHTTP.abort();}catch(e){}
Because you're using a global object, you may want to "close" it before opening another connection.
Edit:
Some browser (maybe Firefox itself?) do not handle non-"text/xml" response very well in default state, so to ensure things and stuffs, try this:
function getresponse () {
try{XMLHttp.abort();}catch(e){}
XMLHttp.open("GET", "http://localhost/cgi-bin/AJAXTest?" + "fname=" +
document.getElementById('fname').value + "&sname=" +
document.getElementById('sname').value,true);
if(XMLHttp.overrideMimeType) XMLHttp.overrideMimeType("text/plain");
XMLHttp.send(null);
}
My problem had nothing to do with the code...
I was testing my script on the local IIS7 and I opened the html-page with double-clicking on the file. But you have to open the webpage via browser (localhost/mypage.htm) because otherwise for the browser the html and the executable have different origins. which is not allowed.

Ajax resending XMLHttpRequest

I've got a client side js/ajax script like this:
<p>server time is: <strong id="stime">Please wait...</strong></p>
<script>
function updateAjax() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==3 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
}
if (xmlhttp.readyState==4) {
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
}
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
window.setTimeout("updateAjax();",100);
</script>
And a on the server side:
<?php
echo 6;
for ($i=0; $i<10; $i++) {
echo $i;
ob_flush(); flush();
sleep(1);
}
?>
After first 'open' and 'send' it works ok, but when the server finishes the script and xmlhttp.readyState == 4 then the xmlhttp resends the request but nothing happens.
Instead of re-using the same XHR object all the time, try repeating the function with a new object. This should at least fix incompatibility issues as you listed.
Try re-calling your Ajax function inside the callback of it, if you want to loop it infinitely.
if (xmlhttp.readyState==4) {
updateAjax(); //or setTimeout("updateAjax();",100); if you want a delay
}
I'd also suggest putting your .innerHTML method inside the .readyState==4, which is when the requested document has completely loaded, and .status==200 which means success. Like this:
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
updateAjax(); //or setTimeout("updateAjax();",100);
}
Also, if you want your Ajax to be cross-browser, you should test if the browser supports the XHR object which you're using:
var xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
I just typed the code above but it should work just fine to add compatibility with older versions of IE and other browsers.

Categories