Calling jQuery in Ajax response - php

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.

Related

Passing input file type via ajax to php is not working

I have this function to get values from a form
$("button[name='createimport']").click(function() {
var fd = new FormData();
var files = $('#xsfile')[0].files[0];
fd.append('file',files);
var batchid = $("input[name='batchid']").val();
var yrstart = $("input[name='yrstart']").val();
var yrend = $("input[name='yrend']").val();
$.ajax({
url:"fetch_import.php",
method:"POST",
data: { batchid : batchid, yrstart: yrstart, yrend: yrend, fd},
success: function (data) {
//show success result div
if(data)
{
showSuccess();
}
else
{
showFailure();
}
},
error: function () {
//show failure result div
showFailure();
}
});
});
and a php code like this:
enter code here$bcid = $_POST['batchid'];
$yrs = $_POST['yrstart'];
$yrg = $_POST['yrend'];
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "upload/".$filename;
$FileType = pathinfo($location,PATHINFO_EXTENSION);
move_uploaded_file($_FILES['file']['tmp_name'],$location);
passing the file doesn't work. I've searched for this but still not working for me, i think i'll understand how it will work. Any idea? Tyia
You should append your fields to fd and simply use that as data-parameter in $.ajax:
$("button[name='createimport']").click(function() {
var fd = new FormData();
var files = $('#xsfile')[0].files[0];
fd.append('file',files);
fd.append('batchid', $("input[name='batchid']").val());
fd.append('yrstart', $("input[name='yrstart']").val());
fd.append('yrend', $("input[name='yrend']").val());
$.ajax({
url:"fetch_import.php",
method:"POST",
data: fd,
success: function (data) {
//show success result div
if(data)
{
showSuccess();
}
else
{
showFailure();
}
},
error: function () {
//show failure result div
showFailure();
}
});
});

Ajax post data through name

If I add caption to image it's working, if I add one more caption without refreshing the page the 1st value is posting to the second one...
$(document).ready(function () {
$(".cap_btn").click(function(){
var li = $(this).closest("li");
var cap = $('input[name="cap"]').val();
$.ajax({
type: "POST",
url: "addcap.php",
data: { id: li.data("imageId"), "cap": cap},
success: function(data){
alert("Caption Added");
},
error: function(){
alert("failure");
}
});
});
});
php code:
if(isset($_POST['id'])){
$ids = $_POST['id'];
$cap = $_POST['cap'];
try
{
$query = "UPDATE image SET caption='$cap' WHERE id='$ids'";
$sql=$con->prepare($query);
$sql->execute();
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
You can do it like this
$(document).ready(function () {
$(".cap_btn").click(
function()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
alert("Caption Added");
}
else
{
alert("failure");
}
};
xmlhttp.open("POST", "addcap.php", true);
var formdata = new FormData();
var li = $(this).closest("li");
var cap = $('input[name="cap"]').val();
formdata.append("id",li.data("imageId"));
formdata.append("cap",li.data("cap"));
xmlhttp.send(formdata);
});
});
Hope it helps :)

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 disable submit button on click and re-enable on the response in jquery forms plugin

i want to be able to make the submit button in jquery form plugin disabled and then when the response is retrieved, it should become enable. i am trying thru the code below but as soon as in the onlick event i disabled the button it somehow stops the submission. although i am able to change the class of the button.
what am i doing wrong?
code is like this:
function timing(){
d=Math.round(new Date().getTime() / 1000);
$('input[name=timedate]').val(d);
var btn1 = $('#post_global');
btn1.val('posting');
btn1.removeClass('t_s').addClass('t_sDisabled');
btn1.prop('disabled',true);
}
(function() {
$('form').ajaxForm({
dataType: 'json',
beforeSubmit: validate,
success: processResponse
});
})();
function processResponse(data) {
document.getElementById('upfile').value = "";
document.getElementById('fileinfo').innerHTML = "";
document.getElementById('txt1').value="post anything...";
var status = $('#status');
if(data.errors == ""){
status.hide().html(data.htmlResponse).fadeIn(1000);
} else{
alert(data.errors);
}
var btn2 = $('#post_global');
btn2.val('post');
btn2.removeClass('t_sDisabled').addClass('t_s');
btn2.prop('disabled',false);
}
This is the answer that I think you're looking for. If you want more, just comment what you want below:
$("#btn2").click(function() {
$('#btn2').attr("disabled", true);
//Do the request here
$('#btn2').attr("disabled", false);}
Possibly this?
function timing(){
d=Math.round(new Date().getTime() / 1000);
$('input[name=timedate]').val(d);
var btn1 = $('#post_global');
btn1.val('posting');
$('#btn2').attr("disabled", true);
}
(function() {
$('form').ajaxForm({
dataType: 'json',
beforeSubmit: validate,
success: processResponse
});
})();
function processResponse(data) {
document.getElementById('upfile').value = "";
document.getElementById('fileinfo').innerHTML = "";
document.getElementById('txt1').value="post anything...";
var status = $('#status');
if(data.errors == ""){
status.hide().html(data.htmlResponse).fadeIn(1000);
} else{
alert(data.errors);
}
var btn2 = $('#post_global');
btn2.val('post');
$('#btn2').attr("disabled", false);
}

pass php array to jquery with getJSON

updated:
i use this:
$.getimagesarr = function(operation) {
return $.ajax({
type: 'POST',
url: 'operations.php',
data: {'operation':operation},
async: false
}).responseText
}
var jsonstring = $.getimagesarr('getimg');
var data = (new Function("return " + jsonstring))()
if (data){
....
}
old:
i want to pass a php aray to jQuery:
$.getimagesarr = function() {
$.getJSON('operations.php', {'operation':'getimglist'}, function(data){
var arr = new Array();
arr = data;
return arr;
});
}
var data = $.getimagesarr();
if (data){
jQuery.each(data, function(i, val) {
....
});
}
it return undefined
in php i have this:
function getimglist(){
$results = $_SESSION['files'];
echo json_encode($results);
}
it is possible?
The return arr; line isn't going to return a value for the $.getimagesarr function. It's going to execute asynchronously, after the $.getJSON() call has finished. You should move the bottom area of code to within the success event handler for the $.getJSON() call:
$.getimagesarr = function() {
$.getJSON('operations.php', {'operation':'getimglist'}, function(data){
if (data){
jQuery.each(data, function(i, val) {
....
});
}
});
};

Categories