Sending additional variable to server with dataUrl - php

This should be a simple fix, but I just have not been able to find anything about it.
I am using both postData and editData to POST a variable to the server for form editing. This variable is used in a switch to select the appropriate function. This php contains ALL of the functions for the project. I want to avoid having many different php pages.
So all of that is fine, but I cannot find a way to do the same thing for dataUrl. The one lead I've been able to find is using ajaxSelectOptions, specifically the data option. If this is the appropriate way to go about this, what is the way to use it? Like this?:
ajaxSelectOptions:{
contentType: "application/json",
dataType:'json',
type:'POST',
action: function(){
return 'popCodeAdjust';
}
}

In general you can use data property of ajaxSelectOptions. The code cam look like
ajaxSelectOptions: {
type: "POST",
data: {
action: "popCodeAdjust";
}
}
or
ajaxSelectOptions: {
type: "POST",
data: {
action: function () {
return "popCodeAdjust";
}
}
}
See here or here.
The problem can be if you really need to send the data in JSON format. In the case you can need either to serialize the value of the parameter data (like JSON.stringify({action: actionValue})) or the value with parameter name (like action: JSON.stringify(actionValue)). See the answer which role play BodyStyle attribute (WebMessageBodyStyle.Wrapped, WebMessageBodyStyle.WrappedResponse etc) in WCF method in the case.
In jqGrid 4.4.2 or higher (see the answer, my pull request and the fix) you can use postData as function. You can define it either inside of ajaxSelectOptions
ajaxSelectOptions: {
contentType: "application/json",
dataType: "json",
type: "POST",
postData: function (rowid, value, name) {
return JSON.stringify({action: "popCodeAdjust"});
//or depend on the relinquishment of the server side
//return {action: JSON.stringify("popCodeAdjust")});
}
}
You can specify postData alternatively inside of editoptions (see here).

How about?
$.ajax({
type: 'POST',
url: 'url',
data: { varName: JSON.stringify(arrayValues) },
dataType: 'json',
success: function(msg) {...},
error: function(res, status, exeption) {...}
});
Server-side:
$var = json_decode($_POST['varName'], true);

Inside your grid setup it would be:
postData: { KeyName: KeyValue },
You will see this extra parameter go out with your POST.
The example below will set the postData value, (if it was to change) and then trigger a reload of the grid.
$('#gridName').jqGrid('setGridParam', { postData: { UserName: userName }).trigger('reloadGrid', [{ page: 1}]);

Related

Pass Boolean Values from Ajax to PHP

I've read a tonne of questions on the subject but none of them seam to solve my particular issue – I guess there's something wrong with the way I've formatted my array of objects in JS. Here's my Ajax function:
var marketing_prefs = [];
$('#save-marketing-prefs input').each(function() {
var tmp_array = {};
tmp_array['marketing_permission_id'] = $(this).val();
if ($(this).prop('checked')) {
tmp_array['enabled'] = 1;
} else {
tmp_array['enabled'] = 0;
}
marketing_prefs.push(tmp_array);
})
console.log(marketing_prefs);
$.ajax({
dataType: 'json',
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'acrew_save_mc_marketing_prefs',
marketing_prefs: marketing_prefs
},
success: function(response) {
console.log('#####', response);
},
error: function(response) {
console.error('!!!!!', response);
}
});
What I'm doing is looping through a simple form with three checkboxes and creating an array of objects which will then go off to Mailchimp. My data arrives intact but the problem is that my boolean values come over to PHP as strings. I've switched from using true and false which was coming over as "true" and "false", to using 1 an 0 but those come over as strings too.
I suppose I could loop through the data and build a new array in PHP but the data is so close to being correct when it arrives that it seems like it must be unnecessary.
How can I get my data over as non-strings?
POST data is sent as simple name=value pairs, there's no syntax to specify datatypes, and everything is parsed as strings.
You can call intval($_POST['marketing_prefs'][$i]['enabled']) to convert it to an integer.
Another option is to convert the marketing_prefs array to JSON.
$.ajax({
dataType: 'json',
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'acrew_save_mc_marketing_prefs',
marketing_prefs: JSON.stringify(marketing_prefs)
},
success: function(response) {
console.log('#####', response);
},
error: function(response) {
console.error('!!!!!', response);
}
});
Then in the PHP you can do:
$marketing_prefs = json_decode($_POST['marketing_prefs'], true);
Since, as Barmar stated, GET/POST can't specify data types (that's a rant in and of itself), one way would t be to cast it.
Very rough example:
var_dump((bool) <variable>);
The issue is if it's anything but 'true', 'empty' or I believe 0 it will return true. I'm in a hurry else I'd flush it out for you better.

jQuery send a query strings value as POST instead of GET

One of my php pages was changed to handle POST data (in order to accommodate a few form text fields), instead of GET (which was previously used).
So now, instead of if($_GET) { } it uses if($_POST) { }. They (team) wont allow both methods using ||.
I need to send a querystring to that same page using jQuery, but because of if($_POST) { }, it will not get through.
The querystring is formed from this : <i class="icon-hand remove" data-handle="se25p37x"></i>
I used to send it using jQuery ajax before, but that will not work now. Any idea how I can send it as POST?
$('.remove').live('click', function() {
var self = $(this);
var handle = $(this).data("handle");
if(handle) {
$.ajax({
type:"POST", // this used to be GET, before the change
url:"/user/actions/"+handle,
dataType:'json',
beforeSend:function(html) {
},
Just change type: "GET" to type: "POST" and add data parameter:
...
type: "POST",
data: $('form').serialize(), // OR data: {handle: $(this).data("handle")}
dataType: 'json',
...

dataType: "json" won't work

I'm trying to send back multiple variables from a php file to ajax using json in an array. The code in the php file works perfectly and does everything with my database like it should. But as soon as I add dataType: "json" in ajax, nothing happens in the php file anymore. I googled a bit and some people mentioned it could be a browser problem, but so far it doesn't work in either firefox, chrome or IE. I'm using the latest version of jQuery.
This is what happens inside php:
<?php
//Create variables and update database
echo json_encode(array("id" => "$realid", "un" => "$username", "date" => "$date"));
?>
And this is the ajax code:
.ajax(
{
url: 'UpdateComments.php',
type: 'POST',
dataType: "json",
data:
{
type: "add",
comment: $("#comment").val(),
id: videoID
},
success: function (data)
{
//Get the data variables from json and display them on page
}
});
I'm clueless on this, any advice would be greatly appreciated!
Common issue is that browser prints "something else" before JSON whether that is some readable or unreadable(invisible) char. Try doing something like this:
<?php
//at the very beginning start output buffereing
ob_start();
// do your logic here
// right before outputting the JSON, clear the buffer.
ob_end_clean();
// now print
echo json_encode(array("id" => $realid, "un" => $username, "date" => $date));
?>
Now, all supplement data (before JSON) will be discarded and you should have it working...
I believe if you use dataType you should be using contentType, "The official Internet media type for JSON is application/json".
.ajax(
{
url: 'UpdateComments.php',
type: 'POST',
contentType: "application/json",//note the contentType defintion
dataType: "json",
data:
{
type: "add",
comment: $("#comment").val(),
id: videoID
},
success: function (data)
{
//Get the data variables from json and display them on page
}
});
It's easy to forget about an echo or a var_dump() that you may have been using in the past to test how your script is working.
In my own script I had a var_dump(), which I had forgotten about, that wasn't using JSON_encode-ed text and sent plain text to the browser. This broke the dataType:"json" requirement and caused the success function not to work.
Took me a while to find the problem as I had ctrl+f(ed) for echo only and forgot about the vagabond var_dump().
printf is probably another suspect.
If you set the dataType in jQuery, that actually sets the Content-Type header attribute. Perhaps, in your PHP script you will need to declare this MIME type as accepted. Did you notice if the code even enters the PHP script when you make the request? I doubt it is a browser problem if it doesn't work in Firefox, Chrome or IE.
To gain a better perspective at your AJAX request, subscribe to the ajaxBeforeSend (not sure if the event name is right check jQ docs) event and log the xhr object.
I wouldn't use the dataType if it is causing you issues, also I've personally not used an object as the data value before maybe that has something to do with it?
Anyway I've tweaked the main ajax routine I hope this helps.
$.ajax(
{
url: 'UpdateComments.php',
type: 'POST',
data:
{
type: "add",
comment: $("#comment").val(),
id: videoID
},
success: function (response)
{
//Get the data variables from json and display them on page
var data = $.parseJSON(response);
alert(data.id);
}
});
Try defining the error handler as part of the $.ajax call
$.ajax({
...,
error: function(xml, error) {
console.log(error);
}
});
Then check your debugging console for any errors that can help you diagnose the problem.
$.ajax({
url: '/route/',
type: 'POST',
dataType: "json",
data:
{
type: "add",
comment: $("#comment").val(),
id: videoID
},
success: data => {console.log(data);}
});
<?php
ob_start();
ob_end_clean();
echo json_encode(array("id" => "$realid", "un" => "$username", "date" => "$date"));
?>

JQuery + Json - first steps with an example

I need (recently) to get an array from the server after an ajax call created by jquery. I know that i can do it using JSON. But i don't know how to implement it with JQuery (im new with JSON). I try to search in internet some example, but i didnt find it.
This is the code :
// js-jquery function
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
success: function(msg) {
// here i need to manage the JSON object i think
}
});
return false;
}
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo $linkspon;
}
in fact, i need to get the array $linkspon after the ajax call and manage it. How can do it? I hope this question is clear. Thanks
EDIT
ok. this is now my jquery function. I add the $.getJSON function, but i think in a wrong place :)
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
$.getJSON(url, function(data) { alert(data[0]) } );
}
});
return false;
}
Two things you need to do.
You need to convert your array to JSON before outputting it in PHP. This can easily be done using json_encode, assuming you have a recent version of PHP (5.2+). It also is best practice for JSON to use named key/value pairs, rather than a numeric index.
In your jQuery .ajax call, set dataType to 'json' so it know what type of data to expect.
// JS/jQuery
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
console.log(data.key); // Outputs "value"
console.log(data.key2); // Outputs "value2"
}
});
return false;
}
// PHP
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon["key"]= "value";
$linkspon["key2"]= "value2";
echo json_encode($linkspon);
}
1) PHP: You need to use json_encode on your array.
e.g.
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo json_encode($linkspon);
}
2) JQUERY:
use $.getJSON(url, function(data) { whatever.... } );
Data will be passed back in JSON format. IN your case, you can access data[0] which is "my";

Jquery, reading JSON variables received from PHP

Sorry if this is basic, but I have been dealing with figuring this out all day and have gotten to where I can do everything I need with Jquery and cakephp (not sure if cakephp matters in this or if its same as any PHP), I want to return a variable from a cakephp function to jquery, I had read about how to do it, like here:
the cakephp:
$test[ 'mytest'] = $test;
echo json_encode($test);
and the jquery:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
}
});
I just can't figure out how to get one or more variables back into usable form within jquery, I just want the variable so I can do whatever else with it, I've been looking at what I can find through searching but its not making it fully clear to me.. thanks for any advice.
The JSON variables are in the data variable. In your case, it'll look like this:
var data = {
myTest: "Whatever you wrote here"
};
... so you can read it from data.myTest.
(Not sure whether it's relevant but you can remove the http://localhost/ part from the URL;
AJAX does not allow cross-domain requests anyway.)
Your variables are in data.
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
var values = eval( data ); //if you 100 % trust to your sources.
}
});
Basically data variable contain the json string. To parse it and convert it again to JSON, you have to do following:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
json = $.parseJSON(data);
alert(json.mytest);
}
I haven't test it but it should work this way.
Note that when you specify dataType "json" or use $.getJSON (instead of $.ajax) jQuery will apply $.parseJSON automatically.
So in the "success" callback you do not need to parse the response using parseJSON again:
success: function(data) {
alert(data.mytest);
}
In case of returning a JSON variable back to view files you can use javascript helper:
in your utilities controller:
function ajax_component_call_handler() {
$this->layout = 'ajax';
if( $this->RequestHandler->isAjax()) {
$foobar = array('Foo' => array('Bar'));
$this->set('data', $foobar);
}
}
and in your view/utilities/ajax_component_call_handler.ctp you can use:
if( isset($data) ) {
$javascript->object($data); //converts PHP var to JSON
}
So, when you reach the stage in your function:
success: function(data) {
console.log(data); //it will be a JSON object.
}
In this case you will variable type handling separated from controllers and view logic (what if you'll need something else then JSON)...

Categories