CodeIgniter - jQuery, JSON, simple example not working - ajax

Ok, Im a real newbie when it comes to ajax and json ... Im trying to figure it out in my codeigniter project.
Ive written something simple to start, just to bring up an alertbox, but it doesnt seem to be working, if someone could let me know where im going wrong, that would be grand.
In my view i have the following code.
$('.users').change(function(){
$.ajax({
type: "POST",
url: "/edituser/returndata",
data: {id: this.find(':selected').val()},
dataType: json,
success: function(data){
alert(data);
}
});
});
in the edituser/returndata controller, i just simply have the following
function returndata(){
echo $_POST['id'];
}
I know this will look pretty stupid to some people, but im still trying to figure it out, if someone could help :)
Cheers
----------------- UPDATED CODE BELOW
<script type="text/javascript" charset="utf-8">
$('#users').live('change', function(){
$.ajax({
type: "POST",
url: "/edituser/returndata",
data: {id: $(':selected', this).val()},
dataType: 'json',
success: function(data){
alert(data.id);
}
});
});
</script>
Controller code
function returndata()
{
$ID = $this->input->post('id'); // Use this instead of $_POST['id']
echo json_encode(array('id'=>$ID));
}

Your dataType should be:
dataType: 'json',
Your data should be:
data: {id: $(this).find(':selected').val()},
Inside of a event callback, this is a DOM element, so it needs to wrapped in $().
or:
data: {id: $(':selected', this).val()},
Which is the same as above, just less characters.
Also, in your PHP, you need to output JSON.
function returndata(){
$ID = $this->input->post('id'); // Use this instead of $_POST['id']
echo json_encode(array('id'=>$ID));
}
Then in your success function, you can do:
alert(data.id);

UPDATE
Disregard the answer. I thought the JSON was sent as a string, but it's not, as pointed out by Rocket. It is converted to url encoded value pairs. I'm leaving the answer up just in case someone thought the same thing as me....
The incoming JSON is not a request parameter, you need to read the body of the request
$json = json_decode(trim(file_get_contents('php://input'));
$id = $json->id;

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

Ajax serialise - issue with data format

I have several inputs formatted with this jquery plugin here.
I use $.ajax to do my mysql insert:
$.ajax({
type: 'GET',
url: 'xxxx.php',
data: $('#new_form').serialize(),
}),
I face an issue as my input values are formatted with the plugins and can't get into mysql db.
As an example:
Input value: $450,000.00 is not accepted.
Is there a way to unformat within the serialise function values that have a specific classes (like class="money")?
Thanks for your help!
I have tried the below code:
$.ajax({
type: 'GET',
url: 'xxx.php',
data: $('#new_form').serialize(),
dataType:"json",
beforeSend: function(){
$(".money").cleanVal();
},
<script>
function cleanVal(v) {
return v.replace(/^\,/,'');
};
</script>
the result of the insert in mysql is still 450 for 450,000.
Do you have an idea?
thanks
You can try using the plugin $.cleanVal() method to retrieve the unmasked type value of the corresponding HTML element, prior to your AJAX form submission. So something like this:
$.ajax({
type: 'GET',
url: 'xxxx.php',
data: $('#new_form').serialize(),
beforeSend: function(){
$(".money").cleanVal();
}
}),
I couldn't make it work with beforehand. I found a solution which is to unmask values before calling ajax.
If anyone knows why it does not work with beforesend, thanks for letting me know.
cheers

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.

How do I use data passed back in the response from ajax jQuery?

I am trying to use the response from a jQuery ajax request to set the innerHTML of a div with a certain id. This is the code I am using:
$(".show_comments").click(function(){
var articleName = $(this).closest("article").find(".articlename").attr('id')
$.ajax({
url: "commentView.php",
data: { 'articleName': articleName },
cache: false,
dataType: "html", // so that it will auto parse it as html
success: function(response){
$(this).closest("article").find(".comments").html(response);
}
});
however it doesn't seem to be doing anything at all, I've tried googling around, but everything I can find says to do it the way I am doing it... I have tested in Firebug and the ajax request is giving me the exact response I want it too... But I just cant access this to set the innerHTML of the div to the response!
In your ajax success handler there is another scope and this points to not what you think. So change your code to:
var articleName = $(this).closest("article").find(".articlename").attr('id'),
that = this;
$.ajax({
url: "commentView.php",
data: { 'articleName': articleName },
cache: false,
dataType: "html", // so that it will auto parse it as html
success: function(response){
$(that).closest("article").find(".comments").html(response);
}
});
What I've changed: I added that variable that points to this instance and use it in the success handler instead.
How would you debug it yourself: if you tried to output console.log(this) and console.log($(this).closest("article").find(".comments")); you would see that it returns a wrong object (in first case) and nothing in second.

How use Facebook Javascript SDK response in Ajax request?

Supposing I have the following code which returns a Javascript object which I can read in Firebug's console:
FB.api('/me',function(apiresponse){
console.log(apiresponse);
});
How can I then use the data from apiresponse in an Ajax request on the same page?
Currently my Ajax request looks as follows:
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
I know very little about Javascript, but reading around the subject leads me to think I have to convert the Javascript object to a JSON string. Is that correct? Am I on the right track?
You could put your AJAX call inside the handler for the API call like below..
FB.api('/me', function(apiresponse){
console.log(apiresponse);
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
});
one possible way:
define a global variable in your javascript, e.g. var myVar1;
set apireponse to the global variable in your FB.api callback (i.e. where u call console.log)
reference the var myVar1 in your ajax fcn.

Resources