I dont know why this is not working. Im trying to pass data through ajax. Iv used this many times but for some reason its not working. Its returning nothing.
here is the js
$('#contactformbtn').click(function(){
var fullname = $('#fullname').val();
var youremail = $('#youremail').val();
var subject = $('#subject').val();
var yourmessage = $('#yourmessage').val();
var datastring = 'fullname=' + fullname + '&youremail=' + youremail + '&subject=' + subject + '&yourmessage=' + yourmessage;
$.ajax({
type: "POST",
url: "ajax-contact.php",
data: datastring,
success: function(status){
alert(status);
}
});
//alert(datastring);
return false;
});
and this is the php
<?php
require 'core/init.php';
if(isset($_POST)){
$fullname = $_POST['fullname'];
$youremail = $_POST['youremail'];
$subject = $_POST['subject'];
$message = $_POST['message'];
echo $fullname;
}
?>
in chrome im checking the console and im getting 2 errors
Uncaught TypeError: Cannot read property '1' of null
Uncaught TypeError: Cannot read property '3' of null
My full js is this, (just incase the error is not the contact function)
$(document).ready(function(){
$("#download-btn").bind("click", downloadfile);
$(".download-link").hide();
function downloadfile()
{
var dl = $("#dl").val();
var counter = 10;
var interval = setInterval(function(e) {
counter--;
if(counter > 0){
$("#download-btn").html("Your Download will begin in " + counter + " Seconds");
$("#download-btn").attr("disabled", "disabled");
} else {
window.location.href="http://www.forwardfiles.com/get_file.php?i="+dl;
$("#download-btn").hide();
$(".download-status").html("<h3 class='center'>Download is complete</h3>");
clearInterval(interval);
}
}, 1000);
}
$('#contactformbtn').click(function(){
var fullname = $('#fullname').val();
var youremail = $('#youremail').val();
var subject = $('#subject').val();
var yourmessage = $('#yourmessage').val();
var datastring = 'fullname=' + fullname + '&youremail=' + youremail + '&subject=' + subject + '&yourmessage=' + yourmessage;
$.ajax({
type: "POST",
url: "ajax-contact.php",
data: datastring,
success: function(status){
alert(status);
}
});
//alert(datastring);
return false;
});
});
Did you try .serialize?
$('#contactformbtn').click(function(){
$.ajax({
type: "POST",
url: "ajax-contact.php",
data: $("form").serialize(),
success: function(status){
alert(status);
}
});
//alert(datastring);
return false;
});
Check in your HTML code if these values
var fullname = $('#fullname').val();
var youremail = $('#youremail').val();
var subject = $('#subject').val();
var yourmessage = $('#yourmessage').val();
Have defined their id's and not only "name" tags
I got it working, the code i had was fine. the problem was i wasnt running php version 5.3, so i updated it and its working :D. Thanks for you help anyway
Related
I have a jquery function that has an ajax call. I can't get the total price to come up even though it should be working. The class .cart-price is within .cart-body so I don't think its an issue with the template.
function refreshCart(){
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
// $(cartBody).empty()
//cartBody.html("<h1>Changed</h1>")
var productRows = cartBody.find(".cart-product")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data){
console.log("success")
console.log(data)
if (data.products.length > 1){
productRows.html(" ")
$(cartBody).empty()
$.each(data.products, function(index, value){
console.log(value)
cartBody.append("<tr><td>" + value.name + "</td><td>" + value.price + "</td></tr>")
})
// console.log(data.total)
cartBody.find(".cart-total").text(data.total)
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
})
$(cartBody).empty() was clearing everything in the table body. The solution was to create a new HTML table row outside of the table body.
I have written a script on change event of image uploading and getting it's value then passing it through ajax datatype in json format on click of a button.
But the error is occurring at this below line
byteData = byteData.split(';')[1].replace("base64,", "");
error message "cannot read property split of null". So exactly what is the issue is occurring
HTML code
<input type='file' id='flImage' name='flImage' />
Script
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
var reader = new FileReader();
var fileName;
var contentType;
$("#flImage").change(function () {
if (typeof (FileReader) != "undefined") {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
fileName = file[0].name;
contentType = file[0].type;
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
$(document).on("click", "[id*=btnFrmSubmit]", function () {
alert("hi");
var user = {};
user.PRODUCT_ID = 1;
user.TDC_NO = $("[id*=Tdc_No]").val();
user.REVISION = $("#Revision").text();
user.REVISION_DATE = $("[id*=Revision_Date]").text();
user.P_GROUP = $("[id*=P_Group]").val();
user.PROD_DESC = $("[id*=Prod_Desc]").val();
user.N_I_PRD_STD = $("[id*=N_I_Prd_Std]").val();
user.APPLN = $("[id*=Appln]").val();
user.FRM_SUPP = $("[id*=Frm_Supp]").val();
user.CREATED_DATE = $("#Revision_Date").text();
user.CREATED_BY = $("[id*=lblUserName]").text();
var byteData = reader.result;
byteData = byteData.split(';')[1].replace("base64,", "");
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: '{user: "' + JSON.stringify(user) + '",byteData: "' + byteData + '", imageName: "' + fileName + '", contentType: "' + contentType + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
try to check your value for "null" and "undefined" first, before use it :
if(byteData)
byteData = byteData.split(';')[1].replace("base64,", "");
I am using jquery in my one of the form. where on click of submit button i call one function QuoteDetailValidation(). In which i validate fields. But after validate that fields i try to get all fields which have errorActive class. But unfortunately i can't get it.
See my code
$('#saveQuote').on('click', function(event) {
var descriptionData1 = $('input[name=\"QuoteDetail[description][]\"]');
QuoteDetailValidation(descriptionData1);
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length;
alert(selectors);
return false;
});
function QuoteDetailValidation(descriptionData1) {
for (var i = 0; i < descriptionData1.length; i++) {
var id = descriptionData[i].id;
var value = descriptionData[i].value;
var costid = costData[i].id;
var costValue = costData[i].value;
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
}
}
Now What happens, When there is error QuoteDetailValidation() append errorActive class to fields.
By var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length; i try to get length of the fields which have errorActive class. but in alert of selectors, it always gives 0. But when i alert something before getting all errorActive Class then alert selectors give me perfect count. i think there is delay because of alert before getting class errorActive. so that it give me count. How to use it. Any help please. Thanks in advance.
You can determine the exact delay required for selectors to be initailized properly. Whatever we add as delay will be assumption and can be short for some scen
One options using below in your ajax request
async: false
like below:-
$.ajax({
type: 'GET',
async: false,
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {}});
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true(it is default) then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet. Helpful question
But I still will advise you to move selectors part in success of ajax like below:-
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length;
alert(selectors);
//some logice here or move the above in some function and call it here
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
or use call back functions.
Update: try something like below It will keep async as true and keep the count logic outside $.ajax.
function QuoteDetailValidation(descriptionData1,submitFormOrAddError) {
for (var i = 0; i < descriptionData1.length; i++) {
var id = descriptionData[i].id;
var value = descriptionData[i].value;
var costid = costData[i].id;
var costValue = costData[i].value;
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
submitFormOrAddError(data);
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
}
}
Call it like this:
$('#saveQuote').on('click', function(event) {
var descriptionData1 = $('input[name=\"QuoteDetail[description][]\"]');
QuoteDetailValidation(descriptionData1);
QuoteDetailValidation(descriptionData1,function(output){
// here you use the output
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length; //This line is excuted only after call completes
alert(selectors);
//form submit here if error is zero.
});
alert("hii");//this line is executed without waiting for above call..
return false;
});
You need to do this on your success callback of the QuoteDetailValidation method, because the $.ajax runs async and after invoking the method it still hasn't completed.
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
// Here you know that the elements will have the necessary classes.
var selectors = $('#quote-quoteItems-form .errorActive').length;
alert(selectors);
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
After submit a reply without 1st post Its display a blank data space and after refresh page its show reply.
What is problem here please.
..............................................................................
This is my script
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputReplycom = $(".replycom");
var inputImg = $("#img");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var replyList = $("#replynext");
function updateReplybox() {
var tutid = inputTutid.attr("value");
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid=" + tutid,
complete: function (data) {
replyList.append(data.responseText);
replyList.fadeIn(2000);
}
});
}
$(".repfrm").click(function () {
error.fadeOut();
if (checkForm()) {
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$('.reply_here').hide();
$("#loader").fadeIn(400).html('<br><img src="loaders.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
//send the post to submit.php
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&author=" + author + "&replycom=" + replycom + "&url=" + url + "&img=" + img + "&parent_id=" + parent_id + "&tutid=" + tutid,
complete: function (data) {
error.fadeOut();
$("#loader").hide();
replyList.append(data.responseText);
updateReplybox();
$("#repfrm").each(function () {
this.reset();
});
}
});
} else //alert("Please fill all fields!");
error_message();
});
Probably all this code should be inside a $(document).ready({ ... });
To debug: Open chrome inspector and put a brakepoint at this line: var tutid = inputTutid.attr("value"); and check for what is inside inputTutid variable.
Also you can try
inputTutid.val();
instead of
inputTutid.attr("value");
I am using jQuery.validationEngine plugin .I have a below ajax function to check duplicate unique value for a field.
function _is_unique(caller) {
var value = jQuery(caller).val();
var field_id = jQuery(caller).attr('id');
var field_name = jQuery(caller).attr('placeholder');
if (value != '') {
var uniqueObject = new Object();
uniqueObject.field_id = field_id;
uniqueObject.value = value;
var uniqueString = JSON.stringify(uniqueObject);
var getUrl = window.location;
//console.log(getUrl);
var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
jQuery.ajax({
type: "POST",
url: baseUrl + "/dashboard/check_unique",
data: uniqueObject,
async: false,
cache: false,
dataType: "text",
success: function(msg) {
if (msg == "exist") {
isError = true;
promptText += " This " + field_name + settings.allrules["is_unique"].alertText + "<br />";
}
}
});
}
}
if the field value is present in server then from server I am returnning "exist" else I am returning "notexist".
Now while running my ajax script is calling infinitely . Can any please tell me what should I do to stop infinite loop of my ajax call.
Edited
This is the form Submit function . its also showing
too much recursion
error in console. By any chance am I having problem here ?
$('#searchform').on('submit', function(e){
var validateError ='';
var id='';
var fieldError = [];
$('#searchform :input:text').each(function(){
id = $(this).attr('id');
validateError = jQuery.fn.validationEngine.loadValidation(document.getElementById(id));
if(validateError)
{ fieldError.push(id);
}
});
if(fieldError.length!=0)
{
return false;
}
else{
$("form#searchform" ).submit();
return true;
}
});
});