I created ajax function which sends data to php file but something is wrong because when i die it, it holds nothing, and i know that my ajax function was written good. Here is how am i sending it:
xmlhttp.send(dop);
And here is how i recieve it in php file:
$selectedLang = isset($_POST['dop']) ? $_POST['dop'] : '';
What am i doing wrong? I'am probably recieving info badly. Coz i can see that parameteres are good in ajax function. Please help, really need fast.
<script type="text/javascript">
function run()
{
var dop = document.getElementById("kalba").value;
return dop;
}
function insertData()
{
var dop = run();
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","style/wps-light/datafile.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("Reiksme=" + encodeURIComponent(dop));
}
</script>
datafile.php:
<?php
$selectedLang = isset($_POST['dop']) ? $_POST['dop'] : '';
die("Viskas ok $selectedLang");
?>
You need to get it like that:
$selectedLang = isset($_POST['Reiksme']) ? $_POST['Reiksme'] : '';
Because Reiksme is the key in $_POST array, not dop:
xmlhttp.send("Reiksme=" + encodeURIComponent(dop));
^^^^^^^
Related
Code below is run in the onLoad event of the page. I first would like to populate a drop down menu with getCompany() and then fill in data from the server into text boxes and choose the selected option.
Both functions work, in fact when I reload the page with debugger running and step into everything both do what they are supposed to.
When I just open the page or reload with out debugger the text boxes are filled but the options disappear from the dropdown, why is that?
<script>
var result;
function init(){
var name = window.name;
name = name.split(",");
getCompany();
setTimeout(200);
if (name[0] = "update"){
id = name[1];
getTenant(id);
//get the info for the line that called the edit function
//fill fields with information from server
}
}
function getCompany() {
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 x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getCompany.php",true);
xmlhttp.send();
}
function getTenant(id){
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 y() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
result = xmlhttp.responseText;
result = result.split(",");
//fill the form with old information
document.getElementById("fname").value = result[0];
document.getElementById("lname").value = result[1];
document.getElementById("company").selectedIndex = result[2];
document.getElementById("phone").value = result[3];
document.getElementById("email").value = result[4];
document.getElementById("crm").value = result[5];
}
}
xmlhttp.open("GET","getTenant.php?p=" + id,true);
xmlhttp.send();
}
</script>
I assume the input fields you are filling in data in the second request belong to the data fetched from the first request. I also assume you are using the setTimeout() to delay the 2nd request...
Javascripts are single threaded. To provide asynchronous behavior js uses callback mechanism. After sending a request to the server, js doesn't wait until the response comes. JS keeps executing the rest of code until the results from the server comes. When the response comes from the server the code in the callback function xmlhttp.onreadystatechange is executed. Because of that, both requests may happen at almost the same time and consequently the response for the 2nd request may come before the first response which leads the behavior you see as an error.
When you debug, you execute line by line. Therefore there is enough time to get the response for the first request before getting the response for the second request.
As a solution you can move the code for the second request inside the xmlhttp.onreadystatechange callback in the code for the first request. Then as the callback is always executed after the results are fetched, the second request is sent after the response for the first one comes.
You may google about asynchronous javascript and learn in details...
<script>
var result;
function init(){
var name = window.name;
name = name.split(",");
getCompany(name);
}
function getCompany(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 x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
if (name[0] == "update"){
id = name[1];
getTenant(id);
//get the info for the line that called the edit function
//fill fields with information from server
}
}
}
xmlhttp.open("GET","getCompany.php",true);
xmlhttp.send();
}
function getTenant(id){
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 y() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
result = xmlhttp.responseText;
result = result.split(",");
//fill the form with old information
document.getElementById("fname").value = result[0];
document.getElementById("lname").value = result[1];
document.getElementById("company").selectedIndex = result[2];
document.getElementById("phone").value = result[3];
document.getElementById("email").value = result[4];
document.getElementById("crm").value = result[5];
}
}
xmlhttp.open("GET","getTenant.php?p=" + id,true);
xmlhttp.send();
}
</script>
It is happening because of a race condition between the two XHR calls made from getCompany and getTenant methods. Even though you are making the getTenant call 200ms after making the first XHR call there is no guarantee that the getComapny XHR call will finish first. When that happens the follwoing line of code
document.getElementById("company").innerHTML = xmlhttp.responseText;
removes all the options from the menu and also resets the selected index. To circumvent this issue do not make getTenant(id); call from init method. Instead make it from the success handler of the getCompany XHR call.
xmlhttp.onreadystatechange=function x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
**getTenant(id);**
}
}
Make two different object name instead of one (xmlhttp). Like
in 'getCompany()' function object name is 'xmlhttp'
in 'getTenant()' function changed object name to 'xmlTalenthttp' (or any other name which you wish)
How come when I populate my textbox with what's in xmlhttp.responseText tags are shown? It shows
<!DOCTYPE html><html><body></body></html>
as well as what I want it to show. Is there a way to make it so that the tags aren't shown? The Javascript and AJAX code is as follows:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("textbox").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
ADDED-Code for loadTextBox.php is as follows:
<?php
---placeholder for correct db login info---
$result = $mysql->query(---placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult = $row->column_1;
}
$textboxValue = $queryResult;
echo $textboxValue;
?>
Well, I was unable to reproduce your problem, so I had to improvise slightly to get the same responseText as you. Anyway, this is what I came up with, please let me know if it doesn't work:
var doc = window.document.createElement("doc");
doc.innerHTML = xmlhttp.responseText;
document.getElementById("textbox").value=doc.innerHTML;
Replace your current instance of:
document.getElementById("textbox").value=xmlhttp.responseText;
With that.
I have been searching for almost an hour without finding proper example to fix my problem:
I would like to call a PHP function (it's a simple unlink with the path given from a javascript function that's executed on page load). I am not good at all with AJAX and I would like to understand how to call directly the PHP function, contained in the index.php file, from the javascript code.
Here's what I have in my javascript code snippet:
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.open("GET","/dev/templates/absolu/index.php?s=" + Math.random(),true);
//#unlink(listeImages[i].toString());
You send the function name (in case you will have more functions in the future) and params as get params
var fileToDelete;
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.open("GET","/dev/templates/absolu/index.php?s=" + Math.random()+"&action=delete&file="+fileToDelete,true);
On your PHP script, you should handle it:
<?php
if (isset($_GET['action'])){
switch($_GET['action']){
case 'delete':
#unlink(listeImages[$_GET['action']].toString());
break;
//Other functions you may call
}
exit;
}
//The rest of your index.php code
?>
You can't call directly a php function from an ajax call, it will only call the php script like if you were opening the page index.php from a browser.
You have to add tests in your php script to know which function has to be called, eg. :
If you call in ajax the page /dev/templates/absolu/index.php?mode=delete_image&image=filename.png
<?php
if($_GET['mode'] == "delete_image") {
unlink($_GET['image']);
}
?>
Please take care that anybody could call this page so you have to check what will be deleted and to verify what you receive in GET parameters. Here i could call /dev/templates/absolu/index.php?mode=delete_image&image=index.php to delete the php script page.
Using jquery (http://jquery.com/) you could make the call as:
$(document).ready(function() {
$.get("/dev/templates/absolu/index.php?", {
'action': 'delete',
'other': 'get-parameters',
'r': Math.random()
});
});
Server side example:
<?php
switch( $_GET['action'] ) {
case 'delete':
// call unlink here
break;
case 'dosomething':
// else
break;
default:
// Invalid request
break;
}
Please note that deleting files should be handled responsibly (enforce security checks) to make sure no wrong file gets accidentally or on purpose deleted.
Well, i have an select list in my php page and i want to refresh only that with new data from my database.Idone it using ajax but on android or other mobiles OSes this messes up the layout.Is there a problem with protable OSes and ajax?Can you give me any hints to solve this problem?
Edited
/*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)
{
var sel1 = document.getElementById("select1");
var selectedI = sel1.selectedIndex;
var i=0;
var excode = excur[selectedI];
var val = sel1.options[selectedI];
excursioncode=excode;
excindex = selectedI;
val.innerHTML = xmlhttp.responseText;
//alert(xmlhttp.responseText);
//setTimeout("loadXMLDoc();",10000);
}
}
xmlhttp.open("POST","<?php echo SITE_ROOT;?>ajaxphp/ajax_get_seats.php?excode="+excursioncode+"&date="+selected_date,true);
xmlhttp.send();
}
function timedRefresh(timeoutPeriod) {
tm=setTimeout("loadXMLDoc();",timeoutPeriod);
}
*/
This is some code that is doing the job.On a regular pc is working but on a mobile browser brings up problems.Anyu ideas
If the problem were with the AJAX, it would not be causing layout issues. Instead the problem is most likely with your implementation of using the data retrieved by AJAX. However, I can't provide any more insights because I have no clue what you're working on and have never experienced such a problem.
This is my first time using AJAX, and I'm trying to send JS variables to a PHP script. I've got an XMLHttpRequest but it doesn't seem complete - what am I missing?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
else {
document.write("Geolocation is required for this page.");
}
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
// document.write("<a href='http://api.geonames.org/findNearbyPlaceNameJSON?lat="+lat+"&lng="+lng+"&username=sebastiano'>my town</a>");
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.open("GET","location.php?lat=position.coords.latitude",true);
xmlhttp.send();
// SOMETHING MISSING HERE?
}
function errorFunction(position) {
document.write("Error");
}
It appears that you're not passing the contents of your variable to the open command.
xmlhttp.open("GET","location.php?lat=position.coords.latitude",true);
in this example your lat will contain a string with contents "position.coords.latitude"
instead try
xmlhttp.open("GET","location.php?lat="+position.coords.latitude,true);
Or better yet, use the variables you created at the top of the function and pass both long and lat in.
xmlhttp.open("GET","location.php?lat=" + lat + "&long=" + lng,true);
you are sending it with "position.coords.latitude" as value...
try xmlhttp.open("GET","location.php?lat=" + position.coords.latitude,true);
Also, take a look at jQuery
Try this:
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){
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET","location.php?lat=" + position.coords.latitude,true);
xmlhttp.send();