use with ajax passed data in my view - Laravel - php

I have some problems with using data I've passed with ajax. Thats the ajax snippet in my code:
$('a[data-id]').click(function () {
var id = $(this).attr('data-id');
var domain = $(this).attr('data-domain');
$.ajax({
url: 'getdata',
type: 'GET',
dataType: 'json',
data: {id: id, domain: domain, tld: tld},
success: function (data) {
$('.resultdomain').html(data);
console.log(data);
}
});
});
In my Controller is just this:
public function getData(Request $req)
{
$getdomain = Domains::where('id', '=', $req['id'])->first();
return $getdomain;
}
So if I console.log(data) i'm getting an object with all the data I need. For example ( copy-paste from my console ) :
Object { id: "5", cus_id: "1", name: "hello-from-the-other-site", tld: ".com", ...... }
thats great but I want to use that also and I couldn't figure out how.
I want to print the domain-name + the tld. and some other things out.
something like:
Domain: ( here I want to be the name + the tld together ).
Created-data : ( date )
Customer-ID = ( cus_id ).
Thanks for any help and sorry for my bad english :-)
current ajax code:
$('a[data-id]').click(function () {
var id = $(this).attr('data-id');
var domain = $(this).attr('data-domain');
$.ajax({
url: 'getdata',
type: 'GET',
dataType: 'json',
data: {id: id, domain: domain, tld: tld},
success: function (data) {
var domain = data.name + data.tld;
$('.resultdomain').html(domain);
}
});
});
in my view:
Domain: <div class="resultdomain"></div>

Your data is an object. You can access the properties directly and create the strings you want to have. So in your like success callback you can do it like this:
var data = {
id: "5",
cus_id: "1",
name: "hello-from-the-other-site",
tld: ".com"
};
var domain = data.name + data.tld;
$('.resultdomain').html(domain);
console.log("My Domain: " + domain);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultdomain"></div>

In your JS code, the success function would need something like the following:
success: function (data) {
$('.resultdomain').html(data.name + data.tld);
}

Related

Can't send data with POST method by jquery

I want to send some data to the file, and it get the file, but there no data
This is my .js code
var ids = [$(this).parent('.status-menu').prev('td').find('input').val()];
var status = $(this).find(":selected").text();
var changeStatusRKO = true;
$.ajax({
url: window.location.origin + '\\partsOfPages\\ajax\\changeStatus.php',
type: "POST",
data: {
'ids': ids,
'status': status,
'changeStatusRKO': changeStatusRKO,
},
success: function () {
console.log('Success');
},
fail: function () {
console.log('Error');
},
})
And this is my php, where I am sending the data
<?php
print_r($_POST);
if(isset($_POST["changeStatusRKO"]) OR isset($_POST["changeStatusRegistrationBusiness"]) OR isset($_POST["changeStatusServiceOneClick"])
OR isset($_POST["changeStatusAcquiring"]) OR isset($_POST["changeStatusCashDesk"])) {
$idItem = $_POST["idItem"]; //id строки в одной из пяти таблиц (`banks_to_requests_for_XXX`); массив
// echo "print_r: "; print_r($idItem); echo "<br>";
// echo "idItem[0]: " . $idItem[0] . "<br>";
if(!isset($idItem[0]))
...
But when I send it, there are no parameter in $_POST
Use 'method' instead of 'type'. Try this:
$.ajax({
url: window.location.origin + '\\partsOfPages\\ajax\\changeStatus.php',
method: "POST",
data: {
ids: ids,
status: status,
changeStatusRKO: changeStatusRKO,
},
success: function () {
console.log('Success');
},
fail: function () {
console.log('Error');
},
})
Also, you can use your browser's developer tools to see what's actually being passed to the server. In Chrome, you can go to Inspect > Network tab > Click on your request > Headers tab.
I solve this problem. I only need to change this part
url: window.location.origin + '\\partsOfPages\\ajax\\changeStatus.php',
to this
url: window.location.origin + '\\partsOfPages\\ajax\\changeStatus',
I removed .php in the end

Upate table with AJAX in Laravel 5.3 not working

I trying to use an AJAX PUT request to update a row in my database and I am trying to send the request to my controller. This is my AJAX call:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leased').val();
var truckModel = $('#truck-model').val();
$.ajax({
url: 'editTruck',
type: 'put',
data: {
truckNo: truckNo,
truckOwner: truckOwner,
vehicle_number: vehicle_number,
capacity: capacity,
end_of_insurance: end_of_insurance,
end_of_kteo: end_of_kteo,
truckCode: truckCode,
leased: leased,
truckModel: truckModel
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(){
console.log('success');
},
error: function(){
console.log('something went wrong');
}
});
});
So far so good. If I console.log() my data is seems I can get them from the form. I am using Laravel Collective for the form:
{!!Form::open(array('action' => ['Trucks#editTruck'], 'method' => 'put')) !!}
and my route is the following:
Route::put('/editTruck', 'Trucks#editTruck',function(){ });
Now I am using Request $request in the parameters of the controller but somehow it looks like I cannot get the incoming values. For example the following var_dump will say NULL.
public function editTruck(Request $request)
{
$data = $request->input('truckNo');
var_dump($data);
}
Same happens if I use
$data = $request->truckNo;
instead. So I am wondering how can I get the values that are been sent to my controller with my AJAX call? Why am I getting NULL values?
What I was planning to do is:
public function editTruck(Request $request)
{
$singleTruck = Truck::find($request->truckNo);
$singleTruck->truckNo = $request->input('truckNo');
$singleTruck->truckOwner = $request->input('truckOwner');
........
$singleTruck->save();
}
You can find the answer here:
https://laravel.io/forum/02-13-2014-i-can-not-get-inputs-from-a-putpatch-request
You should change your form method and method inside your js code to "post", and add extra field "_method" = "PUT"
probably it can help.
OK I found it. Looks like the AJAX was malformed. So here is how it should be written:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#vehicle_capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leasing').val();
var truckModel = $('#truck-model').val();
var outGoingData = {
'truckNo': truckNo,
'truckOwner': truckOwner,
'vehicle_number': vehicle_number,
'capacity': capacity,
'end_of_insurance': end_of_insurance,
'end_of_kteo': end_of_kteo,
'truckCode': truckCode,
'leased': leased,
'truckModel': truckModel,
};
var data = JSON.stringify(outGoingData);
$.ajax({
url: 'editTruck',
type: 'POST',
data: data, <!-- The error was here. It was data: {data}-->
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(response){
alert("The data should be "+ response);
},
error: function(){
console.log('skata');
}
});
});

Pass input value to ajax get Laravel

I am fairly new to Laravel and ajax in general, what I am trying to implement is to pass the value of an input field through an ajax get request.
My request looks like this:
function getInfo() {
$.ajax({
url: "info",
dataType: "json"
}).success(function(data){
$('#result').append(JSON.stringify(data));
}).fail(function(){alert('Unable to fetch data!');;
});
}
$('#infoSubmit').click(getInfo);
I have setup a route for my function in laravel that works like this
public/info/Variable <--
When I add a variable after info/
I get the data for that variable (e.g profile name)
I need to pass this variable from an inputfield to ajax request to something like this:
url: "info/+$inputfieldVariable"
Change:
url: "info",
TO:
url: "info/" + $('input-field-selector').val(),
Not sure about the correctness of your JS code: Shouldn't you be using done instead of success?
JavaScript:
function getInfo() {
var myFieldsValue = {};
var $inputs = $("#myForm :input");
$inputs.each(function() {
myFieldsValue[this.name] = $(this).val();
});
$.ajax({
url: "info",
dataType: "json",
data: myFieldsValue,
type: "GET" // Even if its the default value... looks clearer
success: function(data){
$('#result').append(JSON.stringify(data));
},
error: function(){
alert('Unable to fetch data!');
}
});
return false;
}
$('#infoSubmit').click(getInfo);
Untested but should be something like that

Sending a global variable

I have a piece of Javascript that forwards a users' selected information to an external PHP file, and returns information. In the code below, you can see it sends {'report' : report} via POST to that file. That works fine.
Essentially I need to add another variable to be sent. It's called 'id', but it's in another function. Is there a way to make that variable global and then incorporate it so it's sent in my code snippet? (and when will the global variable be cleared?)I can also send it via the 'url' attribute, and use GET in my PHP...just not sure how to implement.
$('#adminSelectReport a').live("click", function () {
//Get id from clicked link:
var report = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': report
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
UPDATE: Here is the other snippet that sends 'id' to another page, getting information. I need to retain this ID, however, and use it on my original code.
$('#adminSelectCompany a').click(function() {
//Get id from clicked link:
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {'id': id},
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg);
$('#adminSelectReport').fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
So it sounds like they select a Company via a link, then they select a Report via another link, and you need to remember which Company was selected.
In order to avoid global variables, I'd probably just add a class to the selected Company link, and then fetch that element by the selected class, and grab its ID. You could use the class for styling as well if that's needed.
var companies = $('#adminSelectCompany a');
companies.click(function () {
// remove class from previously selected, and add to new one
companies.filter('.selected').removeClass('selected');
$(this).addClass('selected');
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {
'id': this.id
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg)
.fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
$('#adminSelectReport a').live("click", function () {
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': this.id,
'company': $('.selected')[0].id
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
You can achieve this by assigning the value as a property of JavaScripts "global" namespace called window. Simply assign the id you want to make global to window.my_id, then refer to it in the click callback.
Note: If you're setting the global variable in another function, remember to check for its existance in the function that will use the variable, ie: var my_id = null; if (window.my_id != undefined) { my_id = window.my_id; }
Here's an implementation:
$('#adminSelectReport a').live("click", function () {
//Get id from clicked link:
var report = $(this).attr('id');
var company = window.report_company_id != undefined ? window.report_company_id : null;
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': report,
'company': company
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
.
$('#adminSelectCompany a').click(function() {
//Get id from clicked link:
var id = $(this).attr('id');
window.report_company_id = id;
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {'id': id},
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg);
$('#adminSelectReport').fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
Lastly I would advise against global variables if possible, or at least minimize the usage by wrapping common function/purposes in objects and prefixing the names with the project name or something.
Change
data: { 'report': report },
To
data{ 'report': report, 'id': YOUR ID },
Why don't you send the second variable like that:
data: {'report': report, 'id': your_id },
edit: arf too slow!

Zend and Jquery (Ajax Post)

I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.

Categories