ajax type:"POST" but post is empty - ajax

// Kirim permintaan AJAX ke server
$.ajax({
url: "getData", // URL yang akan dituju
type: "POST", // Tipe permintaan
data: { // Data yang akan dikirim ke server
no_spk: $("#input_nomor_spk").val()
},
success: function(result) { // Fungsi yang akan dijalankan jika permintaan berhasil
// Isi form dengan data yang diterima dari server
$("#input_rujuk_sp1").val(result.no_surat_text);
// dst.
}
});
I have set method type as post but in my Controller getData() I just get values either but not in $_POST.
$no_spk = $this->input->post("no_spk");
// Ambil data dari database
$data = $this->m_surat->cari($no_spk);
// Kembalikan hasil dalam format JSON
echo json_encode($data);

Press F12 to open inspect element then perform the transaction, check your payload, to see if javascript is passing a data from post ajax request

Related

How to display the corresponding table value of the response in AJAX

I have an ajax response that is equal to 1. And,in my success function, I want to display not the 1 to my view but the corresponding column_name which is 'brands_name' in the brands table which is 'Apple' in this case. I want to display this after a successful post request. Any ideas?
You need to send your response from your controller (json)
// controller
$data['ajax_response'] = 1;
$data['brands_name'] = $brands_name;
return json_encode($data);
You need to catch the success function to get the variable you want from php
// javascript
$.ajax({
url:link,
dataType:"json",
data:data,
type:"post",
success: function(data)
{
if(data.ajax_response == 1)
{
console.log(data.brands_name);
}
},
error: function()
{
}
});

Send POST Data with Ajax, withtout form, to a Symfony2 Controller, in JSON format

Good evening everybody!
I would like to send JSON Post Data to a Symfony Controller without form, but it doesn't work. I build a JSON data line and it is well built, it is NOT the problem. When I send my data with AJAX, the request is not filled.
Here is my Javascript code:
function validerSession()
{
//I don't describe the composition of the dataline.
var dataObject = JSON.stringify(obj); //My dataline JSONified
$.ajax({
type: "POST",
url: Routing.generate('cloud_money_drop_validerSession', { id: {{ partie.id }}, idSession: sessionId }),
data: dataObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (donnees) {
alert("Hello");
}
});
}
The AJAX call work.
Here is the PHP Symfony Controller method which received data:
public function validerSessionAction(Partie $partie, Session $session)
{
$request = $this->get('request');
$data = json_decode($request->getContent());
$serializer = $this->container->get('jms_serializer');
$response = $serializer->serialize($data, 'json');
return new Response($response);
}
But there is not any data in $data.
EDIT : An example of the dataline JSONified
{"trappes":{"1":{"id":"134","montant":"5000"},"2":{"id":"135","montant":"15000"},"3":{"id":"136","montant":"20000"},"4":{"id":"137","montant":"0"}}}
Do you have any idea ? I'm sure this is a common issue.
Thank you for your participation !
CloudCompany
I found the solution.
It's not really difficult.
It is not necessary to JSonify data. The controller has the capability to understand the original datatype.
So here is my simplified AJAX call:
function validerSession()
{
obj = new Object();
obj["title"] = "Title for example";
$.ajax({
type: "POST",
url: Routing.generate('cloud_money_drop_validerSession', { id: {{ partie.id }}, idSession: sessionId }),
data: obj,
success: function (donnees) {
data = Parse.JSON(donnees);
alert(data.title); //Show "Title for example"
}
});
}
And here is my Controller. It can recover data as an array of values.
public function validerSessionAction(Partie $partie, Session $session)
{
$request = $this->get('request');
$data = $request->request->all();
$serializer = $this->container->get('jms_serializer');
$response = $serializer->serialize($data["title"], 'json');
return new Response($response);
}
Thanks for the help!

pass an array to action using ajax YII

Hi i'm really new with YII, please help me to solve a simple problem.
I'm trying to pass some values from js to action and then to put them into database.
Most of this code i got from tutorial
public function actionInsert(){
$post = file_get_contents("php://input");
$data = CJSON::decode($post, true);
$read = new Read();
$read->attributes = $data;
$response = array();
$read->save();
}
Then i send:
$.ajax({
type: "POST",
url: "/read/insert/",
data: "name=imja&short_desc=korotkoe&author=avtor&image=photo",
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
But i get an 'error' alert and nothing goes to DB.
The values from .ajax don't get submitted as a JSON array, the values should simply be in the $_POST array. Also I like to return something like 'complete'. Try changing your code to this:
public function actionInsert(){
$read = new Read();
$read->attributes = $_POST;
$response = array();
$read->save();
echo 'complete';
die();
}
Or you can send it as a JSON array from the javascript side:
var data = {
name: 'imja',
short_desc: 'korotkoe',
author: 'avtor',
image: 'photo'
};
$.ajax({
type: "POST",
url: "/read/insert/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
error: function (){
alert('Error');
},
success: function(data){
alert('success');
}
});
However even if you do this apache will see the header type and still populate the $_POST array correctly. So it really isn't needed.
Also if you haven't already install Firebug onto Chrome or Firefox so you can see that actual ajax calls in the console. See what error you are getting from your action function in your controller.

Extjs how to memorize a response from an Ajax request?

I want to memorize the response of an ajax request, how I can do it?
In the code above, I found "" in the console...
How can I do it? any suggests?
var jsoncolumnset = '';
Ext.Ajax.request({
scope: this,
url: 'index.php',
params: {
m: 'Columnset',
a: 'readDefault'
},
reader: {
type: 'json',
root: 'rows'
},
success: function(response){
//Passo tutto il json (dovrebbe essere fatto un decode, ma viene gestito da Alfresco)
jsoncolumnset = response.responseText;
this.getStore('Documents').proxy.extraParams.columnset = response.responseText;
},
failure: function(){
//TODO: gestione fallimento chiamata
}
});
console.log(jsoncolumnset);
Ajax is asynchronous so while you have started the request in your Ext.Ajax.request call, the response has not come back by the time console.log(jsoncolumnset) is being executed.
The 'success' method will execute when the server response comes back to the browser which could be milliseconds or seconds later - either way the code mapped to the 'success' event is executed after the console.log executes.
So it appears the snippet is from code nested in some object since you have the "this" scope in place. .
You can add some event based logic that works nicely with ajax. Here is an idea:
// add this custom event in line with other bindings or in the objects constructor or a controllers init method
this.on('columnsready', this.logColumns);
// add this method to the main object
handleColumnResponse: function () {
//Passo tutto il json (dovrebbe essere fatto un decode, ma viene gestito da Alfresco)
this.jsoncolumnset = response.responseText;
this.getStore('Documents').proxy.extraParams.columnset = response.responseText;
// fire the custom event
this.fireEvent('columnsready');
},
// add this as an example of where you would put more logic to do stuff after columns are setup
logColumns: function () {
console.log(this.jsoncolumnset);
},
Ext.Ajax.request({
scope: this,
url: 'index.php',
params: {
m: 'Columnset',
a: 'readDefault'
},
reader: {
type: 'json',
root: 'rows'
},
// map to the handler method in the main object
success: this.handleColumnResponse,
failure: function(){
//TODO: gestione fallimento chiamata
}
});

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