<script>
function postComment() {
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("commentHint").innerHTML = xmlhttp.responseText;
}
var comment = document.getElementById("comment").value;
var id = document.getElementById("postID").value;
xmlhttp.open("POST", "commentpost.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("comment=" + comment + "&postID=" + id);
}
}
</script>
<form>
<div id="comment">
<textarea name="comment" id="comment" rows="4" cols="125" style="max-width: 950px; max-height: 140px;" placeholder="<?php echo $_SESSION["name"] ?>, Write Your Comment Here" class="form-control"></textarea><br>
<div id="commentHint"></div>
<input type="submit" onclick="postComment()" value="Submit Comment" class="btn btn-success btn-sm ">
<input type="hidden" id="postID" name="postID" value="<?php echo $post_id ?>">
</div>
</form>
I have no idea why my AJAX POST request isn't working...
Here's the POST vars in my corresponding PHP FILE:
$comment = $_POST["comment"];
$postID = $_POST["postID"];
When ever I click the submit comment button it refreshes the page first and bring me back to the home page. It does not fire the php script either.. I'm new to AJAX can someone please tell me what's wrong
Your xmlhttp.send(...) call is within the onreadystatechange handler, for the handler method to get called you need to send the request so the ajax method is never executed.
The code that is responsible to send the request should be outside of the handler method.
function postComment() {
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("commentHint").innerHTML = xmlhttp.responseText;
}
}//need to close onreadystatechange here
var comment = document.getElementById("comment").value;
var id = document.getElementById("postID").value;
xmlhttp.open("POST", "commentpost.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("comment=" + comment + "&postID=" + id);
}
Note: If you use proper code indentation this kind of issues can be easily avoided.
Related
Hello I have a "select" drop down, with 2 "onchange" actions attached
echo "<select id='selecttask' name='task' onchange='showpcaction(this.value);showpcinterview(this.value);'>";
echo "<option disabled selected>";
while ($row = db2_fetch_assoc($stmt)) {
echo "<option value='".$row['TASK_NAME']."'>".$row['TASK_NAME']."`</option>";}
echo "</select>";`
the problem is that only ONE (it's always the sedond one) is actually started. I can get one of them to start but not BOTH.
I did this before with no problems so not sure what's up.
here are the 2 java scripts:
function showpcinterview(task_name) {
if (task_name == 'Interview'){
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("pc_interview").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","showpcinterview.php",true);
xmlhttp.send();
}
else{
document.getElementById("pc_interview").innerHTML ="";
}
}
function showpcaction(task_name) {
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("pc_action").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","showpcaction.php?task_name=" + task_name,true);
xmlhttp.send();
}
Try to simply declare your xmlhttp within your functions scope by using the var keyword.
In your case, as no var statement is present, the object is global and so, declared a first time in your first function, placing a listener and sending the request, but then imlmediately in your second function you redeclare this object, thus killing the readystate listener.
So just declare your object like this in both functions: var xmlhttp = new XMLHttpRequest();
carica.html
<td>
<input type="file" size="30" onchange="preview()" id="upload_immagine">
</td>
<td>
<div id="divImmagine" > </div>
</td>
filejavascript.js
function preview()
{
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("divImmagine").innerHTML=xmlhttp.responseText;
}
image=request.getParameter("upload_immagine");
document.getElementById("divImmagine").innerHTML=image;
xmlhttp.open("POST","stampaAnteprima.php", false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("image="+image);
}
stampaAnteprima.php
<?php
$file_temp=($_FILES['image']['tmp_name']);
echo"$file_temp";
?>
The line of javascript image=request.getParameter("upload_immagine"); returns nothing. How do I get the value to pass to php and then read the file via $_FILES['image']['tmp_name'] in practice it would be image? Do you have any advice?
This will allow you to send files to php.
You can add more eventlisteners to display the upload progress and error handling.
function UploadPhoto(){
var file = document.getElementById('upload_immagine').files[0];
var formdata = new FormData();
formdata.append("image", file);
var req = new XMLHttpRequest();
req.addEventListener("load", function(event) { uploadcomplete(event); }, false);
req.open("POST", "stampaAnteprima.php");
req.send(formdata);
}
function uploadcomplete(event){
// Your php reply = event.target.responseText
}
I am getting response without a refresh! When the user clicks on the button, I want it to reload and then display the response!How can I do that?
And What should I do to uncheck the radio box after the response?
<script>
function sendid(attack) {
var att;
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("result").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "battleuser2.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("att=" + attack);
}
</script>
This is my radio form:
<input type="radio" value="10" id="radioButtonId" onClick="sendid(this.value)"/> Attack 1
<input type="radio" value="20" id="radioButtonId" onClick="sendid(this.value)"/> Attack 2
No, you can't reload and display the response unless you are making the ajax call on page load again.
else you need to store the previous response in localstorage and access it from it when the page reloads again.
Regarding unchecking the radio button after the response, Insert the following code inside the if condition:
document.getElementById("radioButtonId").checked = false;
example:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("result").innerHTML = xmlhttp.responseText;
document.getElementById("radioButtonId").checked = false;
}
In my HTML I have this line of code:
<td>Username:</td>
<td><input type="text" size="40" id="username" name="username" /></td>
<td><input type="button" value="check" onclick="checkExistenceUsername()" /></td>
<td id="result_of_checking"></td>
How I tell to ajax that he has to take the content of the tag with id "username"?
This is javascript:
function checkExistenceUsername()
{
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("result_of_checking").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "check_existence.php", true);
xmlhttp.send();
}
I think you would need something like this answer
But instead of hard coded parameters you would need to add the input variable:
var params = "myvar="+encodeURIComponent(document.getElementById('username').value);
Can someone help me with sending this data to a .php page where I could receive it on my PHP page
javascript:
postToSql(){
var ajax;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
alert(ajax.responseText); //receiving response
}
};
var name = $("#entry_1274804157").val();
//alert(name);
var company= $("#entry_1828184698").val();
var phone=$("#entry_2039177352").val();
var email=$("#entry_1545475878").val();
var comments=$("#entry_1846523632").val();
var params = {
"name":name,
"company":company,
"phone":phone,
"email":email,
"comments": comments
};
//var jsonText = JSON.stringify(params);
ajax.open("POST", "view/templates/includes/insertgoogle.php", false);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send("totalJsonStr="+params);
//alert(totalJsonStr);
// alert(params);
return true;
}
</script>
HTML:
<form action="https://docs.google.com/asgsasdfasg/formResponse" method="POST" id="" target="_self" onsubmit="return postToSql();">
EDIT:
This is how I am receiving it:
if(isset($_POST['totalJsonStr']))
{
$jsonVal = json_decode($_POST['totalJsonStr']);
$jsonVal2 = json_decode($jsonVal);
var_dump($_POST['totalJsonStr']);
var_dump($jsonVal);
var_dump($jsonVal2);
$name = $jsonVal2->{'name'};
$company= $jsonVal2->{'name'};
$phone= $jsonVal2->{'name'};
$email= $jsonVal2->{'name'};
$comments= $jsonVal2->{'name'};
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
mysql_query("INSERT INTO `testgoogle` ( Name, Company, Phone, Email, Comments )
VALUES ('$name','$company', '$phone', '$email', '$comments')");
Print "Your information has been successfully added to the database.";
return;
}
else
{
die("No Data Found");
}
Where do you create the "ajax" object?
var ajax;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
from here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp
If you want to use $_GET then,
Remove:
ajax.open("POST", "view/templates/includes/insertgoogle.php", true);
Add:
ajax.open("GET", "view/templates/includes/insertgoogle.php", true);
Helpful link: http://www.degraeve.com/reference/simple-ajax-example.php
Using POST Method,
The perfect solution would be, store all values in an array and send the array as a json request using json.stringify().
In php, Use json_decode() to decode your json string.
UPDATE
Add this to your javascript,
<script type="text/javascript">
function postToSql(){
var ajax;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
ajax=new XMLHttpRequest();
}
else
{// code for IE6, IE5
ajax=new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
alert(ajax.responseText); //receiving response
}
}
var name = "1234";
var company= "1234";
var phone="1234";
var params = {
"name":name,
"company":company,
"phone":phone,
};
var jsonText = JSON.stringify(params);
ajax.open("POST", "view/templates/includes/insertgoogle.php", true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send("totalJsonStr="+jsonText);
}
</script>
<form action="https://docs.google.com/asgsasdfasg/formResponse" method="POST" id="" target="_self" onsubmit="postToSql();return false;">
Add this to php
<?php
if(isset($_POST["totalJsonStr"]))
{
$jsonVal = json_decode($_POST["totalJsonStr"]);
print $jsonVal->{'name'};
print $jsonVal->{'company'};
print $jsonVal->{'phone'};
}
else
{
die("No Data Found");
}
?>
since nothing was working for me, I finally used jquery ajax which worked.