Send multiple AJAX data to PHP and update Mysql database - php

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.

Related

Populate a second dropdown menu from mysql

I have seen that some people asked before similar questions but none of them answers my problem.
I have a question regarding ajax and php. In both of them I am relatively beginner.
What I try to do is a so-called: chained select boxes. I want to have 2 dropdown menus. When I select a value from the first one, then the second dropdown menu it gets populated from a mysql database.
For this purpose I use jquery, ajax, php and mysql.
I was trying to find some examples online but all of them seem rather complicated to me (I guess cause I am beginner).
I decided to make something of my own but I got stacked. I am not sure if the logic is correct.
So here we go (I will include only relevant code here):
Using jquery I send an ajax request:
$("#loc").change(function(){
var val = ($('#loc').val());
$.ajax({
type:'POST',
url:'query.php',
data: {val:val},
success:function(response){
$("#x").html(response);
} });
});
"loc" is the id of the first dropdown menu. I get the value and I send it to query.php
query.php has the following lines of code:
<?php
include('connect.php');
$area = $_POST['val'];
$query ="SELECT DISTINCT activity FROM main ORDER BY 1 where n_city='$area'";
$result = mysqli_query($dbcon, $query) or die('no available data');
$options="";
while ($row=mysqli_fetch_array($result, MYSQLI_ASSOC)){
$activity=$row["activity"];
}
?>
Now I am trying to figure out two things. 1) What should I return in the success function so I get a form which is populated with the results from the query? 2) Second and most important, is my idea actually correct or there is some logical mistake that I am missing?
Thanks a lot.
Dimitris
The clean solution would be to return a JSON array containing all the options for the second dropdown. This can easily be done by creating a normal PHP array and then using json_encode(). You can loop over the result and create new options in your JS function.
It will definitely work like this. However, it might be worth taking the time to learn how to use one of the available solutions.

Jquery Autocomplete too slow

I have written this code what it does is if user types postcode or city name it fetches from database using like query now the problem is i have around 1260 records with two fields one is city and other is post code
SELECT code, area FROM post_codes WHERE code LIKE '$q%' or area LIKE '$q%' ORDER BY area LIMIT 4
i have read many questions posted by users and researched online as well but nothing works used query delay as well .i have even indexed both these fields in database as well .. its getting records too slow that is the first problem now my second problem is when user is in that text field for search and he presses tab he can bypass the search and write any invalid code he wants how to restrict that here is my code for reference.
$("#Postcode").autocomplete("get_codes2.php", {
width: 260,
queryDelay:0,
dataType: 'json',
parse: function(data) {
var array = new Array();
for(var i=0;i<data.length;i++)
{
array[array.length] = { data: data[i], value: data[i].areacode, result: data[i].areacode};
}
return array;
},
formatItem: function(row) {
return row.areacode;
}
}).result(function (){
I think Drupal's API search has a really nice approach to solving this problem. Their alternative to letting every incremental search hit the backend is to serve one big JSON file, which is used to autocomplete on client side.
In their implementation they're listening on the focus event for the search input, to fetch the JSON only when it's actually needed.

Jquery $.post to PHP script time lag

I have a PHP page with an unordered list. I have a some jQuery code that waits for a user to click on one of the items in the list:
$(function() {
$('li.large_box').css('cursor', 'pointer')
.click(function() {
$('#db_sections').empty();
var show_id = this.id;
$.post('get_section_dates.php', { show_id: show_id }, function(sections) {
$('#section_dates_feedback').html(sections);
});
});
});
When a user clicks on one of these items the jQuery code sends it's id to a php script that makes a database query and builds a dropdown list with the results:
if (isset($_POST['show_id'])) {
$show_id = $_POST['show_id'];
$result = mysql_query("SELECT `id`,`air_date` FROM `daily_show` WHERE show_id = '".$show_id."'");
echo"<div id='dates_select'>";
echo "<select id='date_select'>";
echo "<option value='0'>Choose a date</option>";
while ($query = mysql_fetch_assoc($result))
{
$id = $query['id'];
$air_date = strtotime($query['air_date']);
$date = date("M-d-Y \(D\)",$air_date);
echo "<option value='$id'>$date</option>";
}
echo "</select>";
echo "</div>";
}
The first time I click on one of the list items everything works quickly and the dropdown box comes out correctly. The problem is, when I click on the next list item, the code takes a few seconds longer to build the new dropdown list in place of the old one. Each new click on a different list item compounds the time it takes to build the dropdown list until it takes more then a minute each time.
The database table that it's querying is only 12 records long, and generally it's only returning 1 or 2 rows at the most.
I'm new to PHP/jQuery and was wondering if there was anything blatantly obvious in my code slowing this process down.
Thanks for taking a look at my problem!
you should consider optimizing your transport method as well as your JS that handles it.
First of all, your scripts are building "fat" every click. that is, there are excessive jQuery calls. you can optimize it into this:
$(function() {
//put into reference static elements
$db_sections = $('#db_sections');
$section_dates_feedback = $('#section_dates_feedback');
//delegate event to parent handler using .on()
$('the_containing_ul').on('click', 'li.large_box', function() {
$db_sections.empty();
$.post('get_section_dates.php', {
show_id: this.id
}, function(data) {
//callback
});
});
});
as for your PHP reply, you should at least use JSON for transport and not HTML to make it light. you can use json_encode to turn a PHP array to a JSON string for transport.
if (isset($_POST['show_id'])) {
$show_id = $_POST['show_id'];
$result = mysql_query(query_here);
$resultArray = mysql_fetch_assoc($result)
//do a little formatting before we send over
while ($resultArray){
$resultArray['air_date'] = date("M-d-Y \(D\)",strtotime($resultArray['air_date']));
}
echo json_encode($resultArray);
}
this will print the following JSON string which is better than printing HTML:
[
{"id":"1","air_date":"January 1, 12"},
{"id":"2","air_date":"January 2, 12"},
{"id":"3","air_date":"January 3, 12"},
... and so on
]
now, in the POST request, jQuery intuitively converts it into a JSON object which we can parse. you can now use it to generate your selectbox. this will be the callback:
function(data) {
//create a select and div, and append it to a div
$div = $('<div id="dates_select" />');
$select = $('<select id="date_select" />').appendTo($div);
//create options based on data and append to select
$.each(data,function(index,row){
$('<option />')
.attr('value',row.id)
.text(row.air_date)
.appendTo($select);
}
//put div into the feedback
$section_dates_feedback.html($div);
}
Sounds like a multiple binding issue to me. Just a guess, but maybe you are adding the click function to the clickable item each time the POST returns. So, the next time you click, it's going to run the POST twice. Then three times. That's adding a new request each time as well as adding redundant DOM manipulations each time.
However, the code as it looks in the sample isn't showing obvious signs of having the click bound again. So even though I have a suggestion, it's sort of a shot in the dark.
(Side note: there's no reason to add the CSS via jQuery here. Just put this rule into your style sheet! I've eliminated it from the sample)
Now, I don't know your markup, so I'm going to play safe and use document as my suggested listener to help avoid multiple binding. Basically, the first selector in here is ideally an actual node that never gets destroyed as part of the Ajax call. It's rendered on first page load and then never rendered again. You might use $('#someContainer').on( /* ... */) for example. I'll just use document.
$(function() {
$(document).on('click', '.large_box', function() {
/* all the stuff that should happen on click */
});
});
Now here's the truly important thing that you SEEM to be doing in your sample but may not be. This document ready function must be fired only once when the page first loads. A true document ready function as it was intended to be. Don't put it inside any functions that might get fired.
Quick way to tell if it's being bound multiple times is to open Firebug or Webkit Developer Tools... you'll see the POST HTTP requests. If multiple are getting fired for one click, just figure out why it's being bound again.

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