Trouble Accessing Ajax POST variable on Codeigniter end - javascript

I'm using jquery to make ajax calls. Basically I don't know how to access the data I'm sending to the server with a post request. I don't know what the variable is called or... something. I don't know!
Ajax functions:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = JSON.stringify({
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
});
return ajax_client(base_url+'ajax_port/gather_records', json);
}
Codeigniter Function:
public function gather_records()
{
$data = json_decode($this->input->post('ids'));
log_message('debug', $data);//null
return json_encode($data);//null :(
}
I'm having no trouble receiving data back from the server here (and accessing with jQuery), my problem is that I can't get the data I'm sending to codeigniter. I'm developing on MAMP if that makes any difference.
I've tried other variable names like,
$this->input->post('data');
$this->input->post('json');
None seem to work.
Thanks very much for any help I can get!

You don't need to do JSON.stringify({..
just pass an object, and everything will be fine. I mean:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = {
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
};
return ajax_client(base_url+'ajax_port/gather_records', json);
}
One more thing. You don't need to json_decode it in your PHP side. Because default contentType in jQuery is 'application/x-www-form-urlencoded; charset=UTF-8'
Change line
$data = json_decode($this->input->post('ids'));
to
$data = $this->input->post('ids');
But if you really want to send JSON, you can add contentType
return $.ajax({
url: url,
type: 'POST',
data: json,
contentType: 'application/json',
dataType: 'json'
});
dataType you have set is "The type of data that you're expecting back from the server." (http://api.jquery.com/jquery.ajax/)

Related

Jquery ajax call wrong payload

I have some troubles whit jquery ajax call, infact I tried to perform a post call passing like data a string variable:
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: myVar,
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
If I inspect the http call I can see that the payload is:
'Hello': ""
I don't know how it is possible and how fix the problem.
jQuery, by default, will put a Content-Type: application/x-www-form-urlencoded header on data it sends via Ajax.
You, however, are passing a plain text string.
You need to either change the Content-Type to match the data you are sending or the data you are sending to match the Content-Type. (Or you could change both).
The important things are:
The data and content-type need to match
The server needs to be able to handle data in the format you are sending
So you might:
$.ajax({
type: 'POST',
url : 'https://...',
data: myVar,
contentType: 'text/plain'
// ...
})
or, since jQuery will encode objects as URL encoded data:
$.ajax({
type: 'POST',
url : 'https://...',
data: { myVar },
// ...
})
or, if you want multipart data:
const data = new FormData();
data.append('myVar', myVar);
$.ajax({
type: 'POST',
url : 'https://...',
data,
contentType: false // XHR will read the content-type from the FormData object (which it needs to do in order to determine the boundary paramater), putting 'false' here stops jQuery overriding it
// ...
})
or, for JSON
$.ajax({
type: 'POST',
url : 'https://...',
data: JSON.stringify(myVar), // This will be a JSON text representing a string
contentType: 'application/json'
// ...
})
i think you are passing payload in the wrong formate.
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: {
'name':myVar
},
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
On the server side you will get the value in the key 'name' you can fetch the value using 'name' key.

Ajax: How to send FormData inside of json object

To give you a better understanding consider my ajax request:
$.ajax({
url: '{% url "validate-upload-single" %}',
type: "POST",
data: JSON.stringify({
'mainForm': Myform,
'currentForm': 1,
}),
dataType: 'json', // response type
Where:
var Myform = new FormData( $(this)[0] );
The problem is that when i send the request, i get back an empty 'dict' on the server side. Im using Django as my backend
DJANGO VIEW:
print('SORTING THE POST REQUEST')
body = request.body.decode('utf-8')
serialized = loads(body)
print(f'POST: {request.POST}')
print(f'Body: {body}')
print(f'Serialized: {serialized}')
RESULT:
SORTING THE POST REQUEST
POST: <QueryDict: {'{"mainForm":{},"currentForm":1}': ['']}>
Body: {"mainForm":{},"currentForm":1}
Serialized: {'mainForm': {}, 'currentForm': 1}
I've tried $("form").serializeArray() but this only return text data, files seem to be missing
I guess the problem is with contentType header - it should be 'multipart/form-data'. Check this link to make it work with jQuery.ajax
In the .js file you HAVE TO add the fist block of csrf token for properly working.
//Getting csrf token
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Then you use json in you ajax, getting the template that you want to display by variable here "html_form":
// Submit post on submit
$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!") // sanity check
//Send data to server for getting back sorted
$.ajax({
url: '/schedule/sort_group/',
async: true,
type: 'post',
data: { //data sent with the post request
group_field_value: $("#select_group").children("#group-option:selected").val(),
lector_field_value: $("#select_lector").children("#lector-option:selected").attr("name"),
},
dataType: 'json',
success: function (data) {
$("#change_by_select").html(data.html_form);
}
});
});
In the views.py file at the bottom you need to determine the data like that:
data['html_form'] = render_to_string('schedule/select_sort.html', context,
request=request)
return JsonResponse(data)
So I suggest the information that you want to retrieve from the server put into the particular another file, whatever it would be (dictionary or lists or other data structures or html templates).
I hope it would help. Feel free to ask any questions.

Why is my JQuery variable not sending to php?

I have a variable which contains data, i'm then using a ajax function to send this variable data to this php file. I'm slightly unsure I can store this variable into php and echo it out. This is the code that I currently have...
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: data,
success: function(data) {
alert ( data );
}
});
This is my php code
$noteone = $_POST['data'];
echo $noteone;
Any help would greatly be appreciated
data of your ajax call should be like below. Hope it will solve your problem.
data: { "data": data }
You also need to set the data type:
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: { "data": data },
dataType: "json", // <---- THIS ONE
success: function(data) {
alert ( data );
}
});
Try this :
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: JSON.stringify(data),
contentType: "application/json",
success: function(data) {
alert ( data );
}
});
PHP requires data to be submitted in key=value format when building $_POST/$_GET. You didn't do that. You only submitted value, so PHP has no key to populate $_POST with. You need to have:
data: { "whatever_you_want": data }
which becomes
$_POST['whatever_you_want']

JQuery, Ajax and PHP : Sending FormData AND String values

I'd like to send to a PHP page a FormData value and some String values.
Here's my code on the JS side:
$.ajax({
url: 'upload-pic.php',
type: 'post',
data: {
type : type,
id : id,
formData : formData
},
processData:false,
success: function(data, status) {
//stuff i'm doing with the data
}
});
And on the PHP side :
if(isset($_POST['type']) && isset($_POST['id'])){
//stuff i'm doing
}
Then, I get an error saying that type and id are not set. I'm guessing that this comes from the processData: false from my ajax call.
But without this, I get the inevitable Illegal Invocation, coming from trying to send the FormData.
Is there any way to send the FormData AND my String values on the same call ?
Thanks!
I assume you are using the FormData object, in that case you need to append the string values to the FormData object, and pass the object in as the data parameter in jQuery's $.ajax.
You can append data to the FormData object, with the method append.
This should work:
formData.append('type', type);
fromData.append('id', id);
$.ajax({
url: 'upload-pic.php',
type: 'post',
data: formData,
processData:false,
contentType: false,
success: function(data, status) {
//stuff i'm doing with the data
}
});

ajaxSubmit not posting to full url

what am trying to do is submit a form using ajaxSubmit as follow :
$("#login").ajaxSubmit({
url: "index.php?page=login",
type: 'post',
success: function(responseText){
alert(responseText);
}
});
but instead of posting the data to index.php?page=login it post it to index.php which result in wrong response , how I supposed to fix that?
A normal POST request shouldn't include a query string. If you need pass some data, you have to use the "data" option.
data: { page: 'login' }
Take a look at this post, I think it will help you do what you're looking for. Basically you can't add the query string to the url, but you can add it to the data
Adding query string to Ajax url call
Use serialize: http://www.w3schools.com/jquery/ajax_serialize.asp
$("#login").submit(function() {
var url = "path/to/your/index.php";
$.ajax({
type: "POST",
url: url,
data: $("#login").serialize(),
success: function(data)
{
alert(data);
}
});
return false;
});

Categories

Resources