JQuery ajax post is empty on php remote server - php

When I run an ajax POST request on my localhost php server, $_POST array is filled. On a remote server the $_POST array is empty if I use google chrome, MS Edge; but $_POST is not empty on firefox.
When I investigated the HTTP Remote Address headers I noticed the following differences
in chrome --- Remote Address: 95.168.185.183:8080
in firefox ---Remote address:185.27.134.216:80
and if change the ajax call to type get, the code works well.
My ajax call looks like this:
$.ajax({
url: 'index.php/designer/ajax_add_template_to_cart',
type: 'post',
datatype:'json',
data:{
template_name : template_name,
size:size,
qty: 1
},
error: function(data) {
console.log(data);
},
success: function(data){
console.log(data);
},
});

Can you try by doing code sequence change in AJax request.
$.ajax({
url: 'index.php/designer/ajax_add_template_to_cart',
type: 'POST',
data:{
template_name : template_name,
size:size,
qty: 1
},
dataType:"JSON",
success: function(data){
console.log(data);
},
error: function(data) {
console.log(data);
},
});

//You must use valid URL
$.ajax({
url: 'index.php/designer/ajax_add_template_to_cart',
type: 'POST',
data: jQuery.param({ template_name: template_name, size: template_name ,qty:1}) ,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});

Related

$.ajax $_POST to php returns empty array [duplicate]

I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Base on lonesomeday's answer, I create a jpost that wraps certain parameters.
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
Usage:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
you can post data using ajax as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {
"name":"jonsa",
"e-mail":"qwerty#gmail.com",
"phone":1223456789
};
$.ajax({
type: 'POST',
url: '/form/',
data: Data,
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}

AJAX returning ERR_CONTENT_DECODING_FAILED 200 using Codeigniter

I have two AJAX requests on the same page sending data to a Codeigniter framework.
One sends a form of input fields containing shop opening hours. This functions correctly.
$(".hour-field").blur(function(){
$.ajax({
url:'<?php echo base_url(); ?>businesses/updatehours',
type: 'POST',
dataType: 'json',
data: $("#edit-hours").serialize(),
success: function(data){
console.log(data);
},
error: function(data){
console.log(data)
}
});
});
The other sends data from a radio input form. This one returns ERR_CONTENT_DECODING_FAILED 200
$(".image-selector").click(function(e){
$.ajax({
url:'<?php echo base_url(); ?>businesses/selectimage',
type: 'POST',
dataType: 'json',
data: $("#select-image").serialize(),
success: function(data){
console.log(data);
},
error: function(data){
console.log(data)
}
});
});
I have tried removing the 'dataType' without success.
There is seemingly no difference between the two but one is not working.
Add this code in your config file:
$config['compress_output'] = FALSE;
Enable gzip compression in php.ini:
zlib.output_compression=On

jQuery sometimes $_POST is empty

Sometimes i get report that in jQuery Ajax query $_POST is empty.
For example Google Chrome on OS X or Windows 7 Firefox sometimes the post is empty sometime it isn't.
I can't figure out what seems to be the problem
jQuery.ajax({
url: "ajax.php",
method: "POST",
data: {
jqueryAjaxPostData: JSON.stringify({
name: "gen",
id: 1
})
},
processData: true,
dataType: "json",
failure: function ()
{
alert("Ajax failure")
}
});
EDITED : There is PHP code
$post = Variable::toArray(json_decode($this->Http->post("jqueryAjaxPostData")));

how to add header while posting a url and raw data in php

i have to pass header information while posting a url and want to pass raw data in the url can any on help me on this
i have tried
function test(){
alert("test");
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("X-APIKEY", "y5q9q1at8u-1uf4bao2yq-bsjdj3gh1g-u9ymh1t2f8-tt85pn4r50");
},
url: "https://backoffice.hostcontrol.com/api/v1/domain-is",
data: {"domain": "mahrosh.com"},
processData: false,
success: function(msg) {
alert(msg);
$("#results").append("The result =" + StringifyPretty(msg));
}
});
}
its not returning me results
You can add header variables as per given in below described code
function test(){
alert("test");
$.ajax({
type:"POST",
headers: { 'X-APIKEY': 'y5q9q1at8u-1uf4bao2yq-bsjdj3gh1g-u9ymh1t2f8-tt85pn4r50'},
url: "https://backoffice.hostcontrol.com/api/v1/domain-is",
data: {"domain": "mahrosh.com"},
processData: false,
success: function(data) {
alert(JSON.stringify(data));
},
error: function(data){
alert(JSON.stringify(data));
}
});
}
If server gives error in response than you have idea about it so i added the error section as well ...

Ajax passing data to php script

I am trying to send data to my PHP script to handle some stuff and generate some items.
$.ajax({
type: "POST",
url: "test.php",
data: "album="+ this.title,
success: function(response) {
content.html(response);
}
});
In my PHP file I try to retrieve the album name. Though when I validate it, I created an alert to show what the albumname is I get nothing, I try to get the album name by $albumname = $_GET['album'];
Though it will say undefined :/
You are sending a POST AJAX request so use $albumname = $_POST['album']; on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.post('test.php', { album: this.title }, function() {
content.html(response);
});
and if you wanted to use a GET request:
$.ajax({
type: 'GET',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.get('test.php', { album: this.title }, function() {
content.html(response);
});
and now on your server you wil be able to use $albumname = $_GET['album'];. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false setting.
Try sending the data like this:
var data = {};
data.album = this.title;
Then you can access it like
$_POST['album']
Notice not a 'GET'
You can also use bellow code for pass data using ajax.
var dataString = "album" + title;
$.ajax({
type: 'POST',
url: 'test.php',
data: dataString,
success: function(response) {
content.html(response);
}
});
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});

Categories