I am trying to retrieve data from the database, but when the get parameter appears in the address bar, there is no change on the page, so I have to refresh the page to receive the data, instead of receiving it without refresh/reload.
Route:
Route::get('writers/{orders?}/{number?}', ['as'=>'writers','uses'=> 'HomeController#writers']);
Controller:
public function writers($order='all',$num=10){
$dm = new DataModel();
$orders = $dm->getCertainWriters($num);
$this->certainOrders =$orders;
return view('writers')->with(array('title'=>'Writers','data'=>$this->certainOrders,));
}
Method:
public function getCertainWriters($orders = 'all'){
$data = DB::select("SELECT * FROM `writers` WHERE `completed_orders` > '$orders' ");
return $data;
}
AJAX:
$("#ajax-orders").change(function(e) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "GET",
url: url,
dataType:"html",
headers: {
'X_CSRF_TOKEN':CSRF_TOKEN,
'Content-Type':'application/json'
},
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
$(form).submit(e);
var orders = $('select').val();
window.history.pushState("writer", "orders", "/writers/orders/"+orders);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
Related
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');
}
});
});
How to send two id's using ajax and jquery at the same time when bootstrap modal is loaded.
Am working on a project, when a modal load it has to send two ajax request to the server and append the returned data to the modal-body input text.
Below are the codes that send the requests,
$('#myPayment').on('show.bs.modal', function(e) {
var guestID = $(e.relatedTarget).data('guest-id');
var bID = $(e.relatedTarget).data('b-id');
var bgID = $(e.relatedTarget).data('bg-id');
var booking_date = $(e.relatedTarget).data('booking-date');
var room_rate = $(e.relatedTarget).data('room-rate');
var room_price = $(e.relatedTarget).data('room-price');
var room_currency = $(e.relatedTarget).data('room-currency');
$.ajax({
url: "inc/get_room_rate_name.php",
method: 'POST',
data: {'curr_room_rate' : $(e.relatedTarget).data('room-rate')},
success: function(value) {
$(e.currentTarget).find('input[name="room_rate"]').val(value);
}
});
$.ajax({
url: "inc/get_currency.php",
method: 'POST',
data: {'curr_currency' : $(e.relatedTarget).data('room-currency')},
success: function(value) {
var data = value.split('-');
var room_currency = data[1];
$(e.currentTarget).find('input[name="currency"]').val(room_price + " " +room_currency);
}
});
//populate the textbox
$(e.currentTarget).find('input[name="first_name"]').val(guestID);
$(e.currentTarget).find('input[name="b_id"]').val(bID);
$(e.currentTarget).find('input[name="bg_id"]').val(bgID);
//$(e.currentTarget).find('input[name="room_rate"]').val(room_rate);
//$(e.currentTarget).find('input[name="currency"]').val(room_data);
});
I have written this code but it didn't work. I have searched so much but those code are not properly work. what should I do? I want to fetch data without refreshing whole page.
I have looked at this other question.
$(document).ready(function() {
$("#pair_form").submit(function(e) {
e.preventDefault();
var devicename = $("#devicename").val();
var id = $("#id").val();
var latitude = $("#latitude").val();
var longitude = $("#longitude").val();
var ignition = $("#ignition").val();
var Arming = $("#Arming").val();
function showData() {
$.ajax({
url: 'http://example.com/ddd/cfg.php',
method: 'get',
dataType: 'text',
success: function(response) {
$('#result').html(response)
}
});
}
});
});
Heres my code so you can see what i'm trying to do
var cont = 1;
var form_data = {};
$('.preview-add-button').click(function(){ //Introduce los nuevos campo
form_data["isexo"] = $('.payment-form #sexo option:selected').text();
form_data["icolor"] = $('.payment-form input[name="color"]').val();
form_data["iraza"] = $('.payment-form #raza option:selected').text();
form_data["itipo"] = $('.payment-form #tipo option:selected').text();
form_data["iprecio"] = $('.payment-form input[name="precio"]').val();
form_data["ipeso"] = $('.payment-form input[name="peso"]').val();
form_data["imonto"] = parseFloat($('.payment-form input[name="precio"]').val()*$('.payment-form input[name="peso"]').val()).toFixed(2);
form_data["remove-row"] = '<span class="glyphicon glyphicon-remove"></span>';
var row = $('<tr></tr>');
$.each(form_data, function( type, value ) {
$('<td class="input-'+type+'"><input type="hidden" class="form-control" name="data-'+type+'" value="'+value+'"></td>').html(value).appendTo(row);
cont++;
});
$('.preview-table > tbody:last').append(row);
calc_total();
$('#sexo').val('');
$('#color').val('');
$('#raza').val('');
$('#tipo').val('');
$('#precio').val('');
$('#peso').val('');
});
console.log( form_data );
$.ajax({
type: "POST",
url: "/compras/create/store",
data: form_data
});
How can i pass this array: var form_data = {} to my controller? except form_data["remove-row"]
For example: pic
Update: Trying with ajax i don't know if my code is ok,
$.ajax({
type: "POST",
url: "compras/create/store",
data: form_data
});
or
$.ajax({
data: form_data
});
My controller where $data is for return the array but:
public function store()
{
$compra = new Compra;
$compra->fecha = Input::get('fecha');
$compra->num_factura = Input::get('num_factura');
$compra->id_proveedor = Input::get('proveedor');
$compra->nombre_vendedor = Input::get('nombre_vendedor');
$compra->total = Input::get('total');
$compra->descuento = Input::get('desc');
$compra->itbms = Input::get('itbms');
$compra->total_bruto = Input::get('total_bruto');
$id_compra = $compra->id;
$data = Input::except('remove-row');
if($compra->save()){
Session::flash('message','Guardado Correctamente');
Session::flash('class','success');
}else{
Session::flash('message','Ha ocurrido un error');
Session::flash('class','danger');
}
return $data;
}
return: {"_token":"tLPlnBix0vQxkjZkHaF9cdIFPvgq7O1U7pTXye8v","fecha":"2014-11-25","num_factura":"2131AJ","proveedor":"6","nombre_vendedor":"DelPotro","id_proveedor":"","ruc":"","telef":"","sexo":"","color":"","raza":"","tipo":"","precio":"","peso":"","total_bruto":"387.00","total":"387.00","desc":"","itbms":""} without the form_data array
I am giving here the code to do the similar thing, In my case I am saving user interests ( swimming, singing, music etc) into a database table called as Interests( id, interest_name).
First Lets look at the javascript:
public function saveInterests()
{
//I declare the array here
var allVals = [];
//I get my values from checkboxes checked in a div with id interests
$('#interests :checked').each(function(){
allVals.push($(this).val());
});
//Now I am making an post ajax call
$.post("http://b2.com/saveInterests", {interests: allVals},function(data)
{
//this is ajax callback function
if(data=='Saved')
{
alert('Saved With Success');
}
else
{
alert('Sorry couldnt save data in Database');
}
});
}
//A route to handle this Ajax request
Route::post('saveInterests',array('as'=>'interests.Profile','uses'=>'ProfileController#saveInterests'));
//Laravel Code in ProfileController for handling the route
public function saveInterests()
{
$iarray=Input::get('interests'); //getting my array from ajax call to Laravel
foreach($iarray as $userInterest)
{
$inter = new Interest(); //creating a new row in Interest table using model
$inter->interest_name=$userInterest;
$inter->save();
}
return "Success";
}
Using jQuery you can make an ajax call to a designated route, which would in turn call a designated controller method. You can use either:
jQuery.ajax( [settings ] )
//data: form_data,
Or:
jQuery.post( url [, data ] [, success ] [, dataType ] )
//with form_data as the second parameter
And in your controller method you can get the data using:
$mydata = Input::except('remove-row');
NOTE
If the element you're clicking is a submit button, and the ajax call is somewhere within the click handler, please consider making the following changes.
Change:
$('.preview-add-button').click(function(){ //Introduce los nuevos campo
var form_data = {};
To:
$('.preview-add-button').closest('form').on('submit', function( e ){
e.preventDefault();//this line prevents the form from submitting
var form_data = {};
UPDATE:
In addition to the above changes, please move the ajax call so that it is as shown below:
$('#peso').val('');
console.log( form_data );
$.ajax({
type: "POST",
url: "/compras/create/store",
data: form_data,
success: function( result ) {
console.log( result ); //please post output of this
}
});
});
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.