Split values from a jQuery CSV from an AutoSuggest jQuery code - php

I am currently using - http://code.drewwilson.com/entry/autosuggest-jquery-plugin for an autosuggest on my site. I have limited the number of choices to 3.
This is the autosuggest code:
<script type="text/javascript">
$(document).ready(function() {
$("input[id=category]").autoSuggest("http://localhost:8888/bl/pages_mx/category_1.php",
{selectedItemProp: "name", selectedValuesProp: "value", searchObjProps: "name",
minChars: 1, matchCase: false, selectionLimit: 3});
});
</script>
The categories the visitor can choose is taken from a table within the MYSQL database. I can now successfully see the suggestions when I begin to type in potential categories!
The 2 values that are queried from the 'category' table are - category_ID and name.
My question is, once the user has chosen their 1,2 or 3 choices, how can I get the category_ID in 3 different variables in php, or in an array?
The closest I have got to help on their discussion forum is by using this code:
var arr = $(".as-values").val().split(",");
But from there, I have no idea how to implement this?
I have tried using an explode function to split the CSV using this:
<?php if($_POST['category_submit']){ ?>
<script type="text/javascript">
var arr = $(".as-values").val().split(",");
var exploded = arr.split(',');
var category_1=exploded[0];
var category_2=exploded[1];
var category_3=exploded[2];
print (category_1);
</script>
<?php } ?>
But nothing seems to print when I press submit?
Any help would be hugely appreciated.
Many thanks!
But nothing seems

First, it's important to write JavaScript when writing JavaScript. "Print" is not a valid line of JavaScript.
Second, when you call .split(), what you get is an array that's immediately indexable.
var arr = $(".as-values").val().split(",");
var category_1=arr[0];
var category_2=arr[1];
var category_3=arr[2];

Related

Why is AJAX only replacing my variable in some places?

I have the following AJAX code, which replaces anything with class "percentreplacer" with the data in the "Percent" column of the MYSQL database:
<script type='text/javascript'>
$(document).ready(function () {
$('#functionsquestionform2').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : "aplaygroundajaxtest.php",
type: "POST",
data: $(this).serialize(),
success: function (data) {
$(".percentreplace").text(data.percent);
},
});
});
});
</script>
In another part of my script, I have this snippet of PHP code:
<?php echo '<span class="percentreplace">'.$data['FunctionsPercent'].'</span>'; ?>
When I run the code, the AJAX code at the top successfully replaces the above span with the percent value stored in the database (such as "6").
Later on in my code, I try to set this percent as a variable with the JQuery script shown below:
<script type='text/javascript'>
$(function(){
var carouselbutton1percentage='<?php echo '<span class="percentreplace">'.$data['FunctionsPercent'].'</span>'; ?>' ....[cont'd]
Here, however, instead of replacing the entire PHP snippet with the percent (let's say 6), it sets the variable carouselbutton1percentage equal to <span class="percentreplace">6</span> I want the tags to get stripped here just like they did in the former. I'm guessing this has something to do with the quotes, but I've played around with it quite a bit and I can't figure out what to change.
Any help would be greatly appreciated!
Thanks
I might be missing something. But instead of storing a string 'that contains characters that look like PHP and jquery', I would think you want to actually update that html element, like you do in the AJAX response block. So..
$(".percentreplace").text('6');
or
var carouselbutton1percentage = 6;
$(".percentreplace").text(carouselbutton1percentage);
But again, maybe I'm misunderstanding.
I think you need to escape your string properly?
var carouselbutton1percentage='<?php echo \'<span class="percentreplace">\'.$data[\'FunctionsPercent\'].\'</span>\'‌​; ?>';

Onclick event update localhost database

I have a form with a table which has 5 rows and 8 columns. This table represents the available seats in a concert hall. After the submit button is clicked, a javascript function is called, which at the moment is this:
<script>
function submit_tickets(form){
var count=0;
var booked_seats=new Array();
var c = document.getElementById(form).getElementsByTagName('input');
for (var i = 0; i < c.length; i++) {
if (c[i].type == 'checkbox' && c[i].checked==true){
booked_seats[count]=c[i].id;
count++;
//create an array with the booked seats' ID
}
}
//alert(booked_seats.length);
} </script>
When this function is called, I want at the same time the table of the localhost database to be updated (a table which contains all the 40 seatIDs) depending on the seats that were booked.
How can I do this, can you help me?
if you'd like to i can write example in native javascript, but for now i'll try to do it using jQUery.
function submit_tickets(form){
var seats=[];
$(form).find("input:checked").each(function(){
seats.push($(this).val());//i hope you do have a value for your input tags, and if not, then push $(this).attr('id') - but highly recommend you to follow w3c
});
$.post("your/url/to/server",{seats:seats},function(data){
console.log(data);//some info from server
})
}
I believe you need to call a php file using PHP, in which the database update is done. You might consider using jquery ajax, as in http://api.jquery.com/jQuery.ajax/

Get just one of a divs IDS with jQuery

I have a div with more than one ID and I need to get each ID separately and send both variables off to a PHP file. I feel this would be the simpler option if achievable but the other option is to split the two IDS on the server side with PHP once the ID has been sent to it by jQuery. One ID is the timestamp the other the ID in the database.
HTML div example:
<div style="margin-bottom:10px;" id="1000003 2012-09-04 21:24:32" class="newsItem"></div>
The 1000003 is the ID i need to get into one separate variable and the rest is the timestamp I need in another separate variable.
The jQuery I have:
window.setInterval(function(){
//scripting here
var obj = $('.newsItem:first').map(function(_, elem){
return elem.id;
});
var ids = $.makeArray(obj); //variable of IDS
$.get("AJAX/get_feed_updates.php",{ ids: ids },function(result){
$("#newsFeed").html(result);
});
}, 5000);
The PHP file just puts the ID into a variable and queries the database with it.
Store one in the DATA attribute. Here is another reference to how its used.
Is this right?
window.setInterval(function(){
//scripting here
var theId = $('.newsItem:first').attr('id');
var a = theId.split(' ');
var theId = a[0];
var theStamp = a[1]+''+a[2];
$.get("AJAX/get_feed_updates.php",{ ids: theId },function(result){
$("#newsFeed").html(result);
});
}, 5000);
You should use data attribute. Then you can do something like this..
<div data-timestamp="1000003 2012-09-04 21:24:32" id="myId"></div>

I have a variable that i need to send to php to be written to a file

I have a specific array that php needs to access and write to a file. I also want to be able to call the php to get the array info back. I use JSON.strigify to store the array in a string, but i cant figure out how to send it to a server with php. I have very little php experience and i tried:
<script language="javascript">
var COMMENTS_FOR_DISPLAY = new Array('Have fun with this code: Chris');
// Adds a new comment, name pair to the Array feeding textualizer.
function add_comment() {
// Retrieve values and add them to Array.
var new_comment = $('#kwote').val();
var new_name = $('#name').val();
COMMENTS_FOR_DISPLAY.push(new_comment + ': ' + new_name);
// Reset <input> fields.
$('#kwote').val('');
$('#name').val('');
var arrayAsString = JSON.stringify(COMMENTS_FOR_DISPLAY);
}
$(document).ready(function() {
var txt = $('#txtlzr'); // The container in which to render the list
var options = {
duration: 5, // Time (ms) each blurb will remain on screen
rearrangeDuration: 5, // Time a character takes to reach its position
effect: 'random', // Animation effect the characters use to appear
centered: true // Centers the text relative to its container
}
txt.textualizer(COMMENTS_FOR_DISPLAY); // textualize it!
txt.textualizer('start'); // start
});
</script>
in main.php i put:
<?php
$kwoteString = $_GET["arrayAsString"];
echo $kwoteString;
?>
I used echo to see if i was getting any output,but i wasn't. It could be a very simple fix, maybe im missing a header or something telling my html document to read main.php?? any help would be appreciated!
Use jquery with
$.post(url,params);
there are many tutorials around the web and stack overflow itself.
Here the doc:
http://api.jquery.com/jQuery.post/
you can add a hiddenField and set the string to the hidden field.
php code will read the value from hidden field.

Move divtag and store position in mysql?

I want users on my website to be able to "move" div tags once they are 'unlocked' and then for a php script to store the positions in mysql database. So once the user re-logs in the div tags are positioned in the correct place.
I know how to postion div tags in css, and am using php varibles within css to pull the data from the database. I just dont know how to get the position of the div tag in order to store it? Maybe using ajax or something?
any ideas welcome, thanks.
What do you mean by position? Is it "left, right, center..." or the position in pixels?
If it's in pixels, just use the top and bottom css property. If it's a custom position, just do a callback when you change the position.
You can easily get the position using javascript and once you have it you want to save that asynchronously, so yeah ajax is nice. Look up jquery for that one: http://docs.jquery.com/Ajax/jQuery.post
$.post("test.php", { func: "getNameAndTime" },
function(data){
alert(data.name); // John
console.log(data.time); // 2pm
}, "json");
Also, from the way your formulated your question it looks that you don't have a lot experience with ajax. I suggest you look up some documentation online or find a nice book (search SO, there's a bunch of topics about this)
When the position of an element changes, you will want to post the pixel values to a PHP script using AJAX. Here is a brief example using jQuery...
function storeElementPosition(elem) {
var off = $(elem).offset();
$.post("storeElementPosition.php",
{ elem : $(elem).attr("id"), left : off.left, top : off.top },
function(resp) {
alert(resp);
}
);
}
Use jQuery, it'll make life a whole lot easier. ..
HTML:
Save
JavaScript:
$('#savelayout').click(function(){
var postData = {};
$('.xy').each(function(){
var id = $(this).attr('id');
var pos = $(this).position();
if (id && id.length){
postData[$(this).attr('id')] = pos.left.toString() + ',' + pos.top.toString();
}
});
$.post('savelayout.php', postData, function(data, textStatus){
if(textStatus == 'success'){
alert('Positions saved successfully.');
}
});
});
Replace .xy in $('.xy') with the CSS selector that will target all the elements you want saved. Once you do that, if you have two savable elements with with "divid1" and "divid2" id's, the data posted to PHP ($_POST) will look like this:
array(
'divid1' => '123,351',
'divid2' => '512,136'
);
You can then explode each string by the comma and grab each int as the x and y coordinate.

Categories