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
Related
I have blob:http://unifiedmain.localhost.com/a4580f39-8f9d-4e8c-8e4b-02a6bd2df3df url and i want to create actual file file from this.
I've used
PHP code :
file_put_contents('E:\www\nginx\html\unifinedmainsite\123.mp3', file_get_contents($_REQUEST['id']));.
javascript code:
var xhr = new XMLHttpRequest;
xhr.responseType = 'blob';
xhr.onload = function() {
var recoveredBlob = xhr.response;
var reader = new FileReader;
reader.onload = function() {
jQuery.ajax({
type: "POST",
url: BASEURL+"/index.php?saveFileInSession=true",
data: "id="+reader.result,
success: function(response) {
console.log(response);
}
});
};
reader.readAsDataURL(recoveredBlob);
};
xhr.open('GET', 'blob:http://unifiedmain.localhost.com/a4580f39-8f9d-4e8c-8e4b-02a6bd2df3df');
xhr.send();
file is generating with actual size but i can not open it ,what is i am doing wrong?
Do i have to pass some header or something?so that i can play my saved/uploaded .mp3 file?
please help.
What is the best way to display or deal with a large result on success while waiting for PHPto render that result. I would like to use jQuery to submit a form, have PHP process it, and give output/feedback to users while they wait (either in a div or an iframe...in the example below I use an iframe).
I have the backbone of the xhr version that I found online, but I was wondering if there is a better way (I am aware that there is jquery mixed into this:
function submitForm(){
$('#report_iframe').attr('src','/tests/stream_ajax/blank_iframe.php');
$("#report_modal").modal({backdrop: "static"});
count=1;
xhr = new XMLHttpRequest();
xhr.open("GET", "/folder/ajax_result.php", true);
xhr.onprogress = function(e) {
count = count +1;
$( "#report_iframe" ).contents().find( "#content_loader" ).text('this is jquery count' + count);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
//console.log("Complete = " + xhr.responseText);
// alert("complete");
document.getElementById("report_iframe").srcdoc=xhr.responseText;
}
}
xhr.send();
};
Any help appreciated. Thanks.
J Doyle
Anyway you are using JQuery. Why don't you use JQuery ajax ?
$.ajax({
cache: false,
async: true,
type: "GET",
url: '/folder/ajax_result.php',
beforeSend:function()
{
count = count +1;
},
success:function(response)
{
document.getElementById("report_iframe").srcdoc=response;
}
});
I agree with #Nandan, you should use JQuery Ajax, now for the part of the progress feedback you should add an EventListener for the xhr object and display it in your frame, it would be something like this:
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Download progress
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var count = evt.loaded / evt.total;
$("#content_loader").html('this is jquery count ' + count*100);
}
}, false);
return xhr;
},
type: 'GET',
url: "/folder/ajax_result.php",
data: {},
success: function(data){
//Do something
}
});
For a better explanation and more information:
Click here
Or here
UPDATE:
You could also try something like this, it works well for download progress
$.ajax({
type: 'GET',
url: "/folder/ajax_result.php",
data: {},
xhrFields: {
onprogress: function (e) {
if (e.lengthComputable) {
$("#content_loader").text("this is jquery count " + e.loaded / e.total * 100 + "%");
}
}
},
success: function(data){
//Do something
}
});
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'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
}
}
}
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.