My Ajax javascript code isn't working - javascript

My Ajax javascript code isn't working...
Here is the code:
function getMessages() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("box").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "process.php");
xmlhttp.send();
}
I have my php script just doing a test saying: this is a test.
I can't figure out what I did wrong. Chrome javascript debugger says that I have an unxpected token "."
PHP Code:
<?php if (!$_COOKIE["name"]) {
echo "<form method='get' action = 'process.php'><input type = 'text' name = 'name'><input type = 'submit' value = 'Submit'></form>";
} else {
echo '
function getMessages(){var xmlhttp;
if(window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest (); }
else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4&&xmlhttp.status==200) { document.getElementById("box").innerHTML=xmlhttp.responseText; } }
xmlhttp.open("GET","process.php") ;
xmlhttp.send(); }
var is={ie:navigator.appName=="Microsoft InternetExplorer",java:navigator.javaEnabled(),ns:navigator.appName=="Netscape",ua:navigator.userAgent.toLowerCase(),version:parseFloat(navigator.appVersion.substr(21))||parseFloat(navigator.appVersion),win:navigator.platform=="Win32"
}
is.mac=is.ua.indexOf("mac")>=0;
if(is.ua.indexOf("opera")>=0){is.ie=is.ns=false;is.opera=true;}
if(is.ua.indexOf("agecko")>=0)
{is.ie=is.ns=false;is.gecko=true;
}';
echo "<textarea id=box rows=20 cols=20></textarea>
<form method='get' action = 'process.php'>
<input type = 'text' name = 'message'>
<input type = 'submit' value = 'Submit'>
</form>";
} ?>

xmlhttp.readyStat should be xmlhttp.readyState perhaps?

readyStat should be readyState for one. Rest seems okay.

xmlhttp.send() to xmlhttp.send(null) can prevent IE bugs too

Related

why form data not passing?

I tried to make document for upload image in php but the document getiamge.php not accepting the form data and also giving warning.
index.php
<html>
<head>
<meta charset="utf-8">
<title>Image Upload</title>
<script>
function Insert()
{
var image= document.getElementById("image").value;
var name= document.getElementById("name").value;
if (image == "" && name == "")
{
document.getElementById("message").innerHTML="Please Fill The Fields";
return;
}
else if (image == "" || name == "")
{
document.getElementById("message").innerHTML="Please Fill The Form Correctly.";
return;
}
else
{
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 (this.readyState == 4 && this.status == 200)
{
document.getElementById("message").innerHTML = this.responseText;
}
};
xmlhttp.open("POST","getimage.php?name="+name+"&image="+image,true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
xmlhttp.send();
}
}
</script>
</head>
<body>
<form enctype="multipart/form-data">
<input type="file" id="image">
<input type="text" id="name">
<input type="button" value="Upload" onClick="Insert()">
<h6 id="message">yyys</h6>
</form>
</body>
</html>
getimage.php
<?php
include("2nd.php");
$a=$_POST['image'];
$name=$_POST['name'];
$path="images/".basename($_FILES['image']['name']);
$image=base64_encode($a);
$query="INSERT INTO images(image,name) VALUES ('".$image."','".$name."')";
$insert=mysqli_query($conn,$query);
if($insert)
{
move_uploaded_file($_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['name']))
{
echo "Uploaded Successfully";
}
else
{
echo "Not Uploaded successfully";
}
}
else
{
echo "Not Inserted";
}
?>
And the warnings are these
Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0
Notice: Undefined index: image in D:\xampp\htdocs\image\getimage.php on line 4
Notice: Undefined index: name in D:\xampp\htdocs\image\getimage.php on line 5
Notice: Undefined index: image in D:\xampp\htdocs\image\getimage.php on line 7
Notice: Undefined index: image in D:\xampp\htdocs\image\getimage.php on line 16
Notice: Undefined index: image in D:\xampp\htdocs\image\getimage.php on line 17
Not Uploaded successfully
Notice: Undefined index: image error is coming because you are sending image in POST data, so it will come in $_POST['image'] to receive in $_FILES['image']['name'] you have to use FormData() like as below:
'
function Insert()
{
var image= document.getElementById("image").files[0];
var name= document.getElementById("name").value;
if (image == "" && name == "")
{
document.getElementById("message").innerHTML="Please Fill The Fields";
return;
}
else if (image == "" || name == "")
{
document.getElementById("message").innerHTML="Please Fill The Form Correctly.";
return;
}
else
{
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 (this.readyState == 4 && this.status == 200)
{
document.getElementById("message").innerHTML = this.responseText;
}
};
xmlhttp.open("POST","getimage.php",true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
var formData = new FormData();
formData.append("image", image);
formData.append("name", name);
xmlhttp.send(formData);
}
}
</script>'

Get Smarty-formatted data from PHP script

My PHP script, that I call via XMLHttpRequest, executes a query and checks a condition, then outputs a HTML snippet with some Smarty code. When I try to insert that code in a <div> tag, either by calling the jQuery.html() function or by setting the innerHTML property, the Smarty code is printed as it is, thus not interpreted as Smarty code. How could I solve this problem?
Relevant code:
PHP Script:
<?php
$mysqli = new mysqli("localhost", "<<<SQL USERNAME>>>", "<<<SQL PASSWORD>>>", "<<<SQL DATABASE>>>");
$id = $_GET["idmf"];
$cat = $mysqli->query("<<<SQL QUERY>>>")->fetch_assoc()["category"];
if ($cat == $_GET["cat"])
echo 'blahblah';
?>
TPL file:
{foreach from=$manufacturers item=manufacturer name=manufacturers}
<div id="mffilter_{$manufacturer.id_manufacturer}"></div>
<script>
var xhttpf;
if (window.XMLHttpRequest)
{
xhttpf = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xhttpf = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttpf.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("mffilter_{$manufacturer.id_manufacturer}").innerHTML = this.responseText;
}
};
xhttpf.open("GET", "<<<ENDPOINT>>>.php?cat=food&idmf={$manufacturer.id_manufacturer}", true);
xhttpf.send();
</script>
Try replacing your TPL file code with the following code:
{foreach from=$manufacturers item=manufacturer name=manufacturers}
<div id="mffilter_"{$manufacturer.id_manufacturer}></div>
<script>
var xhttpf;
if (window.XMLHttpRequest)
{
xhttpf = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xhttpf = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttpf.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("mffilter_"{$manufacturer.id_manufacturer}).innerHTML = this.responseText;
}
};
xhttpf.open("GET", "<<<ENDPOINT>>>.php?cat=food&idmf="{$manufacturer.id_manufacturer}, true);
xhttpf.send();
</script>

Ajax in timer is affecting my server

I am using ajax so that i can read the content of a file from my server .I am calling a function where ajax is , in a timer.And this is affecting my server .It is crashing.If this is the correct way to do it , what's wrong?
Please give a few sugestions,because i don't know what its problem is.
I am calling first the function:"function(ctrl)".
function get(ctrl){
var content;
content=ctrl.id;
var getTextUpdate= setInterval(function () {
readdocument();
}, 1200);
}
function readdocument() {
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("area").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../user/test/read-text.php?user="+content,true);
xmlhttp.send();
}
Here it is the read-text.php file:
<?php
$rec_user=$_GET['user'];
echo($rec_user);
$chat = fopen($rec_user.".txt", "r") or die("Unable to open file!");
echo fread($chat,filesize($rec_user.".txt"));
fclose($chat);
?>
The problem with your code is that, you are not waiting for the response to get over. So over the time, you are sending request after request. This is going to use up all memory in due time. So first wait for the response before sending the next request.
How about this ?
function loadXMLDoc(ctrl) {
var content=ctrl.id;
var xmlhttp = new XMLHttpRequest();
var url = "../user/test/read-text.php?user="+content;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById("area").value=xmlhttp.responseText;
setTimeout(loadXMLDoc(), 1200); //call the function again
} else if (xmlhttp.status == 400) {
console.log('There was an error 400');
} else {
console.log('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
};
loadXMLDoc(ctrl);

show result dynamically in search box

I want a search box which shows the result just below it when I click the search button without reloading the page.
for this I've js function called ShowUsers(str)
like this
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML =
xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
And a html form like this :
<form>
<input type="text" name="q"/>
<script type="text/javascript">var x = document.getElementById("q").value; </script>
<input type="button" value="search" onclick="showUser(x)">
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
I've one php file to show the result called as GetUser.php
I think the var x deos'nt pass to the ShowUser(str) function in the input tag I think this is not a right way to pass a js var into html event
so what can i do to show the data
Access document.getElementById("q").value directly in showUser function rather than passing x to showUser function.
function showUser() {
var str = document.getElementById("txtHint").value;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML =
xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}

AJAX function( ) part alone not working

After function() it is not working, i don't know why. If I put an alert before that statement it's working but after that statement it isn't working.
<script>
function new_order() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
alert("asdasd");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("order_id").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "item_sort.php?sort=" + str, true);
xmlhttp.send();
}
</script>
3 things you can check
If an element corresponding to id order_id exists on the page
if the str is not null or not defined
If you are using older IE versions IE5 or 6 you need to add the
following in your code.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
Also you need to use the following way if you want to do POST ajax call.
xmlhttp.open("POST", "item_sort.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("sort=" + str);

Categories