jQuery send a query strings value as POST instead of GET - php

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',
...

Related

Ajax variable ignores line breaks

I´ve got a problem when I try to send the value of a textarea through Ajax in Joomla.
The variable looks correct right before the ajax request. But when returned from helper.php, the success response var ignores all the line breaks.
My jQuery / Ajax:
var curBody = jQuery(this).closest("div").children("div").children('textarea').val();
//var curBody = curBodyVal;//.replace("/\r\n/","<br>");
console.log(curBody);
jQuery.ajax({
url: "index.php?option=com_ajax&module=usernotes&method=edit&format=json&Id="+edit_id+"&body="+curBody,
success: function( response ) {
console.log(response);
}
});
In my helper.php file at the function for the ajax call:
public static function editAjax()
{
$input = JFactory::getApplication()->input;
//$bodyToUpdate = $input->get("body", 'default_value', 'raw');
$bodyToUpdate = $_GET['body'];
return($bodyToUpdate);
}
Whenever you are trying to send values, which are not simple strings, send it ina a POST method instead of GET,
GET is used for simple strings, only used for characters within ASCII character range.
POST is used for any other complicated strings, you can send binary data as well, for example you can send files and images using POST method, but you cannot send using GET method
Change your ajax to this:
$.ajax({
method: "POST",
url: "index.php",
data: { option: "com_ajax", module: "usernotes" , method: "edit", format: "json" , Id: edit_id, body: curBody },
success: function( response ) {
console.log(response);
}
});

Why am I not receiving variable from JS to PHP?

I am trying to send a variable from JS to php through ajax but I'm not able to get in php file.
JS
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
PHP
print_r($_POST);
this is showing an empty array but when I do console.log(data) it shows an array in console.log
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function(data) {
console.log(data) ;
});
Edit: (by mega6382) I believe OP wants to open a page in browser with post params, which cannot be done by AJAX. All others who answered got mistaken by the AJAX code in the question and started providing AJAX solutions, without realizing what OP is trying to do. If you were to read OP's comments on Jeroen's answer.
The problem is with what you do when the ajax request finishes:
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
Here you are re-directing to http://localhost/test/ajax.php (requesting it a second time...), using a GET request so $_POST is indeed empty.
Just do the following in your php file to receive a json formatted string
echo json_encode(['success' => true]);
Instead of ajax try sending a dynamically generated form like:
var names = ['lee','carter'] ;
var newForm = $('<form>', {
'action': "http://localhost/test/ajax.php",
'target': '_top',
'method': 'POST'
});
names.forEach(function (item, index)
{
newForm.append($('<input>', {
'name': 'name[]',
'value': item,
'type': 'hidden'
}));
});
$(document.body).append(newForm);
newForm.submit();
This will send the values over POST via a form. It will do both redirect to the new page and send post vals.
Since you're using an AJAX request, in this case POST, you could use the _REQUEST method in php for obtaining the JS variable. In your case try:
$names = $_REQUEST['name']
echo $names;
/* Or try JSON_ENCODE if echo isn't working*/
$json = json_encode($names)
echo ($json);
var names = ['lee','carter'] ;
JSON.stringify(names);
$.ajax({
type: "POST",
dataType: 'json',
url: "http://localhost/test/ajax.php",
data: {name:names}
}).done(function() {
console.log('ok');
});
This is a successful ajax call. Now in order to "check by yourself" that is working you don't have to redirect to the other page because that way you refresh and lose the data. What you have to do is:
Open developer tab in your browser
Go to network tab
Locate your ajax call (it has the name of your php class that you do
the call)
go to response tab and there you have your php output
This link is to help you understand how to debug ajax call

Jquery/Ajax not getting input value from widget

Have a ajax request sending data to a WordPress action which works fine however I can receive the nonce value perfectly but the email input isn't being sent. I know I'm targeting the right value. It does not want to get the value of the email input. If I hardcode a value into the input it will see it. I need to get the user entered value and send that to the ajax script. The code is also run on document load and is after the form values have been rendered.
Input field looks like this:
<input type="email" name="cjd_email" id="cjd_email" class="cjd-email-input"/>
The jquery selector looks like:
var cjd_email = $('#cjd_email').val();
The ajax call is:
$.ajax({
url: cjdAjax.ajaxurl,
type: 'POST',
data: {
action: 'cjd_subscribe',
nonce: cjd_nonce,
email: cjd_email
},
cache: false,
success: function(data) {
var status = $(data).find('response_data').text();
var message = $(data).find('supplemental message').text();
if(status == 'success') {
console.log(message);
}
else {
console.log(message);
}
}
});
Thanks :)
I am assuming you are having a class on form i.e. cjdajax. Then use serialize method to send data instead of any other.
$.ajax({
url: cjdAjax.ajaxurl,
type: 'POST',
data: $('.cjdAjax').serialize(),
cache: false,
success: function(data) {
//your code
}
});
Depending on the browser you use, type=email might not be supported by jQuery / JavaScript and thus the valid() method could return rather strange values. As an alternative, one can use type=text with input validation.
Also, you should Review the success function : You attempt to apply the find()-method on text rather than a DOM element. The code could be corrected if the server returned a JSON-encoded string, so in JavaScript you could convert the string back into an object.
In PHP one could write print(json_encode($yourArray, true)); (notice how the true flag is required for associative keys), while
...
success: function(data){
var yourObject = JSON.parse(data);
if (yourObject.responseData === "success")
console.log(yourObject.message);
},...
could replace the respective current JavaScript passage.

Sending additional variable to server with dataUrl

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}]);

How to get the url for a ajax page?

I'm pretty new to ajax and I applied it succesfully to a Drupal site. But I was wondering, how do I get an URL to a page where part of the content is loaded through ajax. Is this even possible? The JSON object is retrieved on click, so how do I make it work when retrieving a certain URL?
I realize this is a very broad questionany, any help would be greatly appreciated.
Thanks in advance!
My JS looks like this:
Drupal.behaviors.ajax_pages = function (context) {
$('a.categoryLink:not(.categoryLink-processed)', context).click(function () {
var updateProducts = function(data) {
// The data parameter is a JSON object. The films property is the list of films items that was returned from the server response to the ajax request.
if (data.films != undefined) {
$('.region-sidebar-second .section').hide().html(data.films).fadeIn();
}
if (data.more != undefined) {
$('#content .section').hide().html(data.more).fadeIn();
}
}
$.ajax({
type: 'POST',
url: this.href, // Which url should be handle the ajax request. This is the url defined in the <a> html tag
success: updateProducts, // The js function that will be called upon success request
dataType: 'json', //define the type of data that is going to get back from the server
data: 'js=1' //Pass a key/value pair
});
return false; // return false so the navigation stops here and not continue to the page in the link
}).addClass('categoryLink-processed');
}
On the begining of the page load ajax based on hash part of the url page#id,
$(document).ready(function() {
$.ajax({
type: 'POST',
url: "/path/to/page",
success: updateProducts,
dataType: 'json',
data: 'id=' + window.location.replace(/.*#/, '')
});
$('a.categoryLink:not(.categoryLink-processed)', context).click(function () {
$.ajax({
type: 'POST',
url: "/path/to/page",
success: updateProducts,
dataType: 'json',
data: 'id=' + this.href.replace(/.*#/, '')
});
});
Or you can use jquery-history but I didn't test it.
I don't know what exactly you are trying to do. But unless you have a module that creates the JSON data you need to do it yourself.
You would need to create a menu callback with hook_menu. In the callback function you can return json data by using drupal_json.
If you create the menu callback etc yourself, the URL will be whatever you make it to. Else you just have to use the URL defined by the module you want to use.

Categories