Select <options> loaded by jquery not getting serialized - php

I have loaded a form. In the form there is a select area that when changed calls a ajax query to load and display a second level select area
$('.subjectareaid').change (function ()
{
var selected = $(this);
var ssindex = selected.closest("tr").index()+1;
var putid = '#subsub'+ssindex;
var pdata = 'subjectareaid='+selected.val();
$.ajax({
type : "POST",
cache : false,
url : "a_subsubject.php",
data : pdata,
success: function(data) {
$(putid).html(data);
$(putid).removeClass('hideme');
}
});
});
the a_subsubject.php file creates a list of options to be returned
<option value=".$row['subsubjectid']."> ".$row['subsubjectname']
The HTML that is modified is a table, and in the table are the rows. The row looks like:
$outline .= "<tr><td>".$oline."Question ".$k."</td><td valign=bottom><select name=dif[".$j."]>".$difsel."</select></td><td valign=bottom><select class=subjectareaid name=sub[".$j."]>".$subsel."</select></td><td valign=bottom><select class=hideme id=subsub".$j." value=subsub[".$j."]><option value=0></select></td></tr>";
where $oline is either blank or a section name, $k is the question number, $j is the index (1-54), $difsel is a select statement's options, $subsel is a select statements options and the third selection is set to a single option, and hidden with the hideme class. In addition it has a ID that allows it to have the HTML refilled with the options being returned by the a_subsubject.php ajax call.
All of this table is wrapped in a form
<form id=deform1>
When the form is submitted the following jquery is run:
var formser = $('#deform1').serialize();
var crud = "&crud=scd";
var scorecardid = '&scorecardid='+ escape($('input[name=id]').val());
var pdata = formser+'&action=cru'+crud+scorecardid;
This is then sent to an ajax routine with pdata being the data being passed to the CRUD program to update the database.
The result (as displayed from an alert) from making selection in all three select values for questions 1, 21 and 39, are: {the id=1 is a hidden field ignored by the receiving code as it is captured and sent as the scorecardid later in the post string}
id=1&dif%5B1%5D=0&sub%5B1%5D=2&dif%5B2%5D=0&sub%5B2%5D=0&dif%5B3%5D=0&sub%5B3%5D=0&dif%5B4%5D=0&sub%5B4%5D=0&dif%5B5%5D=0&sub%5B5%5D=0&dif%5B6%5D=0&sub%5B6%5D=0&dif%5B7%5D=0&sub%5B7%5D=0&dif%5B8%5D=0&sub%5B8%5D=0&dif%5B9%5D=0&sub%5B9%5D=0&dif%5B10%5D=0&sub%5B10%5D=0&dif%5B11%5D=0&sub%5B11%5D=0&dif%5B12%5D=0&sub%5B12%5D=0&dif%5B13%5D=0&sub%5B13%5D=0&dif%5B14%5D=0&sub%5B14%5D=0&dif%5B15%5D=0&sub%5B15%5D=0&dif%5B16%5D=0&sub%5B16%5D=0&dif%5B17%5D=0&sub%5B17%5D=0&dif%5B18%5D=0&sub%5B18%5D=0&dif%5B19%5D=0&sub%5B19%5D=0&dif%5B20%5D=0&sub%5B20%5D=0&dif%5B21%5D=3&sub%5B21%5D=4&dif%5B22%5D=0&sub%5B22%5D=0&dif%5B23%5D=0&sub%5B23%5D=0&dif%5B24%5D=0&sub%5B24%5D=0&dif%5B25%5D=0&sub%5B25%5D=0&dif%5B26%5D=0&sub%5B26%5D=0&dif%5B27%5D=0&sub%5B27%5D=0&dif%5B28%5D=0&sub%5B28%5D=0&dif%5B29%5D=0&sub%5B29%5D=0&dif%5B30%5D=0&sub%5B30%5D=0&dif%5B31%5D=0&sub%5B31%5D=0&dif%5B32%5D=0&sub%5B32%5D=0&dif%5B33%5D=0&sub%5B33%5D=0&dif%5B34%5D=0&sub%5B34%5D=0&dif%5B35%5D=0&sub%5B35%5D=0&dif%5B36%5D=0&sub%5B36%5D=0&dif%5B37%5D=0&sub%5B37%5D=0&dif%5B38%5D=0&sub%5B38%5D=0&dif%5B39%5D=2&sub%5B39%5D=3&dif%5B40%5D=0&sub%5B40%5D=0&dif%5B41%5D=0&sub%5B41%5D=0&dif%5B42%5D=0&sub%5B42%5D=0&dif%5B43%5D=0&sub%5B43%5D=0&dif%5B44%5D=0&sub%5B44%5D=0&dif%5B45%5D=0&sub%5B45%5D=0&dif%5B46%5D=0&sub%5B46%5D=0&dif%5B47%5D=0&sub%5B47%5D=0&dif%5B48%5D=0&sub%5B48%5D=0&dif%5B49%5D=0&sub%5B49%5D=0&dif%5B50%5D=0&sub%5B50%5D=0&dif%5B51%5D=0&sub%5B51%5D=0&dif%5B52%5D=0&sub%5B52%5D=0&dif%5B53%5D=0&sub%5B53%5D=0&dif%5B54%5D=0&sub%5B54%5D=0&action=cru&crud=scd&scorecardid=1
as you can see dif%5B1%5D=0&sub%5B1%5D=2&dif%5B2%5D=0&sub%5B2%5D=0 this shows that sub[1] has been set to 2. This caused subsub1 to get loaded with a set of select options and then shown. A select option was made (the second item) yet no subsub[1] is being captured by the serialize of the form data. [this was also done with record 21 and record 39].
Am I missing some way of "updating" the form prior to making the serialize to capture the third jquery added select values?

okay, the code is 300 lines in one file and 400 lines in another...
$outline .= "<tr><td>".$oline."Question ".$k."</td><td valign=bottom><select name=dif[".$j."]>".$difsel."</select></td><td valign=bottom><select class=subjectareaid name=sub[".$j."]>".$subsel."</select></td><td valign=bottom><select class=hideme id=subsub".$j." value=subsub[".$j."]><option value=0></select></td></tr>";
looks fine, but this one line of code has ONE error in it.
<td valign=bottom><select class=hideme id=subsub".$j." value=subsub[".$j."]><option value=0></select>
select statements don't have "value", they have "name".
25 hours of time wasted chasing down one bad line of HTML. Okay, I feel foolish. Hard to believe I wrote a bloody book on CGI programming for Prentice Hall back in 1997. I am so glad I use a anon handle and not my own name right now. :-)

Related

Send multiple AJAX data to PHP and update Mysql database

i am tying to build an application where user can reorder items (and save the order to database). The items user is reordering are navigation links, which are generated dynamically on the page from php loop:
$nav_links.='<li class="collection-item ui-state-default item" data-ord="'.$navorder.'" data-url="'.$pageurlname.'"><a>' .$pagename. '</a></li>';}
$navorder is order of the page in the navigation
$pageurlname is string which is used to call the page dynamically (index.php?page=$pageurlname) and is unique key in the table.
I am using jqueryUi sortable funcion to make the process drag & drop, it is working fine and each time i reorder the links, the new order is updated to "data-ord".. the sript:
$('#sortable').sortable({
stop: function(event, ui){
$(".sortable li").each(function(i, el){
$(el).attr('data-ord',$(el).index()+1);
});
}
});
Now to the problem, which is my ajax script:
$(document).on('click','.saveorder',function(){
var neworder = $('.collection-item').attr('data-ord');
var pgurl = $('.collection-item').attr('data-url');
$.ajax({
type:'POST',
dataType:'text',
url:'/rs/pages/nav_order.php',
data: { neworder:neworder, pgurl:pgurl },
success: function(data) {console.log(data); $('#response').html(data);},
error: function(data) {console.log('Error!', data); }
});
});
I am new to ajax, so it is mostly build on scripts i found in other quiestions here. (I was able to succesfully implement cript link this to my other functions) however it is not working in this case. The problem seems to be that i am trying to post multiple data for multiple rows (At this time i have 4 links i am trying to reorder, but the link count can be more or less). When i tried to get values of variables "neworder" and "pgurl" (using alert), it always show only the values for the first item.
I have tried lot of solutions found in similar quiestion but none of them worked, simply because user were posting form data and then serialized it, which is not my case because i am not sending data from the form.
Lastly here is the nav_order.php (i guess it is wrong here too, probably need to add foreach but at first i need to have the ajax working correctly):
<?php
include "/rs/include/db.php";
$neworder = $_POST['neworder'];
$pgurl = $_POST['pgurl'];
$query = mysqli_query($Connection, "UPDATE horus_pages SET nav_order='$neworder' WHERE url_name='$pgurl'") or die (mysqli_error($Connection));
echo 'Reordered';
?>
Also when i check the console, there is no data.
So please can you tell me how to correct the ajax script to send the data for each object and then handle it correctly in the php script? Hope i described my problem clearly. Thank you for any help.
Put data-id="your_database_id" in your links html. Selecting them in your database with href, will be slow and bug things if there are multiple records with the same href.
You have save button which sends the order and href of the first link it finds? And what happens when multiple items change their order? If you have many links, you will be throwing hundreds of mysql updates for each save?
You should be better off sending json to your php. Something like that:
[{id:123, order: 332}, {id:124, order:334}, ... ]
dataType:'text' becomes dataType:'json'
If you don't care about scalability, then this will work on the backend.
$data = file_get_contents("php://input");
$links = json_decode($data, true);
foreach($links as $link) {
$order = intval($link['order']);
$id = intval($link['id'])
// UPDATE table SET `order` = '$order' WHERE id = '$id'
}
Btw. Your php code allows SQL injection. Thats bad
Perhaps you can make the order 'float' and make an algorithm which finds empty spot. This will allow you to reduce these 100's of SQL requests to 1.

Jquery - How to call a function only if a new row is inserted in database

I have a div which contains comments for a post ... when user add a comment the div containing comments get updated immediately ( i have set a function which is called when user press enter )
Here Is my code for that :
$(document).on('keydown','.addComment',function(e){
var id = $(this).attr('id').match(/\d+/);
var p_id = Number(id);
var comment_box = '#comment_box_'+id;
var content = $(comment_box).text();
if (e.which === 13 && e.shiftKey !== true) {
content = content.replace(/\s\s+/g, ' ').replace(/\n/g, '<br>');
if (content.length > 0 ) {
$.ajax({
type : 'POST',
url : 'update.php',
data: ({
content: content,
id: p_id,
act: "add_cmnt"
}),
success : function()
{
update_ca("comment_area_"+id, true);
}
}); //End of Ajax
}
return false;
}
});
but a user logged in from another account must have to refresh the page to see new comments ... now what i want to do is that all users see the latest comments without refreshing the page i.e when ever a new comment is posted by any user the div containing comments should be updated ... now one way is to do this is that a function is called out after every 10 seconds which refreshes the div via ajax
Here is code :
setInterval(function(){update_comment_area();}, 10000);
this line of code refreshes the comment area after every 10 seconds but i want this function to be called only if a new row ( comment ) is inserted into a database
can anyone help me that how this can be done ??
Create a function that checks for a new row in the database i.e checkNew().
Then try:
if (checkNew()) {
refreshAjax();
}
Note: for the checkNew(), if a new record has been inputted, return true;
Else return false;
Here is a way to implement the checkNow():
Let it retrieve the value gotten from a PHP page that performs the SQL: SELECT lastupdated FROM commentTable ORDER BY id DESC LIMIT 1.
What that does is that it retrieves the last value in the commentTable which would obviously be the last inserted comment. Then update your page with intervals. The comment will continue to change as long as more comments are being added
Since it sounds like you already have an event for the submission of a comment, and assuming you're using javascript to push the comment to the server:
You can just use a callback and have it refresh then. Of course, that would only show up for the user that submitted the comment.
Example for that: JQuery Ajax calls with callbacks
Since you haven't mentioned your back-end coding language or database structure there are only a limited amount of suggestions I can give. However, one that would work would be to use AngularJS, or Socket.io to establish 2-way binding.
UPDATE:
Based on your code and how you're calling it I'm going to assume that update.php has the ability to know whether the record (comment) was added successfully. Once it's been added, have update.php set a global javascript variable to a new value (increment it, use a random number, doesn't matter as long as the value changes)
Then setup an object.watch() that will do your ajax call to update the comments when that variable changes. This is probably the simplest way to do it without using something like socket.io or angular.
How to use object.watch in javascript

Can MySQL query include HTML values?

REVISED QUESTION:
How can I reference a row of MySQL data while a form is being filled out. In other words, with my ('Select * FROM... how can I specify the row to pull the fields from without having to process the form to get the PHP fields?
Desired Process 1) User inputs first value, 2) Sidebar MySQL query looks up that value and fills div with data from that row, 3) User continues to fill out form while able to see div filed with MySQL data
ORIGINAL QUESTION:
I am curious if you can include a reference to an HTML input in a MySQL query.
Take the following for an example.
('SELECT * FROM MyTableName WHERE MyColumnID="MyHTMLInputValue"');
I would like to reference all the fields in the row based on the value of an input field and not sure of how to reference such a query.
Thank you!
Ajax is the way to go.
This example uses jQuery.
First we need to setup a php script to get our value and search for it, then return our data.
PHP myPhpScript.php
<?php
$search_value = $_POST["field1"]; //Get our value from the post.
//Make sure to do some authentication on the value so that bad values dont get through
$connection = new mysqli(Stuff here);
$rows = $connection->query(
"SELECT * FROM someTable where searchColumn LIKE %".$search_value."%"
);
//Now all we need to do is send out our data. Lets use json.
$out = $rows[0];//Get the first row. NOTE: Make sure to remove any columns that you dont want the client to see.
echo json_encode($out); //Send the client the data.
?>
Javascript Some script on the page.
var textbox = $("#mySearchBox"); //This is the jQuery object for our text box.
var viewbox = $("#myViewer"); //This is the jQuery object for the div that holds the results
textbox.on("input", function () {
$.ajax({
url: "myPhpScript.php", //This is the php script that we made above.
method: "POST", //This set our method to POST.
data: {field1: textbox.val()}, //set the textbox value to field1
dataType: "json", //So jquery formats the json into an object.
success: function (phpDataObject) { //Now its up to you to decide what to do with the data. Example below
viewbox.html("");//Clear the viewbox.
viewbox.append("Id: "+phpDataObject["id"]); //Show the id of row that was found.
}
});
});
This code may not work. Just fix whatever syntax errors that show up.
Hope this helps.
Comment if you need any more help.
This does not sound like a good idea. Usually you want some separation between your site and database. You could take in "MyHTMLInputValue", process it, then you can complete your query.
var myValue = MyHTMLInputValue;
//validate input
('SELECT * FROM MyTableName WHERE MyColumnID="' + myValue + '"')

display html select (from PHP) via jquery?

So I have a PHP backend that pulls some data from SQL, let's just say its a list of user ID numbers.
I want to be able to display that list in an html select, via jquery, after a button click.
In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery. Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.
How would you do it?
a fill-in-the-blanks code example follows:
idea 1:
function button_click() {
$.ajax({
url: "PHP_backend.php", // this does the sql query and returns the results
type: 'POST',
data: 'returnquery',
success: function(result) {
//????? put the result array or whatever into a submit, perhaps with a foreach or something similar..??
}
}); // end ajax
}
Or idea 2:
$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}
function button_click() {
/// create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}
if you are sure that the button will be clicked always or very most of time, idea2 is better becouse overhead of send/receive Ajax (trafic) and its delay (time) will be removed
if the web page is "public" (not for an intranet, behind a vpn), I strongly advise to not use any sql in jquery. It's simplistic to call the php ajax response file with arbitrary sql (ie what I want), and even modify anything in the data or database.

JQuery MySql update

im trying to adapt this little snippet:
$("#checkbox_id").change(function(){
/* CODE HERE */
});
I have a series of checkboxes that are dynamically generated and their id's are always like "hug3443" were "hug" is the column in the DB and "3443" is the unique id for each row.
My objective would be that every time the checkbox changes state to update it own state in the DB.
Can it be accomplished with jQuery?
Thank you.
I just found a script for this stuff and thought to post it here as I was checking this page a while ago until I finally came across to this script. Tested it and worked like a charm and I have inserted it in my coding library. Enjoy, folks.
http://www.jooria.com/Tutorials/ajax-20/jquery-live-checkbox-inputs-with-animation-effects-158/
Yes. Use live events to attach the change event handler to your checkboxes (so that dynamically added checkboxes will be handled also). Then simply do a AJAX request inside the event handler passing your script the new state and the name/id of the checkbox (you can then "parse" the id and column name in the script).
Not without a server side script that would deal with the data changes.
jQuery is a client side javascript framework and doesn't have direct access to mysql, which is a server side daemon.
Have a look into pairing jQuery with php and mysql.
Code in javascript you write with the use of jQuery is executed on the client-side in a browser. A solution is from your script to make a call to a server page that will execute a MySQL update . For example like this.
$("#checkbox_id").change(function(){
$.ajax({
type: "POST",
url: "/page-that/makes/update.php",
data: {param1:value1}
});
});
You should write some server-side code for managing database (php, ruby, whatever).
You should create something like API, which means, that server-side script needs to get some variables, which sended to it from clients (id's of rows, name and value of columns for example).
And after that you should write your jQuery frontend script, which will request server-side script for managing database tables. For requests you can use AJAX technology, something like this:
$.ajax({
url: 'http://somesite.com/path/to/server/side/script',
type : 'POST',
success: function (data, textStatus) {
alert('yahoo! we get some data from server!' + data);
}
});
You can get the value of the id of the checkbox using javascript you can then split the name into the field name and id value. For this example I've added a - into id to give a seperator
(I think you may need to use the click event rather than change, think change may only work for drop down menus)
$("#checkbox_id").click(function(){
var checkbox_id = $(this).attr("id");
var id_bits = checkbox_id.split("-");
// this would split hug-3443 into hug and 3443 setting id_bits[0] = hug and id_bits[1] = 3443
$.post("update,php",
{
row: id_bits[0],
id: id_bits[1]
}
);
});

Categories