AJAX Call not returning data - php

Can someone tell me why the div called tellme is showing only showing something for half a second.. or less and then just doing nothing? I have tried everything and just can't get the code to work. It is funny because I have the exact same code on my other page and it works with no problems what so ever, I am trying to call an AJAX call and it is just not working and its not making the div called tellme anything, it's just keeping it blank...
<script type="text/javascript">
function fireWorkerFixed(userid)
{
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "http://private.com/fire_worker.php";
var id = userid;
var vars = "userid="+id;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById('tellme').innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById('tellme').innerHTML = "<div class='alert alert-info'>Please wait, Processing request...</div>";
}
</script>

Related

JQuery Ajax Calls -- Intermittent image display issues (Chrome & FF) (some PHP and MySQL)

I use JQuery to pull form data and send an XMLHttpRequest(); I open the request using the POST method. The image and supplementary data are passed to a PHP script that handles, resizes, and saves it to the server. The file name and location of the image are updated in the relevant fields in a MySQL database. On the uploadComplete(evt) I attempt to display the newly uploaded image by calling .load() to populate a div.
80% of the time, the image displays correctly when the content is loaded into the div. 20% of the time, the image is displayed as if the link provided were a broken link. However, if I refresh the page, the image is displayed correctly.
Why does the image sometimes show as a broken link?
How do I stop it from doing this?
* EDIT
function loadFile()
{
var fileURL = $( "#url" ).val();
if(fileURL == "")
{
// Retrieve the FileList object from the referenced element ID
var myFileList = document.getElementById('upload_file').files;
// Grab the first File Object from the FileList
var myFile = myFileList[0];
// Set some variables containing the three attributes of the file
var myFileName = myFile.name;
var myFileSize = myFile.size;
var myFileType = myFile.type;
// Let's upload the complete file object
imageUpdate(myFile);
}
else
{
var newinfo = new Array();
newinfo[0] = "URL";
newinfo[1] = fileURL;
imageUpdate(newinfo);
}
}
function imageUpdate(newinfo)
{
var formData = new FormData(); // data object
// extra
var stylistID = $( "#editThisStylist" ).data('stylistid'); // Grab stlyistID
formData.append("stylistID", stylistID);
// IF URL
if ( newinfo[0] == "URL" ){
formData.append("type", "URL");
formData.append("url", newinfo[1]);
}
// IF LOCAL FILE
else
{
formData.append("type", "FILE");
// Append our file to the formData object
// Notice the first argument "file" and keep it in mind
formData.append('my_uploaded_file', newinfo);
}
// Create our XMLHttpRequest Object
var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
// Open our connection using the POST method
xhr.open("POST", "u/stylist_avatar.php", true);
// Request headers
//xhr.setRequestHeader("Content-Type", formData.files[0].type);
// Send the file
xhr.send(formData);
}
// While xhr is in progress
function updateProgress(oEvent)
{
if (evt.lengthComputable)
{
//var progressBar = document.getElementById("progressBar");
//var percentComplete = oEvent.loaded / oEvent.total;
//progressBar.value = percentComplete;
}
else
{
// unable to compute progress information since the total size is unkown
}
}
// onComplete
function uploadComplete(evt) {
//alert("The transfer is complete.");
resetForm($('#uploadImageForm'));
var stylistID = $( "#editThisStylist" ).data('stylistid'); // Grab stlyistID
$('#uploadImageModal').modal('toggle');
// Reload right div
$( "#editStylistRight" ).load( "u/stylist_lookup.php", {stylistID: stylistID}, function (){});
// Reload stylist list
var index = 0;
var numRecords = 10;
$( "#stylistTable" ).load( "u/stylist_lookuptable.php", {start: index, end: numRecords}, function (){});
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
It seems that you are trying to show the new image before the PHP script in fact create and save the new image.
Instead of calling the javascript function that loads the new image on the "uploadComplete", use the "success" param (if you are using jQuery $.ajax function) that call the function that loads the new image.
The "success" function is called only when the server finish processing the request (when the PHP script finish editing and saving the image) and not when the new image params were succesfully sent to the server.
This happens because of image cache,force browser to fetch image evrytime.
use this in uploadcomplete event
var timestamp = new Date();
timestamp = timestamp.getTime();
imageurl+'?t='+timestamp;

Get / replace contents of div tag using PHP and Ajax

I'm very new to PHP/Ajax/Html so here's my baby problem (I'm making a radio station site),
test.php queries my server for the currently playing song name.
listen.php displays this song name in the 'refreshTitle' div tag.
When my station changes song there is a 30-ish second delay, so what I want to do is get the song title every second and compare / delay the update of the display if the title is different to what is actually being heard, easy peasy right?! Here is listen.php:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if (window.XMLHttpRequest) { // for Firefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var d = new Date();
var t = d.toLocaleTimeString();
var the_data = 'test=' + t;
//append time purely for testing to make sure text updates
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function () {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
setInterval(
function () {
ajaxrequest('test.php', 'refreshTitle')
}, 1000); // refresh every 10000 milliseconds
//This time val should vary based on the song title retrieved during the last second
</script>
And somewhere down the rest of the page I have this:
echo "<div id=\"refreshTitle\" style=\"float:left; padding-top:6px;\">\n";
echo "</div>\n";
In test.php (the file with the song name) I have this:
if (isset($_POST['test'])) {
$str = $_POST['test']; // get data
echo $dnas_data['SONGTITLE'] . " Current time " . $str;
}
So basically every second I send the time to test.php, which echos it and that echo I assume is put into 'refreshTitle' with this line:
document.getElementById(tagID).innerHTML = request.responseText;
What I want to do is get the song title into my javascript in listen.php and only run the ajax request after some string comparison / delay logic.
Sorry for the long-winded description but I'm fairly confused and think I've done this whole thing backwards :) Please let me know any thoughts...
First, I would recommend to you to update your jQuery version (1.3 is kinda old, the current version is 2+).
What's more, AJAX requesting is very well abstracted in jQuery : you can use the load() function to simply load an element content.
Source : http://api.jquery.com/load/

Javascript-Ajax not able to send any data

i am having trouble making this part of code to work, basically i want to call this function which sends a variable to a php page. Ive tested that the variable is there and also tested that my php page is accepting information as it should be , however i cant make this Ajax thing work.
function ajaxRequest(myname) {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest)
{ // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else
{ // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null)
{ // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
AJAX.onreadystatechange = function()
{ // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete")
{ // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
} // End Ajax readystate check.
}
alert("Alert1");
var url='http://localhost/main.php?Name=myname';
AJAX.open("POST", url, true); // Open the url this object was set-up with.
alert("Alert2");
AJAX.send(); // Send the request.
}
This is my php part which should accept the variable
<?php
$var=$_GET['Name'];
echo $var;
?>
Okay firstly you need to change your request to GET from POST
like
AJAX.open("GET", url, true); // Open the url this object was set-up with.
and you also need to update this line
from
var url='http://localhost/main.php?Name=myname';
to
var url='http://localhost/main.php?Name='+myname;
my full script is:
<script type="text/javascript">
function ajaxRequest(myname) {
var AJAX = null; // Initialize the AJAX variable.
if (window.XMLHttpRequest)
{ // Does this browser have an XMLHttpRequest object?
AJAX=new XMLHttpRequest(); // Yes -- initialize it.
} else { // No, try to initialize it IE style
AJAX=new ActiveXObject("Microsoft.XMLHTTP"); // Wheee, ActiveX, how do we format c: again?
} // End setup Ajax.
if (AJAX==null)
{ // If we couldn't initialize Ajax...
alert("Your browser doesn't support AJAX."); // Sorry msg.
return false // Return false, couldn't set up ajax
}
AJAX.onreadystatechange = function()
{ // When the browser has the request info..
if (AJAX.readyState==4 || AJAX.readyState=="complete")
{ // see if the complete flag is set.
callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function
} // End Ajax readystate check.
}
alert("Alert1");
var url='http://localhost/main.php?Name='+myname;
AJAX.open("GET", url, true); // Open the url this object was set-up with.
alert("Alert2");
AJAX.send(); // Send the request.
}
</script>
you might also be missing the callback function so add it so that it looks like this
function callback(x, y) {
alert(x);
}
And call your AJAX function by
ajaxRequest("ashley");
Here is your required main.php code (even though this isn't what you should be using AJAX for
<?php
session_start();
if(isset($_GET["Name"])) {
$_SESSION["Name"] = $_GET["Name"];
}
if(isset($_SESSION["Name"])) {
echo $_SESSION["Name"];
} else {
echo "The AJAX has not been run!";
}
?>
There are two ways to send an ajax request to server
Either GET or POST
1. GET Method:
var url='http://localhost/main.php?Name='+myname; // you can add any numner of vars here
AJAX.open("GET", url, true);
AJAX.send();
Code in main.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_GET['Name'];
}
2. POST Method:
AJAX.open("POST","ajax_test.asp",true);
AJAX.setRequestHeader("Content-type","application/x-www-form-urlencoded");
AJAX.send("Name="+myname);
Code in main.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $_POST['Name'];
}

pass xmlhttp.responseText data to php variable

i have a jquery that brinds text from a page through ajax and displays that text in a div
i want to pass that data to a php variable how can i do that ?
my jquery code is
<script type="text/javascript">
var xmlHttp = null;
window.onload = function() {
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "abc.php", true);
xmlHttp.onreadystatechange = onCallback;
xmlHttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlHttp.send(null);
}
function onCallback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert(xmlHttp.responseText);
document.getElementById('show').innerHTML=xmlHttp.responseText;
}
}
}
</script>
here i want to save xmlhttp.responseTexrt in a php variable in the same file how i can do that ?
Javascript is executed on the browser, and php is executed in the web server. You can not directly pass values from javascript to php.
Therefore, you need to make another ajax call (POST) from javascript to the web server that sends the xmlHttp.responseText, and write php code in the server to store the value to database.
Pass your data in URL,
var data = "somedata";
xmlHttp.open("GET", "abc.php&send=" + data, true);
For Passing a serialized array, first convert it into string
var send = toString(array);
xmlHttp.open("GET", "abc.php" + send, true);
For storing array to PHP variable use $receive = explode(',',$_POST['send']);

Ajax call will not refresh inner html with php function that makes the html - help?

I have the following code generating content on my site:
<div class="content" id="links">
<?php displayTitle("Links"); ?>
<?php displayContent("Links", $isLoggedIn); ?>
</div>
The content has a button that calls a Javascript function 'addLink()' to edit itself. Here is the Javascript with an Ajax call to change the content:
function addLink(){
var ajaxRequest; // The variable that makes Ajax possible!
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}
else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
alert(ajaxRequest.readyState);
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
}
}
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send(null);
}
'addLink.php' adds things to a table, theoretically allowing the content function 'displayContent()' to show the new entries in the table ('displayContent()' queries a table).
The PHP call works fine, but I have to refresh the page to see the changes.
Is there some problem with how I am doing this? Possibly because there are already PHP calls in the inner HTML when the page is loaded in the first place?
Any help is appreciated, I'm a bit of a beginner with Ajax.
ajaxRequest.onreadystatechange = function(){
alert(ajaxRequest.readyState);
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
Sorry a little correction. You are attempting to access the pre-ajax php scripts inside ajax callback function. That's not how it works. You want the data that is retrived after-ajax call. Ajax retrives the output from the GET request, and store in ajaxRequest.responseText. Try replacing that and then see what you get.
In your addLink.php you should add the link and then echo out the data that you wish to display as the responseText. What had happened is that you inject the data VIA addLink but you never actually display it on the client side VIA ajax correctly. However, when you refresh the page, the script retrives what has been injected and display it accordingly.

Categories