I am still new to cakephp, and my attempt is to retrieve the FormHelper's value and pass it via $.ajax() call in jquery. However, by cakephp convention, the name of each field generated by FormHelper will be in the format of data[Model][field]. Now, I want to submit $_POST data in form of cakephp array format. However, I couldn't find a way to do so, because I couldn't find a way to turn name and value attribute into a passable array format.
My attempt was to turn everything into string and try to create a json array. However, I failed to do so, and this method doesn't seem convincing to me too.
function submitEdit(sendurl, formid){
var dataset = [];
$('form#'+ formid + ' > input,select').each(function(){
dataset.push($(this).attr('name') + ':' + $(this).val());
});
alert(dataset);
$.ajax({
type: 'POST',
data: '{' + dataset + ']',
url: sendurl,
success: function(content){
$('.setting-preview.username').append('<pre>' + content + '</pre>');
}
});
}
Therefore, how do I pass this as data[Model][field] array to the sendurl controller?
Something like
$.ajax({
type: 'POST',
data: {
Model: {
foo: $('#ModelFoo').val(),
bar: $('#ModelBar').val()
}
},
url: sendurl,
success: function(content){
$('.setting-preview.username').append('<pre>' + content + '</pre>');
}
});
Related
I am using PHP and Ajax to parse some JSON. The PHP is creating the array like this.
$myObj->pid = $_POST["parentid"];
$myObj->comp = $comp;
$myObj->colour = $statuscolour;
$myJSON = json_encode($myObj);
header('Content-Type: application/json');
echo $myJSON;
I use the following jquery code
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var response = jQuery.parseJSON(JSON.stringify(msg));
console.log(response);
pid = response[0].pid;
console.log('id = ' + pid);
});
I can see the output from the first console.log as
Object {pid: "p1", comp: 20, colour: "red"}
However I cannot extract the individual variables, it gives the message
Uncaught TypeError: Cannot read property 'pid'
How can I extract the variable?
You've made this more complicated than it needs to be. msg is already an object, which you then convert to a string and back to an object with stringify and parseJSON. And then you try to use it like an array, when it is an object.
Try this:
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var pid = msg.pid;
console.log('id = ' + pid);
});
You are returning an object, not an array.
Also it makes no sense to stringify the data object and parse that string back to object again
Try
var pid = msg.pid;
console.log('id = ' + pid);
First of all, it can't imagine why it would be neccessary to first stringify, then parse the JSON response.
Second, you are trying to access response[0] as if it were an array, which it isn't. You can simply use
response.pid;
To access the object key.
As you don't need to stringify then parse the response, you can just access msg directly, so it all comes down to
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
console.log(msg.pid);
});
I'm working on one project with AngularJs(1.5) and Codeigniter rest server. I'm wondering why data idTag isn't passed to php? Let me show you my code and explain further with comments.
I have this factory
factory.get = function(idLocation, idTag){
console.log(idLocation, idTag); //Console log outputs 1 6, so data is here
return $http({
method: 'GET',
url: $location.protocol() + '://' + $location.host() + '/rest/api/locationtag/locationtag/' + idLocation,
data: {
idTag: idTag
}
}).then(function successCallback(response){
console.log(response);
// response is empty, because data isn't sent to PHP
return response.data;
},function errorCallback(response){
console.log('Error getting slide shows: ' + response.data.message);
});
};
And this is my PHP where i try to fetch the code
public function locationtag_get($idLocation)
{
$condition['id_location'] = $idLocation;
$condition['id_tag'] = $this->get('idTag');
var_dump($condition);
die();
$locationTag = $this->locations_tags->get($condition);
if ($locationTag) {
$this->response($locationTag, REST_Controller::HTTP_OK);
}
}
Out put of var_dump is
'id_location' '1'
'id_tag' null
SO the question, why or how to properly send data from GET method to PHP rest controller in Codeigniter?
If you need any additional information's, please let me know and i will provide. Thank you in advance!
For GET requests you should use params instead of data (which is for POST requests). You can confirm this in the AngularJS documentation.
params – {Object.} – Map of strings or objects which
will be serialized with the paramSerializer and appended as GET
parameters.
Of course, nothing stops you from adding them to the URL but you'd have to deal with encoding the information properly instead of just passing the JSON object.
You should be using a params property in your $http config object:
$http({
url: $location.protocol() + '://' + $location.host() + '/rest/api/locationtag/locationtag/' + idLocation,
data: {,
method: "GET",
params: {idTag: idTag}
});
This will append as query string to you url, which you can then inspect in your server side code.
I have a problem which is proving to be harder to find an answer for than I imagined. I am using AJAX to update the select options based on a response from another select box. I am able to correctly retrieve the right list of objects, serialized as json, but I can't access any of the field values of the object.
View:
def choose_group(request):
team_id = request.POST['team_id']
groups = WorkoutGroup.objects.filter(team_id=team_id)
data = serializers.serialize('json', groups)
return HttpResponse(data, content_type='application/json')
Javascript/jQuery:
$('#team').on('change', function(){
var team_id = $(this).val();
$.ajax({
type: 'POST',
url: '/create_workout/choose_group/',
dataType: 'json',
async: true,
data: { csrfmiddlewaretoken:'{{ csrf_token }}', team_id: team_id },
success: function(data) {
var groups = $('#group');
$(groups).children().not(':first').remove();
if (data.length >= 1){
$.each(data, function(group){
$(groups).append('<option value=' + group['fields']['id'] + '>' + group['fields']['group_name'] + '</option>');
});
}
}
});
})
I get an error with all the ways I've tried to access the fields of each object (such as the id and group_name of the objects, as defined in the model). The error is 'cannot read property of undefined'.
EDIT:
I have also tried just creating a ValueQuerySet and dumping it using simplejson, but I still cannot access any fields within, just 'undefined'. Also, if I alert through each group, I get just the index of the iteration within the group list.
New View:
def choose_group(request):
team_id = request.POST['team_id']
groups = WorkoutGroup.objects.filter(team_id=team_id).values('id','group_name')
#data = serializers.serialize('json', groups)
return HttpResponse(simplejson.dumps(list(groups)), content_type='application/json')
and my Javascript now looks like this:
$('#team').on('change', function(){
var team_id = $(this).val();
$.ajax({
type: 'POST',
url: '/create_workout/choose_group/',
dataType: 'json',
async: true,
data: { csrfmiddlewaretoken:'{{ csrf_token }}', team_id: team_id },
success: function(groups_list) {
var groups = $('#group');
$(groups).children().not(':first').remove();
if (groups_list.length >= 1){
//json = JSON.parse(data);
$.each(groups_list, function(group){
alert(group)
$(groups).append('<option value=' + group.pk + '>' + group.fields.group_name + '</option>');
});
}
}
});
})
Accessing the serialized django object
To access the serialized django object you need to first parse the data variable like this:
var obj = JSON.parse(data);
And then you can access the fields of each object Individually like this:
// for the first object
obj[0]['fields']['id'] // or obj[0].fields.id
obj[0]['fields']['group_name'] // or obj[0].fields.group_name
// for the second object
obj[1]['fields']['id'] // or obj[1].fields.id
obj[1]['fields']['group_name'] // or obj[1].fields.group_name
// and so on...
In your case you can do this:
$.each(obj, function(index){ // for each object
$(groups).append('<option value=' + obj[index]['fields']['id'] + '>'+ obj[index]['fields']['group_name'] + '</option>');
});
I have the following function:
function updateproductselectionxxx(form, productassignment, mainproductid, subprodqty) {
var checkingurl = "shopajaxproductselection.asp";
var pars = 'productassignment=' + productassignment + '&qty=' + subprodqty + '&mainid=' + mainproductid;
var url = checkingurl + '?' + pars;
var target = 'productselectionresult' + productassignment;
var myAjax = new Ajax.Updater(target, checkingurl, {
method: 'post',
parameters: pars
});
}
And I am currently in the process of converting all the javascript on this website to jQuery. Usually I can use something similar to:
function updateproductselection(form, productassignment, mainproductid, subprodqty) {
$.ajax({
type: 'POST',
url: 'shopajaxproductselection.asp',
data: $(form).serialize(),
success: function (response) {
$(form).find('productselectionresult' + productassignment).html(response);
}
});
return false;
}
And that does the trick, however I really only want to send over 1 field as indicated in the first function and I would also like to send along the information I am sending directly to the function upon it being called. JavaScript is definitely not my area of expertise but usually I can muddle through, but this time everything I have tried has caused errors and I'm not getting very far. Any help would be greatly appreciated.
Looks like a bit of confusion between POST and GET. Although the request method is set to POST in the older Prototype version the params are being sent via CGI which normally appear on the server as a GET. It's a bit hard to say more without seeing the server-side code, but you could try this, such that the jQuery version more closely mimics the old Prototype version:
function updateproductselection(form, productassignment, mainproductid, subprodqty) {
var checkingurl = "shopajaxproductselection.asp";
var pars = 'productassignment=' + productassignment + '&qty=' + subprodqty + '&mainid=' + mainproductid;
var url = checkingurl + '?' + pars;
$.ajax({
type: 'POST',
url: url,
data: {},
success: function (response) {
$(form).find('#productselectionresult' + productassignment).html(response);
}
});
return false;
}
Note that I have added a hash # to the start of productselectionresult - this is crucial due to the difference in the way PrototypeJS works. In Prototype, you can use an ID selector like:
$('id')
whereas in jQuery it has to be:
$('#id')
I'm got a form laid out like a spreadsheet. When the user leaves a row, I want to submit fields from that row to the server using jQuery Ajax. The page is one large form, so this isn't really a javascript clicking the submit button scenario - the form is huge and I only want to send a small portion of the content for reasons of speed.
I've got the code written that identifies the row and iterates through the fields in the row. My issue is how to build the dat object in order to submit something comprehensible I can disassemble and store at the server end.
At the moment my code looks like this
var dat=[];
$("#" + finalrow).find("input").each(function () {
var o = $(this).attr("name");
var v = $(this).val();
dat.push({ o: v });
});
$.ajax({
url: 'UpdateRowAjax',
dataType: 'json',
type: 'POST',
data: dat ,
success: function (data) {
renderAjaxResponse(data);
}
});
The assembling of dat doesn't work at all. So how should I build that dat object in order for it to "look" as much like a form submission as possible.
You can add the elements that contain the data you want to send to a jQuery collection, and then call the serialize method on that object. It will return a parameter string that you can send off to the server.
var params = $("#" + finalrow).find("input").serialize();
$.ajax({
url: 'UpdateRowAjax',
type: 'POST',
data: params ,
success: function (data) {
renderAjaxResponse(data);
}
});
You can use $.param() to serialize a list of elements. For example, in your code:
var dat= $.param($("input", "#finalrow"));
$.ajax({
url: 'UpdateRowAjax',
dataType: 'json',
type: 'POST',
data: dat ,
success: function (data) {
renderAjaxResponse(data);
}
});
Example of $.param(): http://jsfiddle.net/2nsTr/
serialize() maps to this function, so calling it this way should be slightly more efficient.
$.ajax 'data' parameter expects a map of key/value pairs (or a string), rather than an array of objects. Try this:
var dat = {};
$("#" + finalrow).find("input").each(function () {
dat[$(this).attr('name')] = $(this).val();
});