Document.ready() function - php

This is my ajax function
<script language="JavaScript" type="text/javascript">
var num = 1;
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "javas.php";
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("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send("num=" + (++num)); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
Now i have this too find the correct div/class to run the ajax function in:
$('.eventcontainer.button').click(function() {
$.post('javas.php', function(data) {
$(this).parent('div').find('.status').html(data);
})
});
However im not sure where to implement this in my code

It's not a good idea to write your own ajax-request if you want to run your code on multiple browsers. If you have jQuery on your hand and you want a post ajax-request use the jQuery function:
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});

example for document ready to use:
function fooBar() {
//some code
}
$(document).ready(function(){
// all your jquery in here
$('body').hide().fadeIn(2000);
// or call your own functions
fooBar();
});

You can use this:
$(function(){
$('.eventcontainer.button').click(function() {
$.post('javas.php', function(data) {
$(this).parent('div').find('.status').html(data);
})
});
})

Related

XHR Request with FormData is POSTing an empty array,

I am working on my own version of this.
Everything works, except the POSTed values are empty. var_dump on the PHP side shows an empty array. What's wrong?
function readfiles(files)
{
console.log('Reading Files...');
console.log(files);
console.log("There are " + files.length + " elements to this array.");
var formData = new FormData();
formData.append('file', files[0]);
console.log(formData);
console.log("Posting XHR request...");
// now post a new XHR request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/devnull.php',false);
console.log("sending data...");
console.log(formData);
xhr.send(formData);
}
$(document).ready(function(e) {
$("#holder").on('dragenter',function(e) {
e.preventDefault();
$(this).addClass('hover');
});
$("#holder").on('dragleave',function(e) {
e.preventDefault();
$(this).removeClass('hover');
});
$("#holder").on('dragover',function(e) {
e.preventDefault();
if(!($("#holder").hasClass('hover')))
$("#holder").addClass('hover');
});
$("#holder").on('drop',function(e) {
e.preventDefault();
console.log(e.originalEvent.dataTransfer.files);
$(this).removeClass('hover');
readfiles(e.originalEvent.dataTransfer.files)
return false;
});
});
Firebug tells me that there is an element in the array:
FileList { 0=File, length=1, item=item(), more...}
But after we append it to the FormData object, I get this:
FormData { append=append()}
And the final var_dump on the PHP side says this:
<pre>array(0) {
}
</pre>
use this code to dispaly file data
<?php var_dump($_FILES);?>

How to load a PHP page into a div with jQuery and AJAX?

I am trying to write a function that will call getproduct.php?id=xxx when clicked. I can get the innerHTML portion to appear, but how do I also call the php page that actually does the work?
var id = id;
document.getElementById("digital_download").innerHTML =
"Downloading...Please be patient. The process can take a few minutes.";
url = getproduct.php?id=id;
you can call or load php page inside a div using this line as :-
$("#content_div").load("ajax/page_url.php");
the "ajax/page_url.php" its a relative path of php file.
so here you can replace it with external url as well.
please share you knowledge if i am wrong.
You can do it with jQuery for example.
var id = 1;
$('#digital_download').html('Downloading...'); // Show "Downloading..."
// Do an ajax request
$.ajax({
url: "getproduct.php?id="+id
}).done(function(data) { // data what is sent back by the php page
$('#digital_download').html(data); // display data
});
There are many ways by which you can load a page into a division .
The very method is
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('digital_download').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", 'getproduct.php?id=' + id,true);
xmlhttp.send();
}
this is a typical method with no external reference.
If you go with reference then there are 5 ways to make a ajax call with jQuery
load(): Load a piece of html into a container DOM.
jQuery.getJSON(): Load a JSON with GET method.
jQuery.getScript(): Load a JavaScript.
jQuery.get(): Use this if you want to make a GET call and play extensively with the response.
jQuery.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
jQuery.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the
fly.
Edit: the original question didn't reference jQuery. Leaving this answer here as others may find it useful.
Here's how you would do this using the XHR object for an ajax request without jQuery or Prototype or other JS library.
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('digital_download').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", 'getproduct.php?id=' + id,true);
xmlhttp.send();
}
Hi You can call the below function to perform this it loads the data from server on success you can create fail function as well
function setValue(Id) {
document.getElementById("digital_download").innerHTML =
"Downloading...Please be patient. The process can take a few minutes.";
var data1 = {
message: Id,
};
$.ajax({
data: data1,
type: 'GET',
url: "http://urltoscript/index.php",
cache: false,
dataType: "json",
crossDomain: true,
success: function(data) {
console.log("Response for cancel is: " + data);
document.getElementById("digital_download").innerHTML = data
}
});
}
You can use get or post request using query
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
example

$_REQUEST var is empty from post send

I'm doing a ajax function for wp. But i get always the response 0. I see the code of the file admin-ajax.php and see this:
if ( empty( $_REQUEST['action'] ) )
die( '0' );
This is my js function ajax.
function fnc(){
var ajax=new XMLHttpRequest();
ajax.open("POST", "<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php");
ajax.onreadystatechange= function(){
if (ajax.readyState === 4) {
if (ajax.status === 200) {
alert(ajax.responseType);
alert(ajax.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
ajax.send("action=some_function");
}
In order to have the send string be used as form data, you will probably need to add the following header:
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Without this, PHP will not turn the raw POST data into $_POST/$_REQUEST variables.
$.ajax({
type:'POST',
url:"<?php echo get_site_url(); ?>/wp-admin/admin-ajax.php",
data:'', // what you want to post
success:function(data){
alert(data);
});
}
});
}
try this
If you want to use javascript and XMLHttpRequest this is the full way to do that :)
function ajax_post(){
// Create our XMLHttpRequest object
var ajax=new XMLHttpRequest();
// Create data to send to our PHP file
var url = "xyz.php";
var fn = document.getElementById("a").value;
var ln = document.getElementById("b").value;
var variable = fn+" hello "+ln;
hr.open("POST", url, true);
// Set content type header for sending url encoded variables
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Get the onreadystatechange event for the XMLHttpRequest
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
var return_data = ajax.responseText;
alert(ajax.return_data);
// Send the data to PHP now... and wait for response to update the status div
ajax.send(variable); // Actually execute the request
}
}
}

How to pass value from AJAX Javascript to PHP file

I want to pass value from AJAX file to PHP using below script, but it fail. What is the correct way to do this? Thanks
Sample code as below:
function createNewWindow()
{
var newWindowModel = new DHTMLSuite.windowModel({windowsTheme:true,id:'newWindow1',title:'Response Time to Invitation',xPos:130,yPos:400,minWidth:100,minHeight:100 } );
newWindowModel.addTab({ id:'myTab1',htmlElementId:'myTab1',tabTitle:'TAB',textContent:'Send data', contentUrl:'load.php?loadNo:loadNo' } );
var newWindowWidget = new DHTMLSuite.windowWidget(newWindowModel);
newWindowWidget.init();
}
Passing values? you mean parameters? if yes:
Create an AJAX obj first: var http = new XMLHttpRequest();
The GET method:
var url = "load.php";
var params = "loadNo=loadNo&param=value";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
The POST method:
var url = "laod.php";
var params = "loadNo=loadNo&param=value";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
Simple and easy way to do a AJAX Request using Jquery
var request = $.ajax({
url: "script.php", // script path goes here
type: "GET",
data: {id : param}, // Parameters go here
dataType: "html"
});
request.done(function(msg) {
$("#log").html( msg ); // On success
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus ); // On failure
});
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x=xmlhttp.responseText;
alert(x);
}
}
}
xmlhttp.open("GET","load.php?loadNo="+loadNo+"&param="+value,true);
xmlhttp.send();

Firing a script on click?

Say I have a URL:
hello
When someone clicks this link, I want it to fire a script off using ajax so we can track how many times this link has been clicked behind the scene.
My page is called track.php which will pull the ID 4298 via GET, track.php?id=4298 and then it updates the database respectively.
How would I go about coding this in javascript/ajax so upon this link being clicked, in form of an "onclick event", this track.php will be ran behind the scene?
Keep in mind that to do a request in the background, you will need to wait for the AJAX response to follow the click. If that's what you want, then using jQuery:
<script type="text/javascript">
var track = function(obj) {
$.ajax({
url: "track.php?id="+obj.id,
success: function(){
window.location.href = obj.href;
}
});
return false;
};
$('a').click(track);
</script>
<script>
window.doTheThing = function() {
//send a request to your 'track.php' URL here
};
</script>
hello
var anchors = document.body.getElementsByTagName('a');
for (var i = 0, anchorsLength = anchors.length; i < anchorsLength; i++) {
a.onclick = function(event) {
event.preventDefault();
var id = this.id,
xhr = new XMLHttpRequest();
xhr.open('track.php?id=' + id);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if(xhr.status == 200) {
window.location = this.href;
}
}
}
xhr.send();
}
}
Keep in mind that XMLHttpRequest() doesn't support older versions of IE.
If you are using jQuery, use the library's AJAX functions.

Categories