Send one more parameter from serialize() - ajax

Into the "data" line of my AJAX code, I would like to send one more parameter (called "action") from serialize(). The 'data' line would look like this (obviously it doesn't work) :
$('.input_inscription').blur(function(){
var myInput = $(this);
$.ajax({
dataType: 'json',
type: "POST",
url: "my_url.php",
data:myInput.serialize()+"&action='input_control'",
success: function(data){
if (data.a == true){
$(".inscription_form_ctrl").text( data.b );
}else{
$(".inscription_form_ctrl").text( data.b );
}
}
});
});
Ps: I serialize a input field, not a form ! So i need to add the "action" parameter "manually" (it can't be a hidden input for example).

Could you share a little more of your code to get a clearer idea of what you are doing?
Anyway,
If you do wish to pass the data through the url, you might as well append the &action="input_control" to the form action attribute if you are using a form, like so
<form action="next.php?action='input_control'" method="POST" >

Related

Ajax link does not send POST request

I have the following ajax link:
#Html.AjaxActionLink(item.Name, "https://test.testspace.space/storage/Data/stream?tokenValue=e58367c8-ec11-4c19-995a-f37ad236e0d2&fileId=2693&position=0", new AjaxOptions { HttpMethod = "POST" })
However, although it is set to POST, it seems that it still sends GET request.
UPDATE:
As suggested below, I also tried with js functuion like this:
function DownloadAsset() {
alert("downloading");
$.ajax({
type: "POST",
url: 'https://test.testspace.space/storage/Data/stream?tokenValue=add899c5-7851-4416-9b06-4587528a72db&fileId=2693&position=0',
success: function () {
}
});
}
However, it still seems to be GET request. Parameters must be passed as query and not in the body of the request because they are expected like that by the target action. I don't know why (it would be more natural to have GET request) but back-end developer designed it like this due to some security reason.
If I use razor form like this, then it works:
<html>
<form action="https://test.testspace.space/storage/Data/stream?tokenValue=2ec3d6d8-bb77-4c16-bb81-eab324e0d29a&fileId=2693&position=0" method="POST">
<div>
<button>Send my greetings</button>
</div>
</form>
</html>
However, I can not use this because I already have bigger outer form on the page and I'll end up with nested forms which is not allowed by razor/asp.
The only way is to use javascript but for some reason it does not make POST request.
#Html.AjaxActionLink will generate to <a> tag,and tag will only have HttpGet request method.If you want to send HttpPost with <a> tag,you can use it call a function with ajax,here is a demo:
link
<script>
function myFunction() {
$.ajax({
type: "POST",
url: "https://test.testspace.space/storage/Data/stream",
data: { tokenValue: "e58367c8-ec11-4c19-995a-f37ad236e0d2", fileId: "2693", position:0 },
success: function (data) {
}
});
</script>
Since you want to make a POST request, but the values need to be as query string params in the URL, you need to use jquery.Param.
see https://api.jquery.com/jquery.param/.
You should set the params, like below :
$.ajax({
url: 'your url',
type: 'POST',
data: jQuery.param({ tokenValue: "your token", fileId : "2693", position: 0}) ,
...
Try this instead,
First remove the action url from the from
Second put the result in the success function to return response
and for parameters, I always use FormData() interface to post with Ajax
And last don't forget to include dataType, contentType, processData to not get an unexpected behavior
your code will look like this
var form_data = new FormData();
form_data.append('tokenValue' ,'add899c5-7851-4416-9b06-4587528a72db&fileId=2693');
form_data.append('position' ,'position');
$.ajax({
type: "POST",
dataType: 'json',
contentType:false,
processData:false,
data: form_data,
url: 'https://test.testspace.space/storage/Data/stream',
success: function (result) {
}
});

joomla token is not getting recognized by controllers method

I'm trying to set up a token on ajax post but is not getting recognized by the controllers method. The javascrip looks as it follows
jQuery(document).ready(function() {
jQuery('#source').change(function() {
jQuery('#fileupload').addClass('fileupload-processing');
var data = jQuery('#source option:selected').val();
jQuery.post('index.php', {
'option': 'com_tieraerzte',
'task': 'parser.importColumns',
'tmpl': 'component',
'token':'<?php echo JUtility::getToken()?>',
'app': data,
'dataType': 'html',
}, function(result) {
jQuery('td.add_column').html(result);
jQuery('button#parse.btn').show();
//edit the result here
return;
});
});
the token is getting generated and posted
in the controller I check the existance of toke but throws me Invalid Token
controller check toke
JRequest::checkToken('request') or jexit( 'Invalid Token' );
You're almost there, it's just a little mixed up. The Joomla! Form Token is generated and submitted as a input name with a value of 1. So, the token looks like this in your form:
<input type="hidden" name="1LKJFO39UKSDJF1LO8UFANL34R" value="1" />
With that in mind, when submitting via AJAX, you need to set the parameter name to your token name, with a value of 1. I accomplish something similar by just using the jQuery('selector').serialize() method:
Joomla.autoSave = function () {
jQuery.ajax({
url: "index.php?option=com_gazebos&task=product.apply&tmpl=component",
type: "POST",
data: jQuery("#product-form").serialize(),
success: function (data) {
console.log("autosaved");
}
});
};
Doing this pulls in all the form data (including the form token from the hidden input) and formats it as a query string, then sends it with the request. However, it seems to me that you might not want to do that and you are really only wanting to submit a single bit of data, not the whole form. So, let's rework your code a little bit to get the desired effect:
/**
* First, let's alias $ to jQuery inside this block,
* then setup a var to hold our select list dom object.
*/
jQuery(document).ready(function ($) {
var sourceSelect = $('#source');
sourceSelect.change(function () {
$('#fileupload').addClass('fileupload-processing');
/**
* Use the token as a parameter name and 1 as the value,
* and move the dataType param to after the success method.
*/
$.post('index.php',
{
'option': 'com_tieraerzte',
'task': 'parser.importColumns',
'tmpl': 'component',
'app': sourceSelect.val(),
'<?php echo JSession::getFormToken()?>': 1
},
function(result) {
$('td.add_column').html(result);
$('button#parse.btn').show();
//edit the result here
return;
},
'html'
);
});
});
Finally, this code is assuming you have this js code either in your view.html.php or in your views/parser/tmpl/default.php. If you have it in a separate .js file, then your php code won't execute and give you the token.
In your ajax call method use url as :
$.ajax({
url: '/index.php?option=com_itemreview&task=item.userReviewVote&<?php echo JSession::getFormToken(); ?>=1',
type: 'post',
data: {'data': submitvalue},
dataType: 'json',
success: function(response) {
}
});
for more information see here:
http://joomlabuzz.com/blog/27-preventing-cross-site-request-forgery-in-joomla
https://docs.joomla.org/How_to_add_CSRF_anti-spoofing_to_forms

How to send json data form jQuery?

I am trying to send JSON string
var json = {"city":value1, "country":value2};
$.ajax({
url : url,
data : json,
dataType : 'json',
success : function(response) {
alert(response);
}
})
In the URL to which I make ajax call I am not getting how to get this string value there? What should I use request.getParameter? What should be the value in the parameter?
Ajax request :
var jsonObj= { jsonObj: [... your elements ...]};
$.ajax({
type: 'post',
url: 'Your-URI',
data: JSON.stringify(jsonObj),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (data) {
...
}
});
on server side :
String city = request.getParameter("city");
String country= request.getParameter("country");
This might be a bad idea but has done the job. Thanks everyone for sharing your thoughts had hard time sending data. I saw all the suggested answers by #baadshah but, I couldn't implement a single one. :(. I reanalyzed the problem.
My problem is I can't retrieve the JSON data in the server side page where as I was able to access other elements. My HTML page had one of these
<input type = "text" name = "fname" class = "imp"/>
In my JSP page I could use
String fname = request.getParameter("fname");
After being stuck for more than couple of hours and getting frustrated I thought for another way. This is the solution I found. This problem would be solved if I can club the JSON string with any input tag with a valid name. The next moment I added this line in script tag
$('input[name=hide]').val(json);
var dataToBeSent = $("form#hidden").serialize();
In the HTML part I added following snippet.
<form name="hidden" id="hidden">
<input type="hidden" name="hide"/>
</form>
This solved my problem. This might not be the best way around but it did the job.
type: "POST"
should do the trick.

ajax request in jquery, data sent to the server not working

var p = JSON.stringify(parameter);
console.log(p);
$.ajax({
type: 'POST',
url: 'http://abc.com/ajax.php',
data: p,
success: function(status) {
console.log(status);
}
});
console.log(p) shows {"o_fname":"hh","o_lname":"jkhk","o_email":"uifh#bjvh.com","o_phone":"","b_name":"bmnbmbm,b","b_address":"","b_city":"","b_postal":"","b_phone":""}
but in my http://abc.com/ajax.php page print_r($_POST) is giving me an empty array Array()
var p = JSON.stringify(parameter);
That is your problem.
When you pass string data to .ajax, it sends it “as-is” – but PHP only popuplates $_POST if it receives data encoded as application/x-www-form-urlencoded.
So don’t make your data into a string, but pass your parameter object directly as value for data – then jQuery will take care of sending it the right way, so that PHP understands what it is supposed to do with it.
I think park of the problem may be that in data: you're passing the parameter details, but to the function on the other side of the jQuery you're passing a parameter name and nothing else.
Try:
$.ajax({
type: 'POST',
url: 'http://abc.com/ajax.php',
data: {parametername:p},
success: function(status) {
console.log(status);
}
});
With parametername replaced with the parameter name ajax.php is expecting.

CodeIgniter/Ajax - Send post values to controller

I'm working on a simple login form. When the user clicks on the Login button, I want to send the post values to my controller, validate them against my database (using a model) and return a value. Based on that value, I want to either send the user to the member area, or display an error message on my form. This error message has a class 'error' and is hidden by default. I want to use jQuery's show() to show it when the credentials are wrong.
My form has two textfields, one for the email address, other one for the password and a submit button. However, I have never really worked with Ajax except for VERY basic things like a simple loader, so I'm not sure what to do next.
$("#btn_login").click(
function()
{
// get values
var email_address = $("#email_address").val();
var password = $("#password").val();
// post values? and ajax call?
//stop submit btn from submitting
return(false);
}
);
I assume I have to use jQuery's ajax() method here, so I was thinking of working off this example:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
However, I'm not really sure how to get my post values (those two vars) in the data: thingy.. Or should I take another road here? This seems like something I'll never forget how to do once I learn it, so if someone can help me out I'd be grateful. Thanks a lot.
All you need to do is create a key/value pair with the values and assign it to the data parameter and jQuery will do the rest.
//create a js object with key values for your post data
var postData = {
'email' : email_address,
'password' : password
};
$.ajax({
type: "POST",
url: "some.php",
data: postData , //assign the var here
success: function(msg){
alert( "Data Saved: " + msg );
}
});
With this, you should be able to access the data with Codeigniters input
EDIT
I've set up a test fiddle here : http://jsfiddle.net/WVpwy/2/
$('#dostuff').click(function(){
var email_address = $("#email_address").val();
var password = $("#password").val();
var postData = {
'email' : email_address,
'password' : password,
'html' : 'PASS'
};
$.post('/echo/html/', postData, function(data){
//This should be JSON preferably. but can't get it to work on jsfiddle
//Depending on what your controller returns you can change the action
if (data == 'PASS') {
alert('login pased');
} else {
alert('login failed');
}
});
});
I just prefer .post, but what you used is an equivalent.
Basically your controller should echo out data. Not return. You need to send a string representation of your data back so your script can (evaluate if json) and act on it
Here's a good example as a starting point : http://www.ibm.com/developerworks/opensource/library/os-php-jquery-ajax/index.html
just modifiy a little bit the url of your ajax :
$.ajax({
type: "POST",
url: "some/myfunction",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Make sure your url point to the function you want inside your controller. For example: "myfunction" inside the controller some (in the file Some.php)
To access to your post variables inside the controller function do not try to put parameters to myfunction but :
class Some extends CI_Controller
{
......
public function myfunction()
{
$name = $this->input->post('name');
$location = $this->input->post('location');
}
......
}
You can definitely use your method, but a shorthand method is this:
$.post("some.php",{name:"John",location:"Boston",email:email_address,password:password},function(data,textStatus) { //response from some.php is now contained in data });

Resources