php update mysql ajax
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:
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:
Now to the problem, which is my ajax script:
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):
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.
В этом уроке мы наглядно проиллюстрируем, насколько просто получить доступ к информации из базы данных с помощью AJAX, мы собираемся создавать запросы MySQL на лету и отображать результаты в виде таблицы HTML.
Пример работы с Ajax, PHP и MySQL
В следующем примере показано, как веб-страница может получать информацию из базы данных с помощью AJAX. Вы можете из выпадающего списка выбрать одного из клиентов и увидите, что, без перезагрузки страницы, необходимая информация будет отображаться ввиде таблицы HTML:
Example
Таблица примера работы с Ajax и MySQL
В базе данных demo создадим таблицу ajax_demo:
Пример
Теперь выгрузите следующие данные в эту таблицу, используя следующие операторы SQL:
Пример
В результате мы получим следующую таблицу, которую будем исползовать в этом уроке:
Объяснение примера работы с Ajax и MySQL
Функция showUser() запускается событием onchange :
Пример
Сначала проверим, выбран ли человек из списка. Если никто не выбран (str == «»), то очистим содержимое элемента с и выйдем из функции. Если же человек выбран, то выполним следующие шаги:
Файл-обработчик для работы с Ajax и MySQL
Страница на сервере, вызываемая выше приведенным JavaScript, представляет собой PHP-файл «getuser.php».
Исходный код в файле «getuser.php» выполняет запрос к базе данных MySQL и возвращает результат в таблице HTML:
Пример
Объяснение кода: Когда запрос отправляется из JavaScript в файл PHP, происходит следующее:
Обновление записи в базе данных mysql\ AJAX формы
Re: Обновление записи в базе данных mysql
беда с тем, что у тебя получается всегда 1 submit на все
Re: Обновление записи в базе данных mysql
теперь изменил вывод, для каждой строки своя форма, но теперь id все время = 2. ничего не понимаю.
блин совсем старый стал, сразу и внимания не обратил, покажи что за яваскрипт функция sendRequest()
ну и какбы правильнее было бы:
Re: Обновление записи в базе данных mysql
Re: Обновление записи в базе данных mysql
Re: Обновление записи в базе данных mysql
как уже писал, изменил вывод данных. Сейчас выводится в каждой строке отдельная форма со своей кнопкой.
Если я понял он собирает данные во всех формах? а использует данные только у одной.
Фишка в том что когда был первый вариант, то он посылал значение а во втором варианте, где вывод в каждой строке отдельная форма, он посылает значение А почему так не могу понять.
Добавлено спустя 4 минуты 56 секунд:
Понял одно, что он собирает информацию только с первой формы, которая идет в начале кода, а все остальные он вообще не проверяет.
Ajax CRUD [CReate Update Delete] with PHP and MySQL database
In this tutorial, we create a basic commenting system consisting of a form with two input fields: name and comment. A user can add a comment on the page without the page reloading (using Ajax) and this comment is stored in the comments table in the database.
All comments in the database are displayed on the page and the user can delete a comment by simply hovering over it and clicking on the ‘x’ button that appears on the comment. This deletes the comment without reloading the page also.
This application requires only one database table. In this case, let’s just call the table comments.
So, create a database called ajax_crud. In that database, create a table with the following fields in it:
Next, we create the files of the project. We are going to create four files namely:
Now before we move on, there’s one more file we need to add. Ajax is a JQuery technology and so as you may have already guessed, we are going to need JQuery. Download JQuery from the JQuery website and add it in the root of your application.
Okay, so now in our application we have five files. They’re still empty, though.
Let’s code now, shall we!
Open the index.php file and place this code in it:
Nothing out of the ordinary right?
Just take note that we have included links to our styles.css, jquery.min.js (which was downloaded) and our scripts.js file.
Now open the styles.css file and paste this CSS code in it:
That’s it for the CSS. Now the scripts.
Open scripts.js and paste this code inside it:
The code in scripst.js above as earlier mentioned is the ajax calls that are made to the server.php file. The first piece of script sends a request with data to the server when a user clicks on the post button. The second sends a request having a comment_id so as to identify the specific comment in the database by that id and delete it.
For the server code, open server.php and paste the following code in it:
This brings us to the end of this tutorial.
Thank you for following this post. I hope it helped you. If you have any worries or comments, just drop them in the comments section below.
PHP MySQL Ajax Live Search
In this tutorial you’ll learn how to create a live MySQL database search feature using PHP and Ajax.
Ajax Live Database Search
You can create a simple live database search functionality utilizing the Ajax and PHP, where the search results will be displayed as you start typing some character in search input box.
In this tutorial we’re going to create a live search box that will search the countries table and show the results asynchronously. But, first of all we need to create this table.
Step 1: Creating the Database Table
Execute the following SQL query to create the countries table in your MySQL database.
Example
After creating the table, you need to populate it with some data using the SQL INSERT statement. Alternatively, you can download the prepopulated countries table by clicking the download button and import it in your MySQL database.
Please check out the tutorial on SQL CREATE TABLE statement for the detailed information about syntax for creating tables in MySQL database system.
Step 2: Creating the Search Form
Now, let’s create a simple web interface that allows user to live search the names of countries available in our countries table, just like an autocomplete or typeahead.
Create a PHP file named «search-form.php» and put the following code inside of it.
Example
Every time the content of search input is changed or keyup event occur on search input the jQuery code (line no-47 to 67) sent an Ajax request to the «backend-search.php» file which retrieves the records from countries table related to the searched term. Those records later will be inserted inside a
Step 3: Processing Search Query in Backend
And here’s the source code of our «backend-search.php» file which searches the database based on query string sent by the Ajax request and send the results back to browser.
Example
The SQL SELECT statement is used in combination with the LIKE operator (line no-16) to find the matching records in countries database table. We’ve implemented the prepared statement for better search performance as well as to prevent the SQL injection attack.
Note: Always filter and validate user input before using it in a SQL statement. You can also use PHP mysqli_real_escape_string() function to escape special characters in a user input and create a legal SQL string to protect against SQL injection.