Alex
Alex

Reputation: 65

jQuery $.post() a form with .serialize() / Where are my params in PHP?

I've got a html form and trying to send it with jQuery to a php script. In this script i am looking for the params.

$(document).ready(function(){
	
  $("#myselect").change(function(e){
    e.preventDefault();
    $.post("mypath/toscript/",$("#form").serialize(), function(data){
      alert(data);
    });
  });
	
});

I need all uri parts. So im fetching it with $_SERVER['REQUEST_URI'].

I am requesting something like this: mypath/toscript/?p1=A&p2=B&p3=C

When i type this URI in the browser it works like it should.

But with the jQuery above i am getting with $_SERVER['REQUEST_URI'] only mypath/toscript/ without params.

Using $_POST shows me the prams p1=A&p2=B&p3=C

So why? Where is the difference when doing a post with $.post() to typing it directly

Upvotes: 1

Views: 1606

Answers (4)

JBX9
JBX9

Reputation: 1

Use parse_str to parse your serialized POST data into an array.

// $_POST['form'] : "num=12&obj=3&obs=text"
$form = array();
parse_str($_POST['form'], $form);

// you get :
$int_num = (int) $form['num'];  // 12
$int_obj = (int) $form['obj'];  // 3
$str_obs = $form['obs'];        // "text"

A serialized form data is commonly used to update a database, so it's recommended to use POST vars.

Upvotes: 0

khaliq
khaliq

Reputation: 108

You have to provide serialize in formatted array way something like this

var data = $('#form').serializeArray();

$.post("mypath/toscript/",data , function(data){
    alert(data);
});

Upvotes: 0

santosh
santosh

Reputation: 787

In your case try this will solve your problem ..

$.get("mypath/toscript/",$("#form").serialize(), function(data){

GET - Requests data from a specified resource..

POST - Submits data to be processed to a specified resource..

from w3school

You should use GET where you're doing a request which has no side effects, e.g. just fetching some info. This request can:

Be repeated without any problem - if the browser detects an error it can silently retry Have its result cached by the browser Be cached by a proxy

Upvotes: 0

castletheperson
castletheperson

Reputation: 33496

POST doesn't use the request URL to send the query string like GET does. POST instead sends the query string in the HTTP message body. When you type the query string into the browser, you are using method GET.

Here is an article from W3Schools about it.

That doesn't mean you should switch to using $.get necessarily though. There are drawbacks to using GET over POST, such as having a length limit or being less secure. Read the article to learn more.

To fix your code, you will have to choose which HTTP method suites your needs, and then align the jQuery and PHP code so that they both use the same method.

Upvotes: 1

Related Questions