serialize ajax form php
Как принять serialize() в php?
Друзья, не могу принять serialize в php и распечатать массив. Дурь какая то.
В php принимал так
И дальше отправлял все работало, теперь когда появился массив многомерный, его оч сложно передать ajax в php, не получилось, несколько дней бился, поэтому решил использовать serialize
Все равно ничего не печатает 🙁
SagePtr, тут засада была еще вот в чем, без serialize не нужны были атрибуты NAME у INPUT, поэтому не приходило, теперь добавил, и в php распечатал var_dump(. ); теперь есть данные в ответе, в php значит тоже приходит, НО не могу отправить все равно 🙁 не уходит письмо, не понимаю, все работало без serialize, в php ведь ничего не изменил, теперь то если и поля опять есть, почему не работает 🙁
Отправляю так, без serialize все работало
Serializing and submitting a form with jQuery and PHP
I’m trying to send a form’s data using jQuery. However, data does not reach the server. Can you please tell me what I’m doing wrong?
JavaScript (in the same file as the above form):
Server side PHP (/getcontact.php):
Can you please tell me what I am doing wrong?
UPDATE
Checked var_dump($_POST) and it returned an empty array.
The weird thing is that the same code tested on my local machine works fine. If I upload the files on my hosting space it stops working. I tried doing an old-fashioned form without using jQuery and all data was correct.
I don’t see how this would be a server configuration problem. Any ideas?
8 Answers 8
You can use this function
return type is json
EDIT: I use event.preventDefault to prevent the browser getting submitted in such scenarios.
Adding more data to the answer.
dataType: «jsonp» if it is a cross-domain call.
beforeSend: // this is a pre-request call back function
complete: // a function to be called after the request ends.so code that has to be executed regardless of success or error can go here
async: // by default, all requests are sent asynchronously
cache: // by default true. If set to false, it will force requested pages not to be cached by the browser.
How do I PHP-unserialize a jQuery-serialized form?
14 Answers 14
Provided that your server is receiving a string that looks something like this (which it should if you’re using jQuery serialize() ):
. something like this is probably all you need:
$params should then be an array modeled how you would expect. Note this works also with HTML arrays.
The serialize method just takes the form elements and puts them in string form. «varname=val&var2=val2»
// You get any same of that
In HTML page:
on PHP page:
on this php code, return f1 field.
Why don’t use associative array, so you can use it easily
I don’t know which version of Jquery you are using, but this works for me in jquery 1.3:
I think you’re wrapping serialized form value in an object’s property, which is useless as far as i know.
This is in reply to user1256561. Thanks for your idea.. however i have not taken care of the url decode stuff mentioned in step3.
so here is the php code that will decode the serialized form data, if anyone else needs it. By the way, use this code at your own discretion.
The url post data input will be like: attribute1=value1&attribute2=value2&attribute3=value3 and so on
Output of above code will still be in an array and you can modify it to get it assigned to any variable you want and it depends on how you want to use this data further.
You just need value attribute name in form. Example :
Php get array, dont need unserialize 😉
My point here is that you will convert the serialized jQuery string into arrays in PHP.
Here is the steps that you should follow to be more specific.
Let me know if you need more clarifications.
I’m trying to learn how to make a registration form. I was getting an error message: «PDOException : SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘firstname’ cannot be null»
Someone told me I could fix it with AJAX, which is something I want to learn anyway. But I’m not sure what I’m doing.
First, I took the PHP code out of my main page (register.php) and put it in a new file (reg-code.php). Then I included reg-code.php in register.php.
Next, I put the following in the head section of register.php:
I fixed one syntax error, but I get another one on the line success: function() <
But I’m not even sure if I’m moving in the right direction. The tutorials are confusing.
This is the PHP code I put in a separate file:
Do I just have to figure out a syntax error, or do I need to go back to square one?
4 Answers 4
That error message means that the firstname variable is not being passed in properly. Make sure the name/id of your form field is indeed «firstname».
actually there is no problem with your procedure but
Use standard alert() function:
First of all, Ajax has nothing to do with that error you get! So you might wan’t to consider changing your title. But anyway.
The reason it says that the column cannot be null, is because that you have set that rule in your database, and if you removed that, i would just be a blank field.
Получение данных формы на jQuery
Статья, в которой рассмотрим различные способы простого извлечения данных из HTML формы. А именно познакомимся с тем, как это сделать с помощью метода each, а также методов jQuery специально предназначенных для этого. Объект FormData в данной статье рассматривать не будем.
jQuery – Получения данных формы с помощью метода each
Работу по извлечению данных c элементов формы посредством метода each рассмотрим на примере.
В минимальном варианте данная последовательность действий состоит из создания пустого объекта JavaScript, перебора элементов формы с помощью метода each и добавления в созданный объект данных соответствующих значениям определённых атрибутов ( name и value ) элементов.
При необходимости, после получения данных формы можно добавить различные проверки. Это предотвратит отправку не валидных данных на сервер.
Методы jQuery serialize и serializeArray оличаются друг от друга только форматом вывода данных. Метод serialize обычно применяется в том случае, когда результат (данные формы) необходимо положить в строку HTTP запроса. Метод serializeArray наоборот, используется тогда, когда результат, который он предоставил, как правило, ещё необходимо обработать.
Внимание: Методы serialize и serializeArray не сериализуют данные из элементов, которые используются для выбора файлов.
PHP код, обрабатывающий ajax запрос на сервере:
Вышеприведёный код просто формирует строку из данных формы на сервере, которая затем будет отправлена клиенту (браузеру).
Сериализация формы с помощью методов jQuery serialize и serializeArray