How to pass value from AJAX Javascript to PHP file - php

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();

Related

How to rewrite Ajax without using JQuery for my code

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

Calling jQuery in Ajax response

I want to call a jQuery function that acts upon a form in AJAX response.
How do I do it???
jQuery Function
$(document).ready(function (e) {
$("#load_timetable").on('submit',function(e) {
e.preventDefault();
$.ajax({
url: "load_timetable.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#time_table").html(data);
},
error: function() {}
});
});
});
Another AJAX Function
$(document).on("click", ".open-viewFacultyDialog", function () {
var uid = $(this).data('id');
$('#update').click(function() {
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
}
catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4) {
**//I would like to call JQUERY here**
document.getElementById("update_action_response").innerHTML = "";
var ajaxDisplay = document.getElementById('update_action_response');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var dept_slot = document.getElementById('dept_slot').value;
var subject = document.getElementById('subject').value;
var faculty1 = document.getElementById('faculty1').value;
var faculty2 = document.getElementById('faculty2').value;
var faculty3 = document.getElementById('faculty3').value;
var queryString="?id="+uid+"&dept_slot="+dept_slot+"&subject="+subject+"&faculty1="+faculty1+"&faculty2="+faculty2+"&faculty3="+faculty3;
ajaxRequest.open("GET", "update_timetable.php"+queryString, true);
ajaxRequest.send(null);
});
});
In simple I would like to reload the contents after updation without page reload by submitting the same parameters that are used to load the contents before update.
Use Promise method which is already defined in jquery.you can use it if data transfer successfully. such that if promise returns true then perform this task.else other task.

How can I simplify this using jquery?

I have the following function, how can I simplify it using jquery?
function updateCards(){
var form = document.getElementById("sets");
var chks = form.querySelectorAll('input[type="checkbox"]');
var checked = [];
for(var i = 0; i < chks.length; i++){
if(chks[i].checked){
checked.push(chks[i].value)
}
}
// test code
//alert("SELECTED SETS:"+checked);
if (checked == ""){
document.getElementById("all-cards").innerHTML = "";
return;
}
if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("all-cards").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","update_cards.php?sets="+checked, true);
xmlhttp.send();
}
Try
function updateCards(){
var $form = $('#sets'), $chks = $form.find('input:checkbox'), checked ;
checked = $chks.map(function(){
return this.checked ? this.value : undefined;
}).get();
if (checked.length == 0){
$('#all-cards').html('');
return;
}
$.ajax({
url: 'update_cards.php',
type: 'GET',
data: {
sets: checked
},
dataType: 'html'
}).done(function(html){
$('#all-cards').html(html);
})
}
Same function in jQuery can be written like below.
function updateCards() {
var $form = $('#sets'),
$chks = $('input[type="checkbox"]:checked'),
$allCards = $('#all-cards');
var checked = $chks.map(function() {
return this.value
});
if(checked.length === 0) {
$allCards.html('');
return
}
// Ajax
$.ajax({
url : "update_cards.php?sets="+checked,
type: 'get',
dataType: 'html'
}).done(function(data) {
$allCards.html(data);
}).fail(function(xhr, status, error) {
console.log(error);
});
}

$_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
}
}
}

Document.ready() function

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);
})
});
})

Categories