How i can create ajax success if else condition without json? - php

I created a form. I added many validations as requirement like required all fields. Check duplicate fields. Now I want if form submitted successfully without error reset my form if it has any error like duplicate email then show error Duplicate data found and don't reset form. I completed my code but tucked in a place I m returning false then it's not showing an error which I mentioned din called PHP file. So, how can I do it without using JSON?
$("#create_stock_out").click(function(){
var form= new FormData();
var subject = $("#subject").val();
var slip_no = $("#slip_no").val();
var warehouse = $("#warehouse").val();
var vendor = $("#vendor").val();
var issued_by = $("#issued_by").val();
var received_by = $("#received_by").val();
var project = $("#project").val();
form.append('subject',subject);
form.append('slip_no',slip_no);
form.append('warehouse',warehouse);
form.append('vendor',vendor);
form.append('issued_by',issued_by);
form.append('received_by',received_by);
form.append('project', project);
form.append('method', "stock_out");
$.ajax({
url: 'Function/Function.php',
type: 'post',
data: form,
contentType: false,
cache: false,
processData:false,
success:function(data){
//alert(data);
$('#stock_out_result').html(""+data+"");
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 5000);
}
});
});

Related

Inserting image and data along with date using ajax to database

I want to submit form data to the database using Ajax, It has image date and some more values which are not inserted into a database
I am trying this in localhost with PHP and mySQL
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
$("#butsave").attr("disabled", "disabled");
var candidate_key=$("#candidate_key").val();
var candidate_employer=$("#candidate_employer").val();
var candidate_ex=$("#candidate_ex").val();
var optionyes=$("#optionyes").val();
var e_date=$("#e_date").val();
var s_date=$("#s_date").val();
var candidate_ctc_ex=$("#candidate_ctc_ex").val();
var candidate_ctc=$("#candidate_ctc").val();
var candidate_email=$("#candidate_email").val();
var candidate_address=$("#candidate_address").val();
var candidate_mobile=$("#candidate_mobile").val();
var candidate_name=$("#candidate_name").val();
var mms_pic=$("#mms_pic").val();
if( candidate_mobile!="" && candidate_email!="" && candidate_name!=""){
$.ajax({
url: "index1.php",
type: "POST",
mimeType:"multipart/form-data",
data: {
candidate_key:candidate_key,
candidate_employer:candidate_employer,
candidate_ex:candidate_ex,
optionyes:optionyes,
e_date:e_date,(This is the date which is in the proper format i am taking from date picker yy-mm-dd)
s_date:s_date,
candidate_ctc_ex:candidate_ctc_ex,
candidate_ctc:candidate_ctc,
candidate_email:candidate_email,
candidate_address:candidate_address,
candidate_mobile:candidate_mobile,
candidate_name:candidate_name,
mms_pic:mms_pic (This is the picture or document file) },
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
console.log(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
});}
else{
alert('Please fill all the field !');
}
});
});
</script>
Uncaught SyntaxError: Unexpected token o in JSON at position
Be sure to check you’re not attempting to JSON.parse() an already parsed JSON object.
Remove this line from your success callback to confirm.

how to send form data with fileupload image in php using ajax

I am trying to send form data with attachment to php via ajax.
My code is :
var company_name = $('#companyname').val();
var company_type = $('#companytype').val();
var industry_sector = $('#industrysector').val();
var email = $('#email').val();
var mobile = $('#mobile').val();
var logo = $("#logo").prop("files")[0];
var company_description = $('#company_description').val();
var password = $('#password').val();
var rePassword = $('#rePassword').val();
var data = {
company_name: company_name,
company_type: company_type,
industry_sector: industry_sector,
email: email,
mobile: mobile,
logo: logo,
company_description: company_description,
password: password
}
$.ajax({
type: "POST",
async: false,
data: {companyregister: data},
url: "ajax/loginvia.php",
processData: false, // tell jQuery not to process the data
contentType: false,
beforeSend:function(){
},
i am getting empty data to php controller. i tried in many ways, im unable to resolve the issue.
With simple ajax it is some complex to perform you can use ajaxForm for this. It is easy to implement. Here is plugin url : http://jquery.malsup.com/form/
It is so easy to implement have a look at this.
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file

How to pass form data along with image through jquery? [duplicate]

This question already has answers here:
Sending multipart/formdata with jQuery.ajax
(13 answers)
Closed 6 years ago.
I would like to pass form data via jquery to a php page. Now I am little confused with image passing through jquery and how it will reach php page.
My code:
<script>
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
var guestbookSendMessage = { //Fetch form data
'name' : $('input[name=name]').val(), //Store name fields value
'msg': $('textarea[name=msg]').val()
'file' :$("#fileInput")[0].files[0];
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'php/process.php', //Your form processing file url
data : guestbookSendMessage, //Forms name
dataType : 'json',
success : function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
}
} else {
$('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
</script>
You may use File API or FormData to send image data to your server with ajax. What to choose is up to you to decide but since FormData is easier to implement I will answer your question using FormData here.
First of all you need to create FormData container and append your data to it. Just amend your code
var guestbookSendMessage = { //Fetch form data
'name': $('input[name=name]').val(), //Store name fields value
'msg': $('textarea[name=msg]').val()
'file': $("#fileInput")[0].files[0];
};
with this
var guestbookSendMessage = new FormData();
guestbookSendMessage.append('name', $('input[name=name]').val());
guestbookSendMessage.append('msg', $('textarea[name=msg]').val());
guestbookSendMessage.append('file', $("#fileInput")[0].files[0]);
Now instead of this parameter in your $.ajax
dataType: 'json'
Add these two
processData: false,
contentType: false
This will allow your data to be interpreted correctly.
Now in your php/process.php script you'll get 'name' and 'msg' in your $_POST superglobal array and 'file' in $_FILES.
var fdata = new FormData();
var myform = $('#prfform'); // specify the form element
var idata = myform.serializeArray();
var document = $('input[type="file"]')[0].files[0];
fdata.append('document[]', document);
$.each(idata,function(key,input){
fdata.append(input.name,input.value);
});
$.ajax({
url:"process.php",
type: "POST",
data: fdata,
processData: false,
contentType: false,
beforeSend: function() {
//something before send
},
success:function(data) {
//something after response
}
});
<form name="prfform" id="prfform" method="post" enctype="multipart/form-data">
<!-- elements -->
</form>
Please try this code.
"enctype" is important in the form.
In ajax script, give "processData: false" and "contentType: false"
This might solve your issue.

jquery ajax: how to keep record not dissapear when the page is refresh

i use this script
<script type="text/javascript">
$(function () {
$(".comment_button").click(function () {
var element = $(this);
var boxval = $("#content").val();
var dataString = 'content=' + boxval;
if (boxval == '') {
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "update_data.php",
data: dataString,
cache: false,
success: function (html) {
$("ol#update").prepend(html);
$("ol#update li:first").slideDown("slow");
document.getElementById('content').value = '';
$("#flash").hide();
}
});
}
return false;
});
$('.delete_update').live("click", function () {
var ID = $(this).attr("id");
var dataString = 'msg_id=' + ID;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete_data.php",
data: dataString,
cache: false,
success: function (html) {
$(".bar" + ID).slideUp('slow', function () {
$(this).remove();
});
}
});
}
return false;
});
});
</script>
this script combine live update and delete record using jquery and ajax
the problem is when I refresh the page, the record will disappear .. how to keep records that show up are not dissapear when the page is reloaded?
First Check the comment list. Did you put any limit in query, if so then use Order by Primary ID desc.So it would display latest records first.
When you delete any record, check whether it is actually deleted from database or not. Because you are not checking whether record actually deleted or not as per the code you given.
Assuming you are using update_data.php and delete_data.php to manipulate some database, you could use PHP to render the page initially using the data that is currently on the database.
If that is not the case, and you don't have access to that database (it could be a third party web service, right?), or you don't want to do that for any reason, you could use cookie like Saeed answered.

Updating div using ajax not working correctly

Sorry but I know something similar to this has already been posted. I have tried every single resource out there and did my research and I still couldn't find out what is wrong with my code. I am using a Ajax Post with php. Everything seems to be working fine except for the fact that the div is not reloading on submit. After I refresh the page what I posted came up. Can someone please tell me what I am doing wrong.
js code:
$(function() {
$('.error').hide();
$('input.text-input').css({
backgroundColor: "#FFFFFF"
});
$('input.text-input').focus(function() {
$(this).css({
backgroundColor: "#C0DDFA"
});
});
$('input.text-input').blur(function() {
$(this).css({
backgroundColor: "#FFFFFF"
});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
var dataString = '&email=' + email;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "../EdinburgCISD/Gorena/Gorena.php",
data: dataString,
success: function(data) {
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
});
return false;
});
});​
html code:
This is where I have my div.
<div id="div"> <?php \\database select query ?> </div>
I am new to this website sorry if I posted something wrong...
did you get any error in console (firebug/developer tools) ?
otherwise you can try below
check with alert
$.ajax({
type: "POST",
url: "../EdinburgCISD/Gorena/Gorena.php",
data: dataString,
success: function(data) {
alert(data);//what you get here? are you getting "object" in alert? then you need to specify property or mention dataType
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
});
modified your code a bit see the comments, you should specify dataType:html (see the ajax part).
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#C0DDFA"});
});//focus ends
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});//blur ends
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var email = $("input#email").val();
if (email == "") {
$("label#email_error").show();
$("input#email").focus();
return false;
}
//var dataString = '&email=' + email; commented out
var dataString = email; //try insted this
//alert (dataString);return false;
$.ajax({
type: "POST",
dataType:'html', //or the appropiate type of data you are getting back
url: "../EdinburgCISD/Gorena/Gorena.php",
data: {email:dataString}, //in the php file do $email = $_POST['email'];
async:false, //not a good practice but you can try with it and without it
success: function(data) {
$("#email").val('');
$("#div").fadeOut(1000);
// Change the content of the message element
$("#div").html(data);
// Fade the element back in
$("#div").fadeIn(1000);
}
}); //ajax ends
return false;
});//click ends
});//document ready ends
update
see this fiddle you will get the idea http://jsfiddle.net/3nigma/LuCQw/ and the delay function is optional i have used it so that the effect is prominent

Categories