jQuery and JSON: loop json array - javascript

I have an array in database:
a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}
So I unserialize with php and then encode it with json, code looks like following:
$unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
print_r ($unwp);
echo json_encode($unwp);
I get this on the page:
Array ( [1] => 1993 [2] => 1994 [3] => 1995 [4] => 1996 ) {"1":"1993","2":"1994","3":"1995","4":"1996"}
I need to loop it somehow with jQuery? so i can get 1993,1994,1995,1996 and so on.
I was testing jQuery.getJSON(), but cant figure out how exactly to use it?
All code together on the page:
<?php
$array = $_POST['inputarray'];
$str = serialize($array);
print $str . "\n";
$unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
print_r ($unwp);
echo json_encode($unwp);
?>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
jQuery(function ($) {
// Add children input fields
var childBlock = $('.block');
var countChildren = $('div.block div.row').size() + 1;
$('#addChild').live('click', function (e) {
e.preventDefault;
$('<div class="row"><input type="text" name="inputarray['+countChildren+']" id="inputarray'+countChildren+'" placeholder="inputarray['+countChildren+']">Delete</div>').appendTo(childBlock);
countChildren++;
});
$('#deleteChild').live('click', function (e) {
e.preventDefault();
if (countChildren > 2) {
$(this).parents('div.row').remove();
countChildren--;
var counter = 1;
$('input[name^="inputarray"]').each(function () {
$(this).attr('name', 'inputarray[' + counter + ']');
$(this).attr('placeholder', 'inputarray[' + counter + ']');
$(this).attr('id', 'inputarray' + counter);
counter++;
});
}
});
})(jQuery);
</script>
<form action="" method="post">
<div class="block">
<div class="row"><input type="text" name="inputarray[1]" placeholder="inputarray[1]"></div>
<input type="hidden" value="<?php echo $str; ?>">
</div>
<input type="submit">
</form>
Add a child
Thank you!

This could be done easily in PHP. Since I don't see any handlers for submit() or click() or anything that could suggest an ajax request.
And you also have the php in the same file, so why not simply loop with PHP and produce what you need?
echo "<select name='year'>";
foreach($unwp as $year) {
echo "<option value='{$year}'>{$year}</option>";
}
echo "</select>";
The above snippet will product exactly what you need.
Example
Edit
You're trying to generate a <select> right? If not, let me know so I can modify as required.

I would change
echo json_encode($unwp);
to
echo "<script> var fromPhP = ".json_encode($unwp). "</script>;
in this way you get json in variable and I saw you are using jquery so i would use $.each to loop it:
$.each(fromPhP ,function(index,item){
console.log(index,item);
});

Use $.getJSON like this:
$.getJSON("scriptname.php", function(data) {
html = '';
$.each(data, function(i, el) {
html += '<div class="block">' +
'<div class="row"><input type="text" name="inputarray['+i+']" placeholder="inputarray['+i+']"></div>' +
'<input type="hidden" value="'+el+'">');
});
$("form > div").delete();
$("form").prepend(html);
});

Related

Convert PHP variable to JQuery

Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery
View:
<?php
foreach ($muziek as $ms)
{
if ($ms->id == 2) {
echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
echo '</audio>';
}
}
foreach ($muziek as $ms)
{
echo '<br>';
echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
}
?>
</div>
<script>
$("input").click(function () {
var test = $(this).attr("id");
console.log(test);
//Here needs to be the foreach muziek
});
</script>
Muziek variable:
This is how i fill the music variable
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
return $muziek;
}
Does someone has an idea or show me how this can be done?
I spent sometime trying to figure out what you want and from what i understood you want to return an array of all muzieks returned to your js to do whatever you wanna do with it, which you can simply get with a simple ajax request:
$.get( "base_url/your_controller/getAllMuziek" )
.done(function( muziek ) {
//Here needs to be the foreach muziek
$.each(muziek, function( index, value ) {
// whatever
});
});
with a simple modification to your method getAllMuziek:
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
header('Content-Type: application/json');
echo json_encode($muziek);
}
now when you make you ajax call you will get your result.
Convert $muziek into javascript array using json_encode
<script>
var myArray = <?php echo json_encode($muziek); ?>;
</script>

ajax with multiple records to insert into database

I have a block of code which is a dynamically generated div with a form (based on array loop) that has dynamic inputs which are added by a button:
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
That code above is working and simply allows the '+' button to add a new input. I'm getting the input values as well as the tickerID from my hidden input in preparation for ajax submission. I'm getting what I expect from the serialized form but I have an issue.
The following code:
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serialize();
console.log(data);
});
</script>
Prints this:
Items%5B%5D=this&Items%5B%5D=is&Items%5B%5D=test&tickerID=1
Which I expect. The problem is that with my ajax call to my mysql insert function, I need to insert one record for each value plus the tickerID. My sql insert is inserting into columns tickerID and content. So for the above console.log, I would need the following insert:
tickerID | content
----------------------
1 this
1 is
1 test
How can I properly pass my form data to the ajax and then do something like a foreach in order to insert multiple records?
ajax call
<script type="text/javascript">
$("#Items").submit(function(e) {
$.ajax({
type: "POST",
url: addticker.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
addticker.php
$tickerID = $_POST[''];
$content = $_POST[''];
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$content');
"
$mysqlConn->query($addTicker)
Hope this works.
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}

PHP Variable inside PHP -> Echo -> Javascript

so I have issue I don't even know how to tell it. But here it is.
//Coupon Code?
if($row['coupon'] == null or $row['2email'] == 'Confirmed')
{
echo '<td>
<input type="text" onKeyup="trackChange(this.value)" id="myInput">
<script type="text/javascript">
var dID = <?php echo $dID; ?>;
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
function trackChange(value)
{
window.open("/functions.php?cCODE="+value+"&ccID="+dID)
}
</script>
</td>';
All I need is to get "user ID" from $dID=$row['ID']; but as it seems It just echo out that to the result and don't do any job. How can I get php variable inside php -> inside Echo -> inside Javascript.
I thought by going other way but I need text box and then submit to url. But I can't seem to get it working. Only 1 request at a time and I need 2. (User ID, and text to text box response)
echo " <td><form action= functions.php?cID= method= 'post'><input
type='hidden' name='cID' value=$dID />
<input type= 'submit' name= 'type' value= Confirm></form></td>";
So I can't get them both to submit that. Only found a way inside javascript.
Picture of text field
You'll want to use string concatenation (using the . character) to insert a variable into your string. Like this:
echo '
[...]
<script type="text/javascript">
var dID = ' . $dID . ';
function wait(ms){
[...]
';
A . will concatenate two strings together. For example:
echo 'hello ' . ' world'
You can also insert a variable directly into a string, if you use double quotes. Single quotes do not allow you to do this:
$text = "world";
echo "hello $text";
In general, you should wrap your variables in curly brackets ({ and })
$text = "world";
echo "hello {$text}";
You can just concatenate the variable there
To concatenate use .
if($row['coupon'] == null or $row['2email'] == 'Confirmed')
{
echo "<td>
<input type='text' onKeyup='trackChange(this.value)' id='myInput'>
<script type='text/javascript'>
var dID = '".$dID."'
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
function trackChange(value)
{
window.open('/functions.php?cCODE='+value+'&ccID='+dID)
}
</script>
</td>";

Ajax autocomplete doesn't return correct value

I have an ajax autocomplete where it returns the full name of the user. However, when there are instances where some names or values are the same, it doesn't return the correct value. Rather, it returns the first value in the dropdown. Even if it has 4 same occurences, it still returns the first value.
When I click Stannis Arryn Baratheon, it returns Stannis Targaryen Baratheon.
Here is my php code (sql/php code; ad.php):
<?php
include('config.php');
if($_POST)
{
if($_POST['search_keyword'])
{
$similar = mysql_real_escape_string($_POST['search_keyword']);
$result=mysqli_query($conn, "SELECT * FROM person WHERE (firstName like '" . $_POST["search_keyword"] . "%' OR lastName like '" . $_POST["search_keyword"] . "%') AND residentOrNot = 'Yes' ");
if (mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_array($result))
{
//$name = $row['fullname'];
//$copiedname = $row['fullname'];
//$b_name= '<strong>'.$similar.'</strong>';
//$final_name = str_ireplace($similar, $b_name, $name);
?>
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
<?php
}
}
else {
?>
<div class="show" align="left">
<span class="returnMessage">No matching records found.</span>
</div>
<?php
}
}
mysqli_close($conn);
}
?>
HTML input form:
<form method="post" action="try.php" name="try">
<div class='web'>
<input type="text" class="search_keyword" id="search_keyword_id" placeholder="Search" />
<input type="hidden" name="resID" id="resID"/>
<div id="result"></div>
<input type="submit" name="try" value="Submit">
</div>
AJAX/JS/JQUERY CODE (i think this is where the problem occurs):
<script type="text/javascript">
$(function(){
$(".search_keyword").keyup(function()
{
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='')
{
$.ajax({
type: "POST",
url: "ad.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}
return false;
});
jQuery("#result").on("click", function(e)
{
/*var $clicked = $(e.target);
var $name = $clicked.find('.returnName').html();
var decoded = $("<div/>").html($name).text();
$('#search_keyword_id').val(decoded);
var $clicked = $(e.target);
var $id = $clicked.find('.returnID').html();
var id = $("<div/>").html($id).text();
$('#resID').val(id);
*/
$name = $('span.returnName',this).html();
$name = $("<div/>").html($name).text().toString();
$('#search_keyword_id').val($name);
$id = $('span.returnID',this).html();
$id = $("<div/>").html($id).text().toString();
$('#resID').val($id);
});
jQuery(document).on("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search_keyword")){
jQuery("#result").hide();
}
});
});
</script>
It really returns the first value even if I click the second or third or fourth value. Where did I go wrong in my code? Please help me. Thank you so much!
Your code is currently collecting all elements with class returnName in #result, and by calling .html() on that collection jQuery will only return the html of the first element found. The same goes for the your returnID search. This is why you are only getting the first returned entry.
Modify your #result click handler to only trigger for elements with class show, since that is the element that will contain your data.
jQuery("#result").on("click", ".show", function(e){
Then all you have to do is search for the elements with class returnName and returnID and call .text().
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
So all together
jQuery("#result").on("click", ".show", function(e){
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
});
Though note there are probably better ways of returning your data, and utilizing it rather than transporting it in html elements. For example use data-* attributes instead of using a separate span element to contain your id.
Another option is to use jQuery-UI's autocomplete that does most of the client side work for you and just return the raw data in JSON format from your php script.
In your php code, change this:
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
With this:
<div class="show" align="left">
<span class="returnName" data-id="<?php echo $row['idPerson'];?>"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
</div>
And your new jquery function:
jQuery("#result").on("click","'.returnName" function(e)
{
var choosenName = $(this).html();
var choosenId = $(this).data('id');
$('#search_keyword_id').val(choosenName );
$('#resID').val(choosenId );
});

Can we put php in jquery code?

I want to use php script in jquery code. Here I put php script in my jquery but my jquery function is not working then. Is it right way to put php script in a jquery function.
<script type="text/javascript">
$(function() {
var count2=1;
$('a#addTelefono').click(function() {
count2 +=1;
$('<p><div style="float:left;width: 100%;"><select name="product_id[]" ><?php $sql=mysql_query("SELECT * FROM tbl_product"); while($res=mysql_fetch_array($sql)){ echo "<option value='".$res['id']."'>".$res['product_name']."</option>";}?></select><input type="text" name="discount[]" placeholder="discount ' + count2 + '" style="margin-left: 8px;" id="discount_' + count2 + '" />%<img src="images/cross.png"></div></p>').fadeIn("slow").appendTo('#extendTelefono');
i++;
return false;
});
//fadeout selected item and remove
$('.remove').live('click', function() {
$(this).parent().fadeOut(300, function(){
$(this).remove();
return false;
});
});
});
</script>
You have to make it in two steps and separate your php code from jQuery for readability :
$sql = mysql_query("SELECT * FROM tbl_product");
while($res=mysql_fetch_array($sql))
{
$contents .= "<option value='".$res['id']."'>".$res['product_name']."</option>";
}
$('<select name="product_id[]" ><?php echo($contents); ?></select> .....');
Also, be carreful of caracters you have in $res['product_name'] : It can fail if you have a quote in your product name (so you must escape it).
Moreover, mysql_* is deprecated, see mysqli_* or PDO.

Categories