OwnurD
OwnurD

Reputation: 195

Error appears when post value to php by using ajax

I get an error while posting datas to php file. Codes below

$.ajax({
        type: "POST",
        url: url,
        data: "{'konuid='" + $('#step2-id').val() + "','kategoriid='" +$('#step3-id').val() +"'}",
        success: function(data){
            $('#form-sorular').html(data);
        },
        error: function(data)
        {
            alert(data.d);
        }
    });

I checked the value in php file which is coming from ajax, and values were empty.. What is wrong with this ajax.

Upvotes: 0

Views: 56

Answers (1)

John S
John S

Reputation: 21482

You are passing a JSON formatted string for the data value, but I am guessing your server code is expecting values as if you posted a form. So instead of a string that looks like this:

{'konuid='step2-id-val','kategoriid='step3-id-val'}

You should pass a string that looks like this:

konuid=step2-id-val&kategoriid=step3-id-val

But rather than concatenate the string yourself, you should set the data value to an object, and then JQuery will format the string for you:

data: {
    konuid: $('#step2-id').val(),
    kategoriid: $('#step3-id').val()
},

Note: JQuery will properly encode the values when it builds the string.


And since your ajax call apparently returns html, I suggest you include the dataType setting:

dataType: 'html',

Also, the signature of the error callback is:

function(jqXHR, textStatus, errorThrown)

Change the error setting to:

error: function(jqXHR, textStatus, errorThrown) {
    alert('Error: ' + textStatus + ', ' + errorThrown);
    alert('Response: ' + jqXHR.responseText);
}

Upvotes: 3

Related Questions