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
}
}
}
Related
Hi I am currently trying to save an image on my canvas to my database, but my code uses jQuery of which I am not allowed to. Can someone please help me with an equivalent of this ajax command without using JQuery, here is my code:
document.getElementById('save').addEventListener('click', function()
var canvas = document.getElementById("canvas");
var dataUrl = canvas.toDataURL("image/png");
$.ajax(
{
type: "POST",
url: "../webcam/save_image.php",
data: {image: dataUrl}
})
.done(function(respond){console.log("done: "+respond);})
.fail(function(respond){console.log("fail");})
.always(function(respond){console.log("always");})
});
You can use Native XMLHttpRequest Objects to accomplish this. I believe your code should look something like this, I haven't tested it though, so you will need to tweak it somewhat I'm sure.
document.getElementById('save').addEventListener('click', function()
var canvas = document.getElementById("canvas");
var dataUrl = canvas.toDataURL("image/png"), xhr = new XMLHttpRequest();
xhr.open('POST', '../webcam/save_image.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200 && xhr.responseText !== dataUrl) {
console.log('fail');
}
else if (xhr.status !== 200) {
console.log('fail');
}
};
xhr.send(encodeURI('url=' + dataUrl);
Reference: https://blog.garstasio.com/you-dont-need-jquery/ajax/#posting
Having Following form validation through jQuery:
$("#Login").submit(function( event ) {
var url = 'ajax/';
var data = {};
$("input").each(function() {
data[$(this).attr('name')] = $(this).val();
});
$.post(url,data,function( resp ) {
$("#formLoginErrorMessage").children().remove();
if(resp === " ")
{
console.log("Empty");
return; // The form should submit
} else if (typeof resp === "object") {
console.log(resp);
} else{
$("#formLoginErrorMessage").addClass("alert-danger");
$("#formLoginErrorMessage").append("<li>" + resp + "</li>");
console.log(resp);
}
},'json');
event.preventDefault();
});
This script is checking some errors and when resp is empty form should submit. But return from if where resp is checked doesn't seem to make form submit.
You can call the submit() method in the if condition
$("#Login").submit(function (event) {
var form = this;
var url = 'ajax/';
var data = {};
$('input').each(function () {
data[$(this).attr('name')] = $(this).val();
});
$.post(url, data, function (resp) {
$("#formLoginErrorMessage").children().remove();
if (resp === " ") {
form.submit();
console.log("Empty");
return; // The form should submit
} else if (typeof resp === "object") {
console.log(resp);
} else {
$("#formLoginErrorMessage").addClass("alert-danger");
$("#formLoginErrorMessage").append("<li>" + resp + "</li>");
console.log(resp);
}
}, 'json');
event.preventDefault();
});
What you seem to be confused about are closures
$( "#Login" ).submit(function( event ) {
// main submit handling function starts here
...
$.post(url,data,function(resp){
// inner response handling function starts here
if(resp === " "){
console.log("Empty");
return; //This returns to jQuery internals somewhere inside $.post
} ...
},'json');
// stops form from submitting
event.preventDefault();
});
I added a couple of comments to help you get a better visual of the scope.
First thing first, you should never rely on client-side validation. It can be overtaken without exceptions. If for some reason you insist on having it this way you can use some outer scope variable to determine whether validation has passed or not, but then you have to use $form.submit() instead of return to actually submit the form.
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
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¶m=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¶m=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+"¶m="+value,true);
xmlhttp.send();
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);
})
});
})