I use eModal to call for a modal remotely via ajax. Although within the modal I have a form and the javascript code does not listen to it and thus it doesn't post. My codes are as follows;
eModal and Ajax for the form;
$(document).ready(function() {
// process the PROJECT UPDATE form
$('#proj-edit').submit(function(event) {
// get the form data
var formData = {
'projID' : $('input[name=projID]').val(),
'projname' : $('input[name=projname]').val(),
'projstart' : $('input[name=projstart]').val(),
'projend' : $('input[name=projend]').val(),
'projhotel' : $('input[name=projhotel]').val(),
'projcity' : $('input[name=projcity]').val(),
'projstatus' : $('#projstatus').val()
};
if (formData.projname == '' ||
formData.projstart == '' ||
formData.projend == '' ||
formData.projhotel == '' ||
formData.projcity == '') {
return false;
}
// process the form
$.ajax({
type : 'POST',
url : 'inc/prjedit.ajax.php',
data : formData,
dataType : 'json',
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
} else {
$('#proj-edit').trigger('reset');
swal("Success!", "Edit success!", "success");
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
console.log(data);
});
event.preventDefault();
});
$('button[id=demo]').click(function() {
var value = $(this).val();
ajaxDemo(value)
});
function ajaxDemo(value) {
var title = 'Ajax modal';
var params = {
size: eModal.size.lg,
title: title,
type: 'GET',
url: 'inc/demo.ajax.php?pID='+ value
};
eModal.setEModalOptions({
loadingHtml: '<div class="text-center"><span class="fa fa-circle-o-notch fa-spin fa-5x text-primary"></span></div>',
});
return eModal
.ajax(params);
}
});
The modal content is rather simple;
<form class="form" method="POST" action="" id="proj-edit" name="proj-edit">
// the input fields are here. Although since it is too long, I did not include them in here.
<button type="submit" class="btn btn-info" name="update-prj">Register</button>
</form>
I should note that the JavaScript code is in a different document named magic.js, the modal works although it does not submit the form. What am I missing here or what am I doing wrong?
The console log has this to say about all this;
(When eModal opens ->) XHR finished loading: GET "http://localhost/parantez/inc/demo.ajax.php?pID=301".k.cors.a.crossDomain.send # jQuery-2.1.4.min.js:4n.extend.ajax # jQuery-2.1.4.min.js:4n.fn.load # jQuery-2.1.4.min.js:4ajax # eModal.js:336ajaxDemo # magic.js:270(anonymous function) # magic.js:253n.event.dispatch # jQuery-2.1.4.min.js:3r.handle # jQuery-2.1.4.min.js:3
(When form is submitted ->) Navigated to http://localhost/
This issue has now been solved thanks to this post. Thank you very much for taking your time to answer, I highly appreciate your input. Kudos to all of you.
you are passing javascript object to php which is not valid in ajax request
use JSON.stringify() to convert json object into string and inside php use json_decode function to make object of json ...
like this
$.ajax({
type : 'POST',
url : 'inc/prjedit.ajax.php',
data : JSON.stringify(formData),
dataType : 'json',
encode : true
})
if you don't want to send json data then use
formData to send data with ajax same as from submission like that
data = new FormData();
data.append('projID', $('input[name=projID]').val());
do this for all and then simply pass data to ajax function like this
$.ajax({
url: 'http://example.com/script.php',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
ok hope this will help ...
Related
In the below code, I'm able to transfer data but when I use the function append to transfer file and data it's not working. Can someone tell me how to transfer file from upload? Looking forward to some help
$(document).ready(function() {
var loader = '<img src="../assets/media/loader.gif" />';
$('#submit').click(function() {
confirm("Do you really want to send messages?");
$('.loading').html(loader).fadeIn();
var msg_area_cst = $('textarea[name=msg_area_cst]').val();
var num_cst = $('textarea[name=num_cst]').val();
var form_data = new FormData();
form_data = 'msg_area_cst=' + msg_area_cst + '&num_cst=' + num_cst;
form_data.append('upload', $('input[name=upload]'));
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: form_data,
success: function(html) {
if (html == 1) {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
});
});
});
The problem is because you correctly declare a FormData object, but then in the next line overwrite it immediately with a string.
You need to append() all data to the FormData object. In addition you need to provide the file data to the append() method, not the jQuery object referencing the input type="file" control.
var form_data = new FormData();
form_data.append('msg_area_cst', msg_area_cst);
form_data.append('num_cst', num_cst);
form_data.append('upload', $('input[name=upload]')[0].files[0]);
That being said, you can make this much more simple if the controls you're reading the values from are contained in a form element. Then you can use the submit event of that form and pass a reference to it to the FormData constructor.
Also you don't do anything with the result of the confirm() I assume you want to stop the form submission if Cancel is clicked, which the above example now does using preventDefault().
Finally, using html == 1 is very unreliable. Firstly html will be a string so relying on implicit type coercion to an integer is not ideal. Also, returning a plain text response can cause issues if there's any whitespace included. I'd strongly suggest you change your server side logic to return a serialised format, such as JSON, and use a boolean value for a 'success' flag.
With all that said, try this:
$('#yourForm').on('submit', function(e) {
if (!confirm("Do you really want to send messages?")) {
e.preventDefault();
}
$('.loading').html(loader).fadeIn();
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: new FormData(this),
success: function(html) {
if (html.trim() === "1") {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
}
});
});
Try this ajax code
$.ajax({
url: "../server/CustomMsg.php",
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData:false,
async: true,
success: function(html) {
if (html == 1) {
$('#register_form').fadeOut('slow');
$('.loading').fadeOut();
$('.message').html('Successfully Sent ! ').fadeIn('slow');
} else
alert('Sorry, unexpected error. Please try again later.');
}
});
In my webpage I am using jQuery/Ajax to save form data. After save the data using php I am showing successful message like bellow :
if($sql){
$sql_result[] = "<div class='success'>updated</div>";
}
echo end($sql_result);
In Ajax return data I am checking a condition if message is contain updated then I will hide a html element but It's not working.
Here is my jQuery code:
function save_email (element, event) {
e = $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
data : formData,
cache : false,
contentType: false,
processData : false,
url : 'save_email.php',
type : 'POST',
xhr : function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success : function (data) {
$("#email_success").html(data);
//$("#email_success").show('slow').delay(3000).hide('slow');
if(data == "<div class='success'>updated</div>" ) {
$("#save_email_button").hide('slow');
$(".delete_ex_email_label").hide('slow');
}
},
});
}
Console log data
Updated:
alert(data) is showing this :
It's not uncommon to end up with extra whitespace in php text/html output
That is one reason it's easier to use json and check object properties , especially over comparing a complex string like you are doing.
However using trim() when comparing string results is generally a good idea
try
$.trim(data) === "<div class='success'>updated</div>")
I'm calling a GET request from a jQuery AJAX function, but the GET request doesn't seem to be calling properly. After running the script, the address bar only shows "index.php?", instead of the expected "index.php?searchterm=searchterm".
index.php
$(function(){
$("form").submit(function(){
var searchterm = document.getElementByID("searchterm").value;
$.ajax({
method: "GET",
url: "search.php",
data: searchterm
})
.done(function(res) {
document.getElementById("item1").innerHTML = res;
});
});
});
If it's any relevance, here is search.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$searchterm= isset($_GET['searchterm']) ? $_GET["searchterm"] : '';
exec("C:\Users\Callum\AppData\Local\Programs\Python\Python35-32\python.exe search.py $searchterm", $output, $result);
echo $result[0];}
?>
Correct data in ajax call as :
.......
$.ajax({
method: "GET",
url: "search.php",
data : { searchterm : searchterm } // Change here
})
.......
According to docs ,data in ajax call is data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. Object must be Key/Value pairs.
Reference
You should open the firebug console and see if you ajax request is visible there. If it is visible you can click on it and you will see what data it is passing to the requested url search.php
Also You didn't pass the data correctly using ajax. And if you are using ajax then browser address bar will not be updated as the page is not getting reloaded.
$(function(){
$("form").submit(function(){
var searchterm = document.getElementsByID("searchterm").value;
$.ajax({
method: "GET",
url: "search.php",
data: { searchterm : searchterm }//This is how to pass data correctly
})
.done(function(res) {
document.getElementById("item1").innerHTML = res;
});
});
});
the data property of the ajax function is an object so it should look like this:
data: { searchterm: searchterm }
The problem that I'm facing is that I'm getting an Undefined Index variable while calling Ajax.
I need to post "json" data to the "update.php" page on click of submit button. Basically, I need to capture the values in textbox and send it to the database.
so, I have created a form on the submit button, for which the code is below:
<form action="update.php" method = "post" class="form-inline">
<input type="submit" class="btn btn-info" id = "saveEdits" disabled = "disabled" onclick = "updateVal()" name="saveEdits" value="Update"/>
/form>
This submit button Calls for an UpdateVal function that captures the value on the text-boxes shown on the page and using AJAX send it to the another php page.
updateVal function is as below:
function updateVal() {
var node_list = document.getElementsByTagName('input');
var c = 0;
var fieldName = [];
var fieldText = []
var ID = [];
for (var i = 0; i < node_list.length; i++) {
var node = node_list[i];
if (node.getAttribute('type') == 'text') {
fieldName[c] = node.name;
fieldText[c] = node.value;
ID[c] = node.id;
c++;
}
}
var postData = {
fieldName: fieldName,
fieldText: fieldText,
ID: ID
};
$.ajax({
type: "post",
url: "update.php",
dataType: "json",
data: {'postData' : JSON.stringify(postData)},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
});
The run time data i.e value in textboxes is being captured and can be shown at console, however, when I'm posting this data on update.php, where I would be capturing the json and will update the database, I'm getting the error:
Notice: Undefined index: in update.php on line 11
Below is my update.php
<?php
$json = $_POST["postData"];
$result = json_decode($json);
var_dump($result);?>
Remove your action attribute from your form, since you send your data per Javascript/AJAX you don't need it.
What you do now is: you send the data twice, once per updateVal() and once per default submit handling of the form.
Since the form-submitted data doesn't contain a input named postData, you are getting your undefined index error.
Edit:
You stated you are not comfortable with the whole AJAX topic. Here is a nice simple answer covering the basics.
Edit2:
to listen for the response of your server add a callback to your ajax-request:
$.ajax({
type: "post",
url: "update.php",
dataType: "json",
data: {'postData' : postData},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
}).done(function (response, textStatus, jqXHR){
// Show an alert on response
alert(response);
});
i'm tring to upload file using jquery ajax function with ruby-sinatra function. here is my code.
<form id="ucform" method="post" action="#" enctype="multipart/form-data">
<input type="file" id="cfile" name="cfile" onchange="prepareUpload(this.files)">
<button type="submit">Update</button>
</form>\
javascript code
var ufiles;
function prepareUpload(files)
{
ufiles = files
}
$(function(){
$('#ucform').on('submit', uploadFiles);
});
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
//alert(ufiles);
// Create a formdata object and add the files
var data = new FormData();
$.each(ufiles, function(key, value)
{
data.append(key, value);
});
alert(data);
$.ajax({
url: '/upload_cfiles',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
alert(data);
}
});
}
sinatra function
post '/upload_cfiles' do
begin
File.open('applications/QOS/conf/' + params['cfile'][:filename], "w") do |f|
f.write(params['cfile'][:tempfile].read)
end
return "The file was successfully uploaded!"
rescue Exception => e
return e.message
end
end
above code return bellow error
ERRORS: parsererror
undefined method `[]' for nil:NilClass
please help me to solve this error
It's a safe bet that params['cfile'] is nil. Have you actually logged your request parameters to ensure you are posting what you think you're posting?
Furthermore, I believe that you're trying to upload these files using JSON - you will most likely need to base64 encode the body of the file to do this.