I'm sure if I'm going about this the right way, but I need to pass the form variables in the URL redirect. The redirect is working, but I can't get the data to output.
$("#promoForm").on('submit', function(e) {
e.preventDefault();
var data = {
firstname: $("#firstname").val(),
lastname: $("#lastname").val(),
email: $("#email").val(),
code: $("#code").val()
};
if ( isValidEmail(data['email']) && (data['firstname'].length > 1) && (data['lastname'].length > 1) && (data['code'].length > 1) ) {
$.ajax({
type: "POST",
url: "php/promo.php",
data: data,
success: function() {
$('.success.pf').delay(500).fadeIn(1000);
$('.failed.pf').fadeOut(500);
setTimeout(function() {
window.location.href = "http://demo.example.com/signup?firstname=+data['firstname']+lastname=+data['lastname']+email=+data['email']+code=+data['code']"
}, 3000);
}
});
} else {
$('.failed.pf').delay(500).fadeIn(1000);
$('.success.pf').fadeOut(500);
}
return false;
});
Try this,
window.location.href = "http://demo.example.com/signup?firstname="+data['firstname']+"lastname="+data['lastname']+"email"=+data['email']+"code="+data['code']
You are not using variables to construct the URL:
window.location.href = "http://demo.example.com/signup?firstname=+data['firstname']+lastname=+data['lastname']+email=+data['email']+code=+data['code']"
Instead, close the string with " and append the values and follow-up strings:
window.location.href = "http://demo.example.com/signup?firstname=" + data['firstname'] + "lastname=" + data['lastname'] + "email=" + data['email'] + "code=" + data['code']
Additionally, you seem to be missing the parameter separators (&), so I should probably be:
window.location.href = "http://demo.example.com/signup?firstname=" + data['firstname'] + "&lastname=" + data['lastname'] + "&email=" + data['email'] + "&code=" + data['code']
Related
I have these columns on my table:
CardNumber
DateRegister
TimeRegister
DateExit
TimeExit
I read a value that is in a box, and when I press enter, the
Cardnumber, DateRegister,TimeRegister is add to the SQL Database
So I'll have like
CardNumber|DateRegister|TimeRegister|DateExit|TimeExit
124455|23-10-2022|11:00|null|null|
My Issue is, If I read the same card again, before I need to see if there is already one entrance on database with that card number, that don't have still DateExit and TimeExit.
If dont, I need to update that line, with that information, of if is a new one, will add a new entrance on the database
This is my code:
#section readcard{
<script>
$(function () {
$("#readONchange").change(function () {
var param1 = new Date();
var param2 = param1.getDate() + '/' + (param1.getMonth() + 1) + '/' + param1.getFullYear();
var param3 = param1.getHours() + ':' + param1.getMinutes() + ':' + param1.getSeconds();
var es = {};
/*es.IdCartao = $("#readONchange").val();*/
/*es.DateRegister = param2;*/
//Le cartao / Le data / Le Hora
es.IdCartao = $("#readONchange").val();
es.DateRegister = param2;
es.TimeRegister = param3;
if (es.IdCartao != null)
{
} else if (es.IdCartao == null) {
empregados.IdCartao = es.IdCartao(id);
(es.IdCartao == $("#readONchange").val && es.DateRegister != null && es.TimeRegister != null)
es.TimeExit = param3;
alert(es.IdCartao == $("#readONchange").val);
} else {
alert("erro")
}
alert("Register ADD!")
$.ajax({
type: "POST",
url: '#Url.Action("AddReport")',
data: '{es: ' + JSON.stringify(es) + '}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
sucess: function () {
alert("Data Insert with Sucess");
},
error: function () {
alert("ERROR! on the regist");
}
});
});
});
</script>
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');
}
});
I have a Google Instant style jQuery search script that queries a PHP file then parses the results into an HTML div. It uses tabs for the user to define the search type that they want and when a search is made, a URL is created which is something like #type/query/.
Currently, the search box is selected on page load with the $('#query').focus(); function however I want it to be deselected when the page is reloaded and there is text in #query. How can I go about doing this? I hope you can understand my question.
My jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
$('#query').focus();
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0, full.indexOf("/"));
$('#type_' + queryType).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}
});
Remove $('#query').focus(); from where it is now, and add it in with an else like this:
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}else {
$('#query').focus();
}
I have a jQuery search script that uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/. I need to somehow define the query terms in my window.location.hash.replace so I am just left with the search type from the URL. How can I go about changing the QUERYGOESHERE in my example below to the query the user has made? I hope people can understand my question.
My jQuery Script is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
if (window.location.hash != "") {
url = window.location.hash.replace('#', '').replace('/QUERYGOESHERE/', '');
$('#type_' + url).click();
} else {
$('#type_search').click();
}
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
This should do it.
var full = window.location.hash.replace('#', '')
var queryType = full.substring(0,full.indexOf("/"))
var query = full.replace(queryType, '');
EDIT: Updated code
if (window.location.hash != "") {
var full = window.location.hash.replace('#', '');
var queryType = full.substring(0,full.indexOf("/"));
console.log('#type_' + queryType);
$('#type_' + queryType).click();
}
OK I am building something that makes an ajax request to one server where it determines the url it needs to then make a new ajax request to another place. Everything is progressing thanks to all the help at SO =) .. however I am stuck again. I am struggling with getting the variables to return to the different functions as I need. The second (jsonp) request returns a json function which looks like :
jsonResponse(
{"it.exists":"1"},"");
and my code...
var img = "null";
var z = "null";
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
$(data).find("ITEM").each(function()
{
query = $("SKU", this).text();
query = 'http://domain.com/' + query + '?req=exists,json';
img = $("SKU", this).text();
img = '<img src="http://domain.com/' + img + '">';
var date =$("LAST_SCAN" , this).text();
$.ajax({
url: query,
dataType: 'jsonp'
});
$("table").append('<tr>'+'<td>' + (date) + '</td>' + '<td>' + (z) + '</td>');
});
}
});
});
// function required to interpret jsonp
function jsonResponse(response){
var x = response["it.exists"];
// console.log(x);
if (x == 0) {
console.log("NO");
var z = "NO IMG";
}
if (x == 1) {
console.log(img);
//this only returns the first image path from the loop of the parseXml function over and over
var z = (img);
}
return z;
}
So I guess my problem is a two parter.. one how do I get the img variable to loop into that if statement and then once that works how can I return that z variable to be used in the first xml parser?
Try this synchronous approach:
var itemQueue = [];
$(document).ready(function ()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
itemQueue= $(data).find("ITEM").map(function ()
{
return {
sku: $("SKU", this).text(),
date: $("LAST_SCAN", this).text()
};
}).get();
getNextItem();
}
});
});
function getNextItem()
{
var item = itemQueue[0];
var query = "http://domain.com/" + item.sku + "?req=exists,json";
$.ajax({
url: query,
dataType: 'jsonp'
});
}
function jsonResponse(response)
{
var item = itemQueue.shift();
if (itemQueue.length)
{
getNextItem();
}
var x = response["it.exists"];
var z = x == "0" ? "NO IMG" : "<img src=\"http://domain.com/" + item.sku + "\">";
$("table").append("<tr><td>" + item.date + "</td><td>" + z + "</td>");
}
Store 'date' in a global variable, and move the logic to append HTML elements into the jsonResponse function. You cannot return control flow from jsonResponse because it's called asynchronously, but you can continue doing anything you'd like from that function.