AJAX and php POST problems - php

I am trying to pass to a PHP file cellnumber. My AJAX isn't even working, when I try
alert("test"); in the ajax.onreadystatefunction() it won't print.
My javascript getrow(t) function gets called every time someone clicks on a cell in a table
and the result is the cell turning into green. I want to ultimately enter this data into a postgres table using php.
Thanks for all the help!
Vlad
<script type="text/javascript">
//gets the row and column number
function getRow(t)
{
var col=t.cellIndex;
var row=t.parentNode.rowIndex;
var testTable = document.getElementById("testTable");
t.style.backgroundColor = "#33CC66";
var cellnumber = (row*15 + col);
var ajax = new XMLHttpRequest();
//use ajax to enter into visitedCells
ajax.onreadystatechange = function()
{
// Call a function when the state changes.
if(ajax.readyState == 4 && ajax.status == 200)
{
ajax.open("POST", insertCoordinates.php, true);
ajax.send(cellnumber);
}
else
{
alert("Error:" + ajax.status + "and " + ajax.statusText);
}
}
}
</script>
</body>
</html>

ajax.open("POST", insertCoordinates.php, true);
ajax.send(cellnumber);
should be outside ajax.onreadystatechange
just befor }//getRow
you actually don't have the request executed
should be like that:
var ajax = new XMLHttpRequest();
//use ajax to enter into visitedCells
ajax.onreadystatechange = function() {//Call a function when the state changes.
if(ajax.readyState == 4 && ajax.status == 200) {
alert('success');
} else {
alert("Error:" + ajax.status + "and " + ajax.statusText);
}
}//onreadyState
ajax.open("POST", insertCoordinates.php, true);
ajax.send(cellnumber);
probably won't work in IE
should use a construction like that:
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
but the best way is to use jQuery ...easy and safe

Related

Adding video to playlist with Youtube API

I successfully added a video to a playlist but it is added multiple times (sometimes twice and sometimes more). Can anybody help?
$resourceId = new Google_Service_YouTube_ResourceId();
$resourceId->setVideoId($videoID);
$resourceId->setKind('youtube#video');
$playlistItemSnippet = new Google_Service_YouTube_PlaylistItemSnippet();
$playlistItemSnippet->setPlaylistId($playlistId);
$playlistItemSnippet->setResourceId($resourceId);
$playlistItem = new Google_Service_YouTube_PlaylistItem();
$playlistItem->setSnippet($playlistItemSnippet);
$playlistItemResponse = $youtube->playlistItems->insert('snippet,contentDetails', $playlistItem, array());
Solved it myself and I'm pretty proud of it :)
I realised that the ajax was triggering the above php script on mouseover. So every time I hovered away from the checkbox element the php script triggered multiple times.
I changed the mouseover code with the following:
$(function() {
$('input.Chilltrap').on('click', function(e) {
var chilltrap = this.id;
if( $("input[name=" + chilltrap + "]").prop('checked') ) {
checkboxstatusCt = "Yes";
}
else {
checkboxstatusCt = "No";
}
var url = "url.php";
var params = "c="+checkboxstatusCt+"&s="+chilltrap;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#error").html(xmlhttp.responseText);
$("#error"). fadeIn('fast');
setTimeout(function(){
$("#error"). fadeOut('slow');
},2000);
}
};
xmlhttp.open("GET", url+"?"+params,true);
xmlhttp.send();
});
});

Button calls ajax function multiple

Quick notes. I am not using jQuery so don't suggest it.
When pressing the button which has the onclick="ajaxfunction();" i get an alert saying "Error during AJAX call. Please try again " and then I get the alert saying success, twice :S ... Why is this happening?
I don't understand why this is happening, as it calls the error, and then goes to the other part of the if statement...
Thanks in advance!
<script>
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
var url="insertProduct.php";
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var name = document.getElementById("name");
var code = document.getElementById("code");
xmlhttp.open("POST",url,true); //calling insertProduct.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("name=" + encodeURIComponent(name.value) + "&code=" + encodeURIComponent(code.value)); //Posting to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4 || xmlhttp.readyState=="complete") {
alert("Success");
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again " + xmlhttp.status);
}
}
</script>
After finishing the task you can call return;
Likes below.
function handleServerResponse() {
if (xmlhttp.readyState == 4 || xmlhttp.readyState=="complete") {
alert("Success");
document.getElementById("message").innerHTML=xmlhttp.responseText;
return;
}
else {
alert("Error during AJAX call. Please try again " + xmlhttp.status);
return;
}
}
I hope this will help to you.

Ajax / PHP updating DIV

I'm using the following to update a DIV called 'output'. This works fine with one exception, I would like echo entries to update the parent page.
<script type="text/javascript">
<!--
var divid = 'output';
var loadingmessage = '<img src="working.gif">';
function AJAX(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function formget(f, url) {
var poststr = getFormValues(f);
postData(url, poststr);
}
function postData(url, parameters){
var xmlHttp = AJAX();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState > 0 && xmlHttp.readyState < 4){
document.getElementById(divid).innerHTML=loadingmessage;
}
if (xmlHttp.readyState == 4) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(parameters);
}
function getFormValues(fobj)
{
var str = "";
var valueArr = null;
var val = "";
var cmd = "";
for(var i = 0;i < fobj.elements.length;i++)
{
switch(fobj.elements[i].type)
{
case "select-one":
str += fobj.elements[i].name +
"=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&amp;";
break;
}
}
str = str.substr(0,(str.length - 1));
return str;
}
//--></script>
This is called using :
<input type='button' name='Send' value='submit' onclick="javascript: formget(this.form, 'foo.php');">
The issue I have is foo.php runs a series of exec() commands, between each command is an echo statement that I would like to be displayed in the output div.
So it will do something like:
echo "archive files";
exec ("tar -cvf bar.tar bar.txt foo.txt");
echo "backing up /user";
exec ("tar -cvf /user.tar /user/*");
I would like the user to see the working.gif, but under it each echo statement from foo.php
Can that be done and how ?
Thanks
I can't say I've ever tried sending back chunks of data at separate times with a single AJAX request, so I'm not sure it's possible. What happens currently? Do you only get first echoed message, or do only get the entire response at the end?
Two things that I know will work:
Break your PHP script into multiple scripts and execute them in order with separate AJAX requests. This will only work if the separated scripts don't depend on each other or you find some other way to persist the state across the separated scripts.
Create an iframe and load the PHP script into it instead of using an AJAX request. Flushing the output of the PHP script should then work. (If you have ever used Wordpress, I believe they use this technique to show the progress of plugin updates.)

while retreving the data using ajax getting an error message

I posting my value through ajax and using the response the details will be displayed.I am getting the problem while retreiving the data.But i dono where i have mistaked,then this is the error getiing displayed frequently
"There was a problem while using XMLHTTP:\n";
in all browsers mainly in the chrome,could any one help me...
this is my code,
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer 6+
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// Internet Eplorer 5
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX. Download a newer browser to view this page.");
return false;
}
}
}
// insert server response into HTML element
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
MM_check_session(xmlHttp.responseText);
var b_gc = document.getElementById(insert).value;
document.getElementById(insert).value = xmlHttp.responseText;
var shippingid = getCheckedValue('checkout_form', 'shippingid');
closeMessage();
MM_calc_shipping(shippingid);
if (b_gc == xmlHttp.responseText) {
MM_register();
} else {
error = 1;
document.getElementById('payment_error').innerHTML = xmlHttp.responseText;
document.getElementById(insert).value = '';
}
} else {
closeMessage();
alert("We can't process your request.Please refresh(reload) the page to proceed further:\n"
+ xmlHttp.statusText);
}
}
}
displayStaticMessage(
'<img src=' + config_MM_loader_image_path + ' alt=\'loading...Please wait\'>',
false);
xmlHttp.open("POST", serverScript, true);
xmlHttp.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xmlHttp.setRequestHeader('Content-length', parameters.length);
xmlHttp.setRequestHeader('Connection', 'close');
xmlHttp.send(parameters);
any help
You seem to be incorrectly tagged as php. Also have you considered jQuery for the ease of ajax whilst using it.
as for your question could you post the code on the page where the ajax request is going to as the code here looks fine..
Edit:
Where is serverScript set?
change serverScript for the ajax page you are calling?
http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849%28v=vs.85%29.aspx

How do I get these two functions to work with Ajax, and how to I rewrite it in Jquery?

function ajaxFunction(phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.subCat').html(ajaxRequest.responseText);
$('.subCat').ready(function(){
$('.subCat').fadeIn();
});
}
}
var url = "products.php?func=" + phpFunction;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
This function works great, and has no problems. But if I add:
function refreshProduct(idNum, phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.' + idNum).empty();
$('.' + idNum).html(ajaxRequest.responseText);
});
}
}
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
When I try to execute ajaxFunction('returnAllProducts') I get:
syntax error
});\n
from
$('.' + idNum).html(ajaxRequest.responseText);
}); <<<----
and
ajaxFunction is not defined
javascript:ajaxFunction('returnAllProducts')()
So my questions are:
a) how do I convert this over to jquery? I've read over some jquery ajax tutorials, but I wasn't able to make the connection how to do what I am doing here.
b) How do I get both functions to work? I know the PHP behind them works fine, but I can't even test if refreshProduct() works properly right now.
You seem to be missing a }
this is your code, properly indented...
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.'idNum).empty();
$('.'idNum).html(ajaxRequest.responseText);
});
When it should be
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.'idNum).empty();
$('.'idNum).html(ajaxRequest.responseText);
}
});
Also, the two } after this should be deleted, rendering your code like this:
function refreshProduct(idNum, phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.' + idNum).empty();
$('.' + idNum).html(ajaxRequest.responseText);
}
});
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
As for rewriting this using jQuery, it's really easy:
function ajaxFunction(phpFunction){
var url = "products.php?func=" + phpFunction;
$.get(url, function(data) {
$('.subCat').html(data).ready(function(){
$('.subCat').fadeIn();
});
});
}
function refreshProduct(idNum, phpFunction){
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
$.get(url, function(data) {
$('.' + idNum).empty().html(data);
});
}

Categories