jQuery serialize and validate data - javascript

I have the following line returned from serializing data
rl=250&first_name=&surname=&email=&phone=&country_id=1&agency_name=&sitename=
I want to loop through these and check if there is an empty field and if there is then I can throw an error.
I can get the index and element but the element is rl=250 or first_name=
How can I check if the element is set or not. I have also tried using serializeArray() but it returns me [Object, Object, Object, Object, Object, Object, Object, Object] which should have the name and value but I do not know how to access these

You need to split this using '&'. Then you should apply for loop and in that loop you again need to split that string with '=' sign. Then if you get second element of loop as blank, you can throw error

serializeArray is a good way.
https://api.jquery.com/serializeArray/
As you can see, it returns arrays of objects so in your case it is something like tihs:
[
{
rl: 250
},
{
first_name: undefined
}
]
After this you can iterate on the array of the objects with for loop on the values.

I found this function by Jack alan
https://stackoverflow.com/a/16215183/1430587
function deparam(query) {
var pairs, i, keyValuePair, key, value, map = {};
// remove leading question mark if its there
if (query.slice(0, 1) === '?') {
query = query.slice(1);
}
if (query !== '') {
pairs = query.split('&');
for (i = 0; i < pairs.length; i += 1) {
keyValuePair = pairs[i].split('=');
key = decodeURIComponent(keyValuePair[0]);
value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined;
map[key] = value;
}
}
return map;
}

You could do something like this:
$(document).ready( function(e) {
$("#frm-login").submit(function() {
var DATA = $(this).serializeArray();
len = DATA.length,
dataObj = {};
for (i=0; i<len; i++) { // acceesing data array
dataObj[DATA[i].name] = DATA[i].value;
}
if ( !dataObj['user-id'].trim() || !dataObj['user-pass'].trim() ) { //cheking if empty field
alert('empty');
}else{
alert('full');
}
//console.log(DATA);
$.ajax({
type: "POST",
url: 'user-login-process.php',
data: DATA,
success: function(response){
//alert(response); // show response from the php script.
}
});
return false; // avoid to run the actual submit of the form.
});
}); //document

Related

How Do I Create a $_POST array from textarea input

Here is what I am trying to do.
I have a textarea input box, I would like to enter in data in an array format like this into that textarea box
'key1'='value1'
'key2'='value2'
'key3'='value3'
I then want to take this data and use it in my ajax call like so
var a = $("textarea#array_box").val().split('\n');
$.ajax({
url: 'index.php/controller/function',
type: "POST",
data: a,
success: function(data) {
console.log(data);
I am trying to get the data to pass in so that in the controller if i did one of the return statements below I would get the resulting output.
return $_POST['key1'] // should return 'value1'
return $_POST['key2'] // should return 'value2'
return $_POST['key3'] // should return 'value3'
How do I code this so that I can type into my textarea box an array, and pass that array into my controller as a $_POST?
based on your code, you can do something like this:
<?php
$tempvar=$_POST['data'];
$result = array();
foreach($tempvar as $tempitem){
$tempitem=str_replace("'","",$tempitem); //we get rid of the ' symbols
$t=explode("=",$tempitem); //' divide them by the "=" symbol
$result [$t[0]]=$t[1];
}
//the result variable now holds the array
echo $result['key1'] // value1
?>
You can use .filter(Boolean) to remove empty elements from a array; $.each() to iterate a array, .trim() to remove space characters, .replace() with RegExp /=(?=')/ to replace = with :; RegExp /'/g to replace ' with "; create a string to concatenate string at each iteration; JSON.stringify() following $.each(); pass result of JSON.stringify() to JSON.parse() as data to POST
$("button").click(function() {
var a = $("textarea#array_box").val().split("\n").filter(Boolean);
var textareaData = "";
$.each(a, function(key, value) {
textareaData += value.trim()
.replace(/=(?=')/, ":")
.replace(/'/g, '"')
+ (key < a.length - 1 ? "," : "");
});
textareaData = JSON.stringify("{" + textareaData + "}");
console.log(textareaData);
$.ajax({
url: "/echo/json/",
type: "POST",
data: JSON.parse(textareaData),
success: function(data) {
console.log(data);
}
});
});
jsfiddle https://jsfiddle.net/ahnegop3/3/
ajax data format must be {key:value,key,value} .So to getting that format , you need do a little loop with $.each and do assign key and value by like this
object[key] = value
var a = $("textarea#array_box").val().split('\n');
var temp = [];
$.each(a,function(i,v){
s = v.split("="); //split again with =
s[0] = s[0].replace(/'/g,""); //remove ' from string
s[1] = s[1].replace(/'/g,"");
temp.push(s[0],s[1]);
});
a = {};
//creating data objects
$.each(temp,function(i,v){
if(i % 2 == 0){
a[temp[i]] = temp[++i];
}
});

Looping through dynamic JSON data using javascript

I am trying to display JSON data but the key value is dynamic it varies from one POST request to another my data hierarchy is as shown in diagram:
This is the part of the code I am running,Can anyone suggest me how to display JSON data where key showed in redbox gonna change for every POST request
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'perfid': valueOne, 'hostname': $("#host").val(), 'iteration': valueThree},
success: function(data) {
$('#img1').hide();
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect.length;
for(var i = 0; i < k; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect.obj.avg_latency);
console.log(iscsi);
}
While running above snippet I am getting following error message :
data[$(....).val(...)].iscsi_lif.result.sectoutput.sect is undefined
You can use a "for in" loop to iterate over the keys of an object without having to specify the key names.
for( var key in myObject){
myValue = myObject[key];
// key will be your dynamically created keyname
}
So your code could be similar to the following:
...
success: function(data) {
$('#img1').hide();
var obj = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for(var key in obj) {
if(obj.hasOwnProperty(key)){
var iscsi = parseInt(obj[key].avg_latency);
console.log(iscsi);
}
}
}
Solution Suggestion:
for (var key in object) {
if (object.hasOwnProperty(key)) {
var element = object[key];
}
}
Yet, in your situation, maybe you'll have to do this multiple times, so I would try to extract a generic function to do this and "normalize" the processing result to an expected format that wouldn't change.
The function will only run when the expected keys exist and since the forin loop uses the object keys, every object is processed dynamically.
This should work:
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for (var i = 0; i < k.length; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
console.log(iscsi);
}
The variable should be put inside brackets.
Also, it seemed to me that k was simply defined as length of an array, I removed that and put it to the for loop.
Since you have obj defined as varible you should use [], so it will be [obj], e.g :
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
Hope this helps.

jQuery traverse json recursive

I am trying to traverse a JSON object with jQuery recursive.. normally it worked , but not on the following JSON.
I want to traverse this JSON, here I uploaded an image:
For my json objects, i had this jquery function:
var construct_id = "#ecommerce_form_";
// function to traverse json objects given back from Serializer class
function process(callback, id) {
var key;
for (key in callback) {
// Handle the arrays
if ('length' in callback[key]) {
// Handle the end - we found a string
if (typeof callback[key][0] == "string") {
var field_id = construct_id + id + key;
var err_msg = callback[key][0];
$(field_id).tooltip('destroy');
$(field_id).tooltip({'title': err_msg});
$(field_id).closest('div[class="form-group"]').addClass('has-error');
console.log(field_id, ":", err_msg);
}
// Else we found something else, so recurse.
else {
var i = 0;
while (i < callback[key].length) {
process(callback[key][i], key + "_" + i + "_");
i++;
}
}
}
// Handle the objects by recursing.
else {
process(callback[key], key + "_");
}
}
}
But that functions fails when trying to build the contact > addresses id with the error message:
"Uncaught TypeError: Cannot use 'in' operator to search for 'length'
in This value should not be blank."
Hope you guys can help me enhancing the jQuery function, it is not 100% successfull as you can see on this json example.
Regards
You are trying to search for the property "length" in a string, which can't be done. In the erroneous iteration: callback = obj.contacts.addresses, key = cities and then callback[key][0] = "This value should not be blank".
What you should do is check if you have reached a string before looking for the "length" property, and only then if you haven't found a string, begin the recursion check.
see jsfiddle example here:
http://jsfiddle.net/38d15z4o/
var construct_id = "#ecommerce_form_";
// function to traverse json objects given back from Serializer class
function process(callback, id) {
var key;
for (key in callback) {
// Handle the end - we found a string
if (typeof callback[key] == "string") {
var field_id = construct_id + id + key;
var err_msg = callback[key][0];
$(field_id).tooltip('destroy');
$(field_id).tooltip({'title': err_msg});
$(field_id).closest('div[class="form-group"]').addClass('has-error');
console.log(field_id, ":", err_msg);
}
// Handle the objects and arrays by recursing.
else {
process(callback[key], id + key + "_");
}
}
}
NOTE: for the error message, you are only showing the first letter of the string, I think you meant to put: err_msg = callback[key] not err_msg = callback[key][0].
Why don't you check for
typeof callback[key] === 'array'
Instead checking the length property?

how to get length of json encoded array in javascript?

I have a json encoded array like this:
{
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
my quetion is :
(1) How to find length of this array? //here it is 3
(2) How to use it's value?
//for example:for as0 the value is {\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}
javascript code where i use upper things :
function setroute(os)
{
var wp = [];
for(var i=0;i<os.waypoints.length;i++)
wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][1]),'stopover':false }
ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
'waypoints': wp,
'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
})
}
function fetchdata()
{
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch')
jax.onreadystatechange = function(){ if(jax.readyState==4) {
alert(JSON.parse(jax.responseText).ar0);
try {
console.log(jax.responseText);
//it is not work
for(var i=0;i<JSON.parse(jax.responseText).length;i++)
{
setroute( eval('(' + jax.responseText + ')') );
}
}
catch(e){ alert(e); }
}}
}
Your JSON is not an array, but an object. If you want it to be an array, it should be something like this:
[
"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
]
Then, you can get a javascript array as follows:
var array = JSON.parse(jax.responseText);
And access values as follows:
array[0]
array.length
EDIT: In order to have a real JSON array with the PHP json_encode method, see this related question.
With this modification you will be able to use all the possibilities of JS array without workaround.
Objects in JavaScript don't have a .length property like Arrays do.
In ES5 you can do: Object.keys({}).length; // 0
The other solution would be to loop over all the properties of your object with a for .. in loop and count.
You can use the following code. It will produce your desired output 3
var test = {
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
var getLength = function(obj) {
var i = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)){
i++;
}
}
return i;
};
console.log(getLength(test));
For your first question, you should use Object.keys(item).length
To get the values of your object, you should iterate over it with a for loop:
for(var key in item)
{
var val = item[key];
}
var count = 0;
Object.keys(json).forEach(function (key) {
count++;
alert(json[key].start.lat);
});
alert(count);
Using jQuery
$(json).each(function() { count++; alert(this.start.lat); });
alert(count);

chrome.storage.local.get results in "Undefined" when called

I'm building a chrome extension, and I needed to save some data locally; so I used the Storage API . I got to run the simple example and save the data, but when I integrated it with my application, it couldn't find the data and is giving me "Undefined" result.
Here is my Code:
function saveResults(newsId, resultsArray) {
//Save the result
for(var i = 0; i < resultsArray.length; i++) {
id = newsId.toString() + '-' + i.toString();
chrome.storage.local.set({ id : resultsArray[i] });
}
//Read and delete the saved results
for(var i = 0; i < resultsArray.length; i++) {
id = newsId.toString() + '-' + i.toString();
chrome.storage.local.get(id, function(value){
alert(value.id);
});
chrome.storage.local.remove(id);
}
}
I am not certain what type of data you are saving or how much, but it seems to me that there may be more than one newsId and a resultsArray of varying length for each one. Instead of creating keys for each element of resultsArarry have you considered just storing the entire thing as is. An example of this would be:
chrome.storage.local.set({'results':[]});
function saveResults(newsId, resultsArray) {
// first combine the data into one object
var result = {'newsId':newsId, 'resultsArray':resultsArray};
// next we will push each individual results object into an array
chrome.storage.get('results',function(item){
item.results.push(result);
chrome.storage.set({'results':item.results});
});
}
function getResults(newsId){
chrome.storage.get('results', function(item){
item.results.forEach(function(v,i,a){
if(v.newsId == newsId){
// here v.resultsArray is the array we stored
// we can remove any part of it such as
v.resultsArray.splice(0,1);
// or
a.splice(i,1);
// to remove the whole object, then simply set it again
chrome.storage.local.set({'results':a});
}
});
});
}
This way you don't need to worry about dynamically naming any fields or keys.
First of All thanks to Rob and BreadFist and all you guys. I found out why my code wasn't working.
Storage.Set doesn't accept the key to be an 'integer' and even if you try to convert that key to be a 'string' it won't work too. So I've added a constant character before each key and it worked. Here's my code.
function saveResults(Id, resultsArray) {
var key = Id.toString();
key = 'a'.key;
chrome.storage.local.set({key : resultsArray});
}
function Load(Id) {
var key = Id.toString();
key = 'a'.key;
chrome.storage.local.get(key, function(result){
console.debug('result: ', result.key);
});
}

Categories

Resources