how to determine the URL for ajax - ajax

As stated in the title...I am having trouble determining whether I'm actually performing the post operation properly or if the operation is properly performed then why is the value empty since I checked the value before passing it in the post operation...here is my code:
script:
$.ajax({
url: "<?php echo base_url();?>/Index/viewDayDocuments",
type: 'post',
data: {currentDay: 'currentDay', currentMonth: 'currentMonth', currentYear: 'currentYear'},
success: function(result){
$('.list').text('');
$('.list').remove();
$(".listIncoming").html("<p class = 'list'>This is the: "+ result +"</p>");
$("#myform").show(500);
}
});
controller code which throws back a return value:
$data['day'] = $_POST['currentDay'];
$data['month'] = $_POST['currentMonth'];
$data['year'] = $_POST['currentYear'];
$date = $data['year']."-".$data['month']."-".$data['day'];
$this->load->model('search_form');
$output['details'] = $this->search_form->searchDateRetrievedIncoming($date);
return $data;

Your ajax request needs a string echoed as a string.
$data['day'] = $_POST['currentDay'];
$data['month'] = $_POST['currentMonth'];
$data['year'] = $_POST['currentYear'];
$date = $data['year']."-".$data['month']."-".$data['day'];
$this->load->model('search_form');
$output['details'] = $this->search_form->searchDateRetrievedIncoming($date);
echo json_encode($data);
An array cannot be echoed out correctly if it's not in a data format, such as JSON.
Now we, take the data in your javascript
$.ajax({
url: "<?php echo base_url();?>/Index/viewDayDocuments",
type: 'post',
data: {currentDay: 'currentDay', currentMonth: 'currentMonth', currentYear: 'currentYear'},
success: function(result){
$('.list').text('');
$('.list').remove();
date = JSON.parse(result);
$(".listIncoming").html("<p class = 'list'>This is the: "+ date.month +"/"+date.day+ "/"+date.year +"</p>");
$("#myform").show(500);
}
});
In this module, I transformed the STRING from your PHP file into a JSON object so it can be read properly.

Related

How to show array result in ajax success using codeigniter?

I am fetching values from data using where in() mysql query and I got the correct result, but I don't know how to display the result in ajax success.
How do I display company name and email id from result data set?
my ajax code
<script type="text/javascript">
$('#ok').on('click', function() {
var vals = $('#show').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: { vals:vals },
datatype: 'json',
success: function (data) {
alert(data);
$("#result").html(data);
var result = JSON.parse(data);
}
});
});
</script>
my controller code:
function get_company()
{
$vals = $this->input->post('vals');
$query = $this->db->query("SELECT * FROM customer` where company_id IN ($vals) ")->result();
echo json_encode($query);
}
my result:
[{"company_name":"xyz Ltd","company_email":"123#gmail.com"},{"company_name":"wer Jit","company_email":"2222#gmail.com"}]
assuming you get this json in your ajax success:
const json = '[ {
"company_name": "xyz Ltd",
"company_email": "123#gmail.com"
},
{
"company_name": "wer Jit",
"company_email": "2222#gmail.com"
}]
';
const obj = JSON.parse(json);
// you don't need this line, if you have set ajax datatype:'json'
you can get results for a single data set:
console.log(obj[0].company_name);
// this is how to get the first company name of the data set
// expected output: "xyz Ltd"
or you can loop through the whole data set
obj.forEach(element => $("#result").append(element.company_name + '<br>'));
see a working example
conclusion: your ajax function could look just simply like this:
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: {
vals: vals
},
datatype: 'json',
success: function(data) {
obj.forEach(data => $("#result").append(data.company_name + '<br>'));
}
})

Return multiple strings from AJAX

With AJAX post i'm sending a data and on other page, according to this data i'm retrieving two different column values of mysql database by query. And i need to get back these two different values as a result of AJAX and show in two different inputs.
var mus_barkod = document.getElementById('mus_barkod').value;
var dataString = "mus_barkod="+mus_barkod;
$.ajax({
type: "POST",
url: "musteri_indir.php",
data: dataString,
success: function(result){
$("#indirim").val(result.mus_indirim);
$("#mus_isim").val(result.mus_isim);
This is the part of AJAX and below the (OLD) query for fetching data:
$mus_barkod = $_REQUEST['mus_barkod'];
$mus_cek = mysql_query("SELECT * FROM musteriler WHERE mus_barkod =
'".$mus_barkod."' AND sub_id = '".$per_sube."' ");
while ($mus_al=mysql_fetch_array($mus_cek)){
$mus_isim = $mus_al['mus_isim'];
$mus_indirim= $mus_al['mus_indirim'];
}
$mus_isim1 = 'Kayıtlı Müşteri Değil';
$mus_indirim1 = '0.00';
if($mus_barkod == '10' || $mus_barkod == '100090'|| $mus_barkod ==
'100237')
{
echo
$mus_indirim,$mus_isim;
}else{
echo
$mus_indirim1,$mus_isim1;
}
So how can i get back mus_indirim and mus_isim seperately and show in different inputs?
NOTE: Don't mind mysql_, this is an old system. PDO Forever :)
Fixed it by checking my codes more carefully. Here is the result for those need the same solution:
var mus_barkod = document.getElementById('mus_barkod').value;
var dataString = "mus_barkod="+mus_barkod;
$.ajax({
type: "POST",
url: "musteri_indir.php",
data: dataString,
dataType: "json", => the little thing i forgot to write :)
success: function(result){
$("#indirim").val(result.mus_indirim);
$("#mus_isim").val(result.mus_isim);
The Old PHP:
$mus_barkod = $_REQUEST['mus_barkod'];
$mus_cek = mysql_query("SELECT * FROM musteriler WHERE mus_barkod =
'".$mus_barkod."' AND sub_id = '".$per_sube."' ");
while ($mus_al=mysql_fetch_array($mus_cek)){
$mus_isim = $mus_al['mus_isim'];
$mus_indirim= $mus_al['mus_indirim'];
}
if($mus_barkod == '10' || $mus_barkod == '100090'|| $mus_barkod ==
'100237')
{
echo json_encode(array("mus_indirim" => $mus_indirim, "mus_isim" =>
$mus_isim));
}else{
echo json_encode(array("mus_indirim" => '0.00', "mus_isim" => 'Kayıtlı
Müşteri Değil'));
}

yii Ajax call not going to correct action

I have the following link to make my ajax call in yii2:
echo Html::a('Load more','ajaxShowMoreProducts', [
'onclick'=>"console.log('Load more');
$.ajax({
type:'POST',
cache: false,
url: 'ajaxShowMoreProducts',
success: function(response) {
console.log('suc');
}
});return false;",
]);
Then I have an action in my SiteController:
/**
* #return string|\yii\web\Response
*/
public function actionAjaxShowMoreProducts() {
var_dump('in');die;
$params = [];
$productModel = new Product();
$params['products'] = $productModel->getAll();
$this->renderPartial('partialProductItem', $params);
}
However when I click the link,the correct controller action does not seem to be called. Its still calling site/index. Any ideas what I have to do to get this working? Have i forgotten some sort of annotation or maybe I have to define my new action somewhere?
When I look in the console, it looks correct:
Request URL: http://localhost:8080/site/ajaxShowMoreProducts
In yii2 you should use the proper notation for action url (in url calling si not used the camelNotation but the words are separated by - (minus)
echo Html::a('Load more','ajax-show-more-products', [
and in ajax url too
url: 'ajax-show-more-products',
or try using Url Helper
use yii\helpers\Url;
....
echo Html::a('Load more', Url::to(['/site/ajax-show-more-products']), [
'onclick'=>"console.log('Load more');
$.ajax({
type:'POST',
cache: false,
url: '" . Url::to(['/site/ajax-show-more-products']) . "',
success: function(response) {
console.log('suc');
}
});return false;",
]);

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.

Resources