foreach equivalent of php in jquery? - php

Is there a foreach code in JQuery as in PHP?
I have a code in php,like
<?php foreach ($viewfields as $viewfield): ?>
if ("<?php echo $viewfield['Attribute']['required'];?>" == 'true') {
$("<span class='req'><em> * </em></span>").appendTo("#fb_contentarea_col1down21 #label<?php echo $viewfield['Attribute']['sequence_no']?>");
}
if (<?=$viewfield['Attribute']['type'];?> == 'text' || <?=$viewfield['Attribute']['type'];?> == 'date' || <?=$viewfield['Attribute']['type'];?> == 'number') {
$("<input id=input<?=$viewfield['Attribute']['sequence_no'];?> type= 'text' style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> ></input><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
else if (<?=$viewfield['Attribute']['type'];?> == 'textarea') {
$("<textarea style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> id=input<?=$viewfield['Attribute']['sequence_no'];?>></textarea><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
<?php endforeach; ?>
Is there any equivalent of foreach in Jquery? How can I accomplish this same functioality in jQuery?
EDIT 1:
I thought it worked but I get an error. The code and the error message is given below.
for (<?=$viewfield;?> in <?=$viewfields;?>) {
if ("<?=$viewfield['Attribute']['required'];?>" == 'true') {
$("<span class='req'><em> * </em></span>").appendTo("#fb_contentarea_col1down21 #label<?php echo $viewfield['Attribute']['sequence_no']?>");
}
if (<?=$viewfield['Attribute']['type'];?> == 'text' || <?=$viewfield['Attribute']['type'];?> == 'date' || <?=$viewfield['Attribute']['type'];?> == 'number') {
$("<input id=input<?=$viewfield['Attribute']['sequence_no'];?> type= 'text' style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> ></input><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
else if (<?=$viewfield['Attribute']['type'];?> == 'textarea') {
$("<textarea style= 'width:<?=$viewfield['Attribute']['size'];?>px' data-attr=<?=$viewfield['Attribute']['type'];?> id=input<?=$viewfield['Attribute']['sequence_no'];?>></textarea><br>").appendTo("#fb_contentarea_col1down21 #<?=$viewfield['Attribute']['sequence_no'];?>");
}
}
Error message:
syntax error
for( in Array)
Can someone help me..

The $.each function is similar.
It allows you to iterate arrays using a callback function where you have access to each item:
var arr = [ "one", "two", "three", "four", "five" ];
$.each(arr, function(index, value) {
// work with value
});
Maybe is useful to know, if you want to break the loop, you can do it with return false; or if you want to skip only one iteration (continue), you return true;

If you want to iterate an object, I would recommend the JavaScript variant:
for (var key in obj) {
alert(key + ': ' + obj[key]);
}
You can also iterate objects in jQuery like this:
Note! Doing this is pretty pointless unless you think this syntax is much simpler to maintain. The below syntax has much more overhead than the above, standard JavaScript, for-loop.
$.each(obj, function (key, value) {
alert(key + ': ' + value);
});
To iterate arrays, this is how you do it in standard JavaScript (assuming arr is the array):
for (var i = 0, l = arr.length; i < l; i++) {
alert(i + ': ' + arr[i]);
}
To do it in jQuery, you can do it like this:
$.each(arr, function (index, value) {
alert(index + ': ' + value);
});

There is jQuery.each.

Javascript supports the for(data in data_array) syntax. jQuery also has a $.each function (as already mentioned)

Jquery operating on selectors:
$('a').each(function() {
$(this).click(function(e) {
e.preventDefault()
var href = this.href;
open(href);
});
// operate on the anchor node.
});
jQuery direct $.each:
var a = ['one', 'two'];
$.each(a, function() {
alert(this)
});
JS: Vanilla for loop
for ( var i = 0, len = 10; i<l; ++i ) {
alert(i)
}
JS #2: vanilla for
var humanLimbs = ['arms', 'legs'];
for ( var limb in humanLimbs ) {
if ( humanLimbs.hasOwnProperty(limb) ) {
alert( limb )
}
}
Js #3: infinite loop
for (;;) { alert(1) } // dont try this :p

Related

How to Jquery foreach in the if controle

I'm returning an array. I don't want to ahve same elements. So how I make a if control?
$.each(data, function(v, k) {
if ( ) {
// İşlem
}
});
headers.forEach(function (header, i) {
if ( ) { // controle ???
}
});
I don't want another same element in array? .
try the following:
var result = []; // result array without duplicate
$.each(data, function(v, k) {
if ($.inArray(k, result) == -1) result.push(k);
});
Try the following function to get distinct elements in an array:
function getDistinctArray(arr) {
var compareArray = new Array();
if (arr.length > 1) {
for (i = 0;i < arr.length;i++) {
if (compareArray.indexOf(arr[i]) == -1) {
compareArray.push(arr[i]);
}
}
}
return compareArray;
}
You can pass the final array to this function before returning the array.

Dynamically load image with different GET parameters

I'm trying to load an image (created with PHP) with jQuery and passing a few variables with it (for example: picture.php?user=1&type=2&color=64). That's the easy part.
The hard part is that I've a dropdown which enables me to select background (the type parameter) and I'll have an input for example to select a color.
Here're the problems I'm facing:
If a dropdown/input hasn't been touched, I want to leave it out of the URL.
If a dropdown/input has been touched, I want to include it in the url. (This won't work by just adding a variable "&type=2" to the pre-existing string as if I touch the dropdown/input several times they'll stack (&type=2&type=2&type=3)).
When adding a variable ("&type=2" - see the code below) to the pre-existing URL, the &-sign disappears (it becomes like this: "signature.php?user=1type=2").
Here's the code for the jQuery:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url += "&type="+$(this).val();
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
Here's the code where I load the image:
<div id="loadsignature">
<div id="loadingsignature" style="display: block;"><img src="img/loading-black.gif" alt="Loading.."></div>
</div>
I don't know how more further I could explain my problem. If you have any doubts or need more code, please let me know.
Thank you for your help!
EDIT:
Here's the current code:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
function updateQueryStringParameter(uri, key, value)
{
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re))
{
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
}
else
{
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
</script>
EDIT2:
Here's the code for signatureload.php
<?php
$url = "signature.php?";
$count = 0;
foreach($_GET as $key => $value)
{
if($count > 0) $url .= "&";
$url .= "{$key}={$value}";
}
echo "<img src='{$url}'></img>";
?>
If I understood your question correctly, it comes down to finding a proper way of modifying GET parameters of the current URI using JavaScript/jQuery, right? As all the problems you point out come from changing the type parameter's value.
This is not trivial as it may seem though, there are even JavaScript plugins for this job. You could use a function like this and in your signature_type change event listener,
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re)) {
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
$('#signature_type').change(function () {
// Update the type param using said function
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
Here is a variant where all the data is keept in a separate javascript array
<script>
var baseurl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
var urlparams = {};
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
urlparams['type'] = $(this).val();
LoadSignature();
});
function LoadSignature()
{
var gurl = baseurl; // there is always a ? so don't care about that.
for (key in urlparams) {
gurl += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(urlparams[key]);
}
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(gurl, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
With this color or any other parameter could be added with urlparams['color'] = $(this).val();
Why don't you try storing your selected value in a variable, and then using AJAX post data and load image. That way you ensure there is only one variable, not repeating ones. Here's example
var type= 'default_value';
$("#signature_type").change(function() {
type = $(this).val();
});
then using ajax call it like this (you could do this in your "change" event function):
$.ajax({
type: 'GET',
url: 'signatureload.php',
data: {
user: <?php echo $_SESSION['sess_id']; ?>,
type: type,
... put other variables here ...
},
success: function(answer){
//load image to div here
}
});
Maybe something like this:
<script>
var baseUrl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(function(){
LoadSignature(baseUrl);
}, 1500);
});
$("#signature_type").change(function() {
var urlWithSelectedType = baseUrl + "&type="+$(this).val();
LoadSignature(urlWithSelectedType);
});
function LoadSignature(urlToLoad)
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(urlToLoad, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>

How to make simple php's foreach equivalent in Javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Loop through array in JavaScript
I want to make the equivalent of php's foreach in javascript. Because I don't really know the Javascript language, I'd like someone to rewrite this PHP code into the Javascript piece:
$my_array = array(2 => 'Mike', 4 => 'Peter', 7 => 'Sam', 10 => 'Michael');
foreach($my_array as $id => $name)
{
echo $id . ' = ' . $name;
}
Is that even possible to do in the Javascript language?
The closest construct is
a = { 2: 'Mike', 4: 'Peter', 7: 'Sam', 10: 'Michael' };
for(var n in a) {
console.log(n+'='+a[n]);
}
In JQuery, The $.each function is similar.
It allows you to iterate arrays using a callback function where you have access to each item:
var arr = ["one", "two", "three", "four", "five"];
$.each(arr, function(index, value) {
// work with value
});
For plain Javascript?
for (var key in obj) {
alert(key + ': ' + obj[key]);
}
For you exists two way.
First when data is in object (in example it is in my_list)
and second when data is exactly in array (in example it is my_array)
In any case you can use JavaScript For...In statement
Example:
<script type="text/javascript" charset="utf-8">
var data;
var my_list = {2:'Mike', 4:'Peter', 7:'Sam', 10:'Michael'};
var my_array = new Array();
my_array[2] = 'Mike';
my_array[4] = 'Peter';
my_array[7] = 'Sam';
my_array[10] = 'Michael';
data = '';
for(index in my_list) {
data += (index+'='+my_list[index]+"\n");
}
console.log(data);
data = '';
for(index in my_array) {
data += (index+'='+my_array[index]+"\n");
}
console.log(data);
</script>
In both cases console output will be:
2=Mike
4=Peter
7=Sam
10=Michael
Actually please read http://www.w3schools.com/js/js_loop_for_in.asp
See below url
foreach equivalent of php in jquery?
Or try it
If you want to iterate an object, I would recommend the JavaScript variant:
for (var key in obj) {
alert(key + ': ' + obj[key]);
}
You can also iterate objects in jQuery like this:
Note! Doing this is pretty pointless unless you think this syntax is much simpler to maintain. The below syntax has much more overhead than the above, standard JavaScript, for-loop.
$.each(obj, function (key, value) {
alert(key + ': ' + value);
});
To iterate arrays, this is how you do it in standard JavaScript (assuming arr is the array):
for (var i = 0, l = arr.length; i < l; i++) {
alert(i + ': ' + arr[i]);
}
To do it in jQuery, you can do it like this:
$.each(arr, function (index, value) {
alert(index + ': ' + value);
});

Javascript events - send values to database

I am having trouble sending data to the database. The values are being sent, but they are all going into the first drop zone field. And I need each dropzone value to go into the correct field in the database.
I've tried putting in different listeners & if statements in the javascript but it won't work for me.
the html:
<ul id="images">
<li><a id="img1" draggable="true"><img src="images/1.jpg"></a></li>
<li><a id="img2" draggable="true"><img src="images/2.jpg"></a></li>
<li><a id="img3" draggable="true"><img src="images/3.jpg"></a></li>
</ul>
//dropzones
<div class="drop_zones">
<div class="drop_zone" id="drop_zone1" droppable="true">
</div>
<div class="drop_zone" id="drop_zone2" droppable="true">
</div>
<div class="drop_zone" id="drop_zone3" droppable="true">
</div>
</div>
<button id = "post" onClick="postdb();">Post info</button>
the javascript:
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () {
return fn.call(el, window.event);
});
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();
var dragItems;
updateDataTransfer();
var dropAreas = document.querySelectorAll('[droppable=true]');
function cancel(e) {
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
function updateDataTransfer() {
dragItems = document.querySelectorAll('[draggable=true]');
for (var i = 0; i < dragItems.length; i++) {
addEvent(dragItems[i], 'dragstart', function (event) {
event.dataTransfer.setData('obj_id', this.id);
return false;
});
}
}
addEvent(dropAreas, 'dragover', function (event) {
if (event.preventDefault)
event.preventDefault();
this.style.borderColor = "#000";
return false;
});
addEvent(dropAreas, 'dragleave', function (event) {
if (event.preventDefault)
event.preventDefault();
this.style.borderColor = "#ccc";
return false;
});
addEvent(dropAreas, 'dragenter', cancel);
// drop event handler
addEvent(dropAreas, 'drop', function (event) {
if (event.preventDefault)
event.preventDefault();
// get dropped object
var iObj = event.dataTransfer.getData('obj_id');
var oldObj = document.getElementById(iObj);
// get its image src
var oldSrc = oldObj.childNodes[0].src;
oldObj.className += 'hidden';
var oldThis = this;
setTimeout(function () {
oldObj.parentNode.removeChild(oldObj); // remove object from DOM
// add similar object in another place
oldThis.innerHTML += '<a id="' + iObj + '" draggable="true"><img src="' + oldSrc + '" /> </a>';
// and update event handlers
updateDataTransfer();
function postdb(){
if (document.querySelectorAll('[droppable=true]')){
var dropDetails = oldThis.id + '=' + iObj;
$.post("a-2.php", dropDetails);
}
oldThis.style.borderColor = "#ccc";
}, 500);
return false;
});
and my php:
$sql="INSERT INTO table_answers (drop_zone1, drop_zone2, drop_zone3) VALUES ('$_POST[drop_zone1]','$_POST[drop_zone2]','$_POST[drop_zone3]')";
Any idea please?
var u = $('drop_zone1');
if(u){
$.post("post.php", y);
};
(I'm assuming this is jQuery.)
Add the # to the beginning of the selector: $('#drop_zone1');.
The jQuery resultset always evaluates to a truthy value. It's not clear to me what condition you're trying to validate here...
In the PHP code, you're creating the query in $sql2 in the first if, as opposed to $sql in the other two.
Edit - now that we know what you're trying to do in setTimeout, this simplified function should work:
setTimeout(function() {
oldObj.parentNode.removeChild(oldObj); // remove object from DOM
// add similar object in another place
oldThis.innerHTML += '<a id="' + iObj + '" draggable="true"><img src="' + oldSrc + '" /> </a>';
// and update event handlers
updateDataTransfer();
/*
this part has been removed, see edit below
var dropDetails = oldThis.id + '=' + iObj;
// now dropDetails should look something like "drop_zone1=img1"
$.post("post.php", dropDetails);
*/
oldThis.style.borderColor = "#ccc";
}, 500);
One more edit, to submit all the dropped elements at once:
function postdb() {
var postDetails = {};
var dropZones = document.querySelectorAll('[droppable=true]');
var allZonesDropped = true;
for(var ix = 0; ix < dropZones.length; ++ix) {
var zone = dropZones[ix];
var dropped = zone.querySelector('[draggable=true]');
if(dropped) {
var dropTag = dropped.id;
postDetails[zone.id] = dropTag;
} else {
allZonesDropped = false;
}
}
if(allZonesDropped) {
$.post("a-2.php", dropDetails);
} else {
alert('Not all targets have elements in them');
}
return false;
});
Just be careful where you place this function - your edited question has it in the middle of the setTimeout call, where it's definitely not going to work.
Regarding your PHP code: You should really learn about PDO or MySQLi and use prepared statements instead of blindly inserting user input into the query. If you care to learn, here is a quite good PDO-related tutorial.

PHP form to Ajax type

I have a standard form on poll.php:
<form method="POST" action="createpoll.php">
..blah...
</form>
Is there anyway to process the form without leading the user to createpoll.php, something like calling createpoll.php on submit?
This technology is called AJAX. With help of JAvaScript libraries it's become really easy to use it. You can use JQuery or Prototype. Search for AJAX submission. There are a lot of answers on this topic - i.e., stackoverflow questions.
For exapmle, using JQuery method ajax() it looks like this(JavaScript):
$.ajax({
type: "GET", // method - Get or Post
url: "cart.php", // Url to send data
data: { addproduct: productIDVal, isAjax: 'true'}, // Parameters
success: function(theResponse) {
// code to operate with response, if the request was succesful.
// It can be string or array.
}
});
A great, extremely easy way to use Ajax in your form can be found here: http://jquery.malsup.com/form/
This is a great tutorial that should help you get started:
http://onlamp.com/pub/a/onlamp/2005/05/19/xmlhttprequest.html
You're going to need to capture form submission with JavaScript, submit the data with XMLHttpRequest (XHR), and parse the response.
Courtesy of http://js.isite.net.au/snippets/form2obj
You can also find the obj2query function on the same site.
<form action="submit.here" method="POST" onsubmit="submit_via_xhr( this.method,
this.action, obj2query( form2obj( this ) ), successFunction ); return false">
function form2obj(theForm) {
var rv = {};
if (typeof(theForm) == 'string')
theForm = document.getElementById(theForm);
if (theForm) {
for (var i = 0; i < theForm.elements.length; i++) {
var el = theForm.elements[i];
if (el.name) {
var pushValue = undefined;
if (
(el.tagName.toUpperCase() == 'INPUT'
&& el.type.match(/^text|hidden|password$/i))
|| el.tagName.toUpperCase() == 'TEXTAREA'
|| (el.type.match(/^CHECKBOX|RADIO$/i) && el.checked)
){
pushValue = el.value.length > 0 ? el.value : undefined;
}
else if (el.tagName.toUpperCase() == 'SELECT') {
if( el.multiple ) {
var pushValue = [];
for( var j = 0; j < el.options.length; j++ )
if( el.options[j].selected )
pushValue.push( el.options[j].value );
if( pushValue.length == 0 ) pushValue = undefined;
} else {
pushValue = el.options[el.selectedIndex].value;
}
}
if( pushValue != undefined ){
if(rv.hasOwnProperty( el.name ))
if( rv[el.name] instanceof Array ) {
rv[el.name] = rv[el.name].concat( pushValue );
}
else {
rv[el.name] = [].concat( rv[el.name], pushValue );
}
else {
rv[el.name] = el.value;
}
}
}
}
}
return rv;
}

Categories