xhr return value from a php page - php

Ok guys im a bit stuck here. I usually use jquery to do this but i found out it cant be done with jquery so im doing it this way ok so this is my code
var url = ("upload.php?loc="+uplocation);
var xhr = new XMLHttpRequest();
if(xhr.upload){ // check if upload property exists
xhr.open("POST", url, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
And all it does is sends a file to a php page, but the php page doesn't upload the image which isn't what i want, so is their anyway of returning all the contents thats displayed on the page
if it was jquery i would do something like this
$.ajax({
type: "POST",
url: 'json/submitsongs.php',
data: loca,
success: function(data){
alert(data);
}
});
so my question is how to do return what ever is echoed on the php page and alert it(for debugging reasons).
thanks for your help

You would add an event listener for whatever event you desired (load, error, progress, etc). So in your case you would use the 'load' event which signifies that the file has finished loading:
xhr.addEventListener('load', onComplete, false);
The onComplete is your callback function which has the event as a parameter. This event contains the response text:
function onComplete(event) {
alert(event.target.responseText);
}

As of today, u can not upload async using Ajax.
Either use Iframes (like Google) or some nifty Flash (or Java) upload app.
Not sure, but might be HTML5 has a solution for that, but it won't be cross browser.

Related

PHP: Assigning an AJAX response value into PHP Variable

I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing

Passing data using $.ajax to PHP leaves $_POST empty [duplicate]

This question already has an answer here:
Wordpress: call to plugin php file via ajax
(1 answer)
Closed 6 years ago.
So I'm making a Wordpress site and want to send data (css styles dynamically created by jQuery) to PHP. The reason for this (not fully relevant to this question) is to write the data as a .css file that is loaded at the beginning of every page--making it so there's no visible 'change' of styles when js executes (well, only the first time the page is loaded). I'm sure there's probably a better way to do this.
But back to the main part (sending data from jQuery to a .php). I'm executing a js script (on "front-page.php") that does this:
jQuery(function($){
$(window).on("load", function() {
$.ajax({
type: "POST",
url: "create-style.php",
data: { style : styleString },
dataType: "json",
success: function () {
console.log("success");
}
});
});
});
The console says 'success', so I assume data is getting passed to create-style.php.
create-style.php's write function does this
$file = 'new-style.css';
$style = $_POST['style'];
file_put_contents($file, $style, LOCK_EX);
Now the first thing I tried was having the function included in Wordpress's functions.php. I don't know a lot about Wordpress or web development in general, but it seems intuitive that this wouldn't work since probably the php files get executed before the js (so how could it get the data?)
In an attempt to solve this I rewrite the create-style.php as a cron using wp_schedule_single_event to fire when someone visits the site, with a slight delay:
add_action('write_style_cron', function(){
// the above writing function
});
wp_schedule_single_event(time() + 10, 'write_style_cron'); // give it a slight delay to make sure jQuery happens
However, no $_POST data gets written to the file and doing any tests shows it's empty. I've done a lot of tests and know that:
cron functionality is basically working
the writing function works with test values
$_POST is showing as completely empty and I get an "Undefined index" error in the /wp-cron.php?doing_wp_cron
$.ajax is firing success
there are no other php / js errors
Thanks for reading this very long post. Been searching the internet all day for solutions and decided it might be best to just ask. I'd much appreciate any ideas.
Try using this code:
jQuery(function(){
$('#yourFormName').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'create-style.php', //URL of page where to pass values
data: $('#yourFormName').serialize(), //seriallize is passing all inputs values of form
success: function(){
console.log("success");
},
});
}
});

sending data from Javascript to remote php

I am modifying a script to make up a firefox extension for my website. The original script ( chrome extension) stores data into a local websql database. I want it rather to send the three variable to a php file using this format
http://mysite.com/receiver.php?id=href&&title=hostname&&article=article&&article=title
The part of Js that is normally sending the data is the following
// post credentials to background
chrome.extension.sendRequest({
action: 'queryDatabase',
crud: 'create',
record: [
window.location.href,
window.location.hostname,
title,
article
]
});
I would be glad if any one can lead me through the modification of this code
You can use jQuery's ajax() method to accomplish this:
// post credentials to http://mysite.com/receiver.php
jQuery.ajax({
url: "http://mysite.com/receiver.php",
type: 'GET',
data: {
id: "href",
title: "hostname",
article: "article"
}
}).success(function ( data ) {
alert("completed successfully");
}).error(function ( data ) {
alert("there was an error");
});
http://api.jquery.com/jQuery.ajax/
example of the image/PHP solution. The jQuery Ajax solution listed is good if you need to know what was returned (I use it on things like http://jsErrLog.appspot.com and it's a great solution), the image is good if you just want to throw something over the fence and move on. Both as non-blocking
in the HTML page the Javascript would need to trigger a call that requests an image:
<script>
databaseImage = new Image();
databaseImage.src = "http://mysite.com/receiver.php?id=href&&title=hostname&&article=article&&article=title";
</script>
and the PHP page that it calls would, after storing the data, would need to return an image (cleaner than sending back something inappropriate) -
<?
$im = file_get_contents('{path to your 1px .gif}');
header('content-type: image/gif');
echo $im;
?>

Reading from a MYSQL table every 5 seconds and dynamically displaying results on a PHP page without refreshing

I'm looking to display data from a table in a mysql database using PHP, however, I want the data to automatically update itself and retrieve current values every 5 seconds.. WITHOUT having to refresh the page. Is this possible? Maybe with JQuery/ AJAX? If so, please explain how it can be done / point me to a resource where I can find such information
Thanks
If you use window.setInterval() and jQuery's .load() you should be able to do what you want. The PHP script should return the HTML that needs to replace the previous one.
Javascript:
function refreshData()
{
// Load the content of "path/to/script.php" into an element with ID "#container".
$('#container').load('path/to/script.php');
}
// Execute every 5 seconds
window.setInterval(refreshData, 5000);
A really basic example:
function poll(){
$.ajax({
type: "GET",
url: "your/php/script/",
success: function(data){
// do something with data
}
});
};
setInterval(poll, 5000);
jQuery is a good option. Here are the docs for ajax.
You will want to make this call with setInterval
Something like this might get your started.
setIntervla(updateFromDb,5000);
function updateFromDb(){
$.ajax({
url: "getUpdates.php",
success: function(){
$(this).addClass("done");
}
});
};
What you are describing is exactly the type of the AJAX is used for, AJAX allows for asynchronous requests to be made to your server.
For learning I would suggest using a framework like Jquery and look into the AJAX api.
Basicly you will need a PHP script that query the database and responds the results the way you want them. A suggestion would be to JSON encode them.
In JavaScript on the client you will need to you things like:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "yourpage.php",
success: function(data){
//HANDLE DATA
// use JSON.parse(data); if your JSON encoding your data
}
});
},5000)
Just go to the documentation of jQuery:
http://api.jquery.com/category/ajax/
Use the command "jQuery.get()" or better "jQuery.getJson()" to make a http request to the server. Use JSON to get a better communication between server and client. Return from server side a json string and convert this on the client to an javascript object. (the function jQuery.getJson already do this for you) so you can easily access the key and values in the data array.
Just an example:
SERVER Part with PHP:
<?
$data = array('key'=>'value');
return json_encode($data, true);
CLIENT Part:
$.getJSON('myurl.php', function(data) {
// THIS ONE IS CALLED with your PHP data
alert(data.key);
});
$(function(){
window.setInterval(function(){
$.post("filename.php",{'field1':field1,'field2':field2,'field3':field3},function(data){
//callbackfunction(data)
})
},30000);//millisecs
});
And have your php file do all your sql

Why isn't this Jquery Ajax working in Opera and Safari?

This code works in FF, Chrome, IE6/8 but not in Safari and Opera.
Any ideas why?
Here is the code:
var name = $('#esm').val();
var email = $('#nam').val();
var message = $('#med').val();
var ad_id = $('#i_d').val();
var data_string = 'esm='+ name + '&nam=' + email + '&med=' + message + '&i_d=' + ad_id;
$.ajax({
type: "POST",
url: "/my_php_file.php",
data: data_string,
success: function(data) {
$('#tip_loader').hide();
if(data==1){alert('success'); }
else {alert('error'); }
}//end success function
}) //end ajax call
I have located the error to exactly the "Ajax" call, because when I put an alertbox just before the $.ajax the alert shows up correctly.
However, if I put the alertbox in the success function, nothing shows up, no alert.
This only happens in Opera and Safari...
EDIT:
FYI: I include this javascript file into a php file, and I also include the jquery.js file into the php file. So this is all in an external file.
EDIT:
/main.php
/bin/jquery.js
/bin/tip.js
/bin/tip.php
I include the above js files into main.php, and the form action in main.php is set to /bin/tip.php
And the path to the ajax url is /bin/tip.php instead of my_php_file.php
In Opera, by default Allow File XMLHttpRequest is false. So you need to change the settings. Open Opera browser, type about:config. It will take you to the Preference screen. Go to User Prefs folder, you can see a settings Allow File XMLHttpRequest. Check that and then Save. It should work.
Opera has a debugging tool built in called Dragonfly. Go to the Tools menu -> Advanced ->Opera Dragonfly
If you don't have the File menu bar, click Menu -> Page -> Developer Tools -> Open Opera Dragonfly
Once you have it open (open it on the page that you're working on), click the Scripts tab (it'll probably ask you to refresh the page, do that) and drop down to your external js file.
Once you've found your code, you can set a breakpoint on the $.ajax() line by clicking on the line number on the left side. Now, trigger your code and you'll see that it will break on that JavaScript line. You can then use the inspection tab (bottom, middle) to ensure that all of your variables are set correctly. You can also step through and debug the JavaScript.
The other thing you'll want to do is add an error function like so:
$.ajax({
type: "POST",
url: "/my_php_file.php",
data: data_string,
success: function(data) {
$('#tip_loader').hide();
if (data == 1) { alert('success'); }
else { alert('error'); }
}, //end success function
error: function(xhr, textStatus, errorThrown) {
alert(errorThrown);
}
}); //end ajax call
See if that gives you any more information.
Also, check the error console as #Mufasa suggested. It can be found under the Error Console tab in Dragonfly.
There isn't really a way to tell. You didn't post the php file. Without knowing the output, we can't determine how the browser will respond.
Other tips though, #1 you are not using encodeURIComponent for any of the values being passed it. Its much more simple to get jQuery to do it for you,
instead of data: data_string, you should have
data: { esm: name, nam: email, med: message, "i_d": ad_id }
jQuery will create the query string for you and correctly.

Categories