How to pass jquery array to a laravel controller - php

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

Related

don't retrieve object on php page which passed from ajax call

Hi i don't get retrieve Ajax Data to PhP page its throwing error. i pass data as json object.
The error i'm getting is
Edit.php
$('#regForm').on('submit', function (e) {
var url = document.URL; // Get current url
var id = url.substring(url.lastIndexOf('=') + 1);
var data1 = $("#regForm").serialize();
data = {data:data1,id:id};
console.log(data)
$.ajax({
method:"POST",
url: 'update.php',
dataType : 'json',
data: data,
success: function () {
alert('form was submitted');
}
});
});
update.php
if(isset($_POST["submit"]))
{
print_r($_POST['data']);
// Error::: Undefined index:data in
pass Id using hidden input field and then form data serialize then after you can use by name wise on php page.
$_POST['name'];
Read my comment, then look at this:
JavaScript may look like this
$('#regForm').on('submit', function(e){
var s = location.search.split('&'), serialId = s[s.length-1], idArray = serialId.split('=');
if(idArray.length === 2 && idArray[1].trim() !== '' && idArray[0].match(/^id$/i)){
var serialData = $(this).serialize()+'&'+serialId;
$.ajax({
method:'POST', url:'update.php', dataType:'json', data:serialData},
success:function(jsonObj){
console.log(jsonObj);
}
});
}
e.preventDefault();
});
PHP may look like this
<?php
if($_POST['id']){
// each property as $_POST[propertyHere]
// sending back to JavaScript
$c = new stdClass; $c->someProp = 'some value';
echo json_encode($c); // dataType is json so you should get Object as result
}
?>

Receive data from MySQL database without reloading the page

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

Content fetch in main page from another page from database through ajax

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

Use JS variables and serialize for AJAX request

I'd like to have the following code in my AJAX request:
function ajax_post( form_info ){
var request = $.ajax({
url: "ajax_handler.php",
type: "POST",
data: {data : form_info},
});
};
I'd like to serialize all of the elements in my clicked event to pass directly to the AJAX function because I'm doing processing on the PHP side. Say I have the following on click function:
$('.open-popup').on("click", function() {
var clicked_id = $(this).attr('id');
var contest_id = $('#contest-id').val();
var contest_type = $('#contest_type').val();
//serialize everything to a data_to_pass variable
ajax_post( data_to_pass );
});
How could I serialize the clicked_id, contest_id and contest_type into a single variable to pass to my AJAX processing function as a single string of data?
This is how you can do it:
var data_to_pass = {
clicked_id: clicked_id,
contest_id: contest_id,
contest_type: contest_type
}
JS:
$('.open-popup').on("click", function() {
var clicked_id = $(this).attr('id');
var contest_id = $('#contest-id').val();
var contest_type = $('#contest_type').val();
var data_to_pass = {
clicked_id: clicked_id,
contest_id: contest_id,
contest_type: contest_type
};
ajax_post( data_to_pass );
});
AJAX:
function ajax_post( form_info ){
var data = JSON.stringify(form_info);
var request = $.ajax({
url: "ajax_handler.php",
type: "POST",
data: {data : data},
});
};
You can create FormData for that and append all the required values with .append() function.
Like this,
$('.open-popup').on("click", function() {
var clicked_id = $(this).attr('id');
var contest_id = $('#contest-id').val();
var contest_type = $('#contest_type').val();
//serialize everything to a data_to_pass variable
var fd = new FormData();
fd.append( 'clicked_id', clicked_id);
fd.append( 'contest_id', contest_id);
fd.append( 'contest_type', contest_type);
ajax_post(fd);
});
And AJAX function would look something like this,
function ajax_post( form_data ){
var request = $.ajax({
url: "ajax_handler.php",
type: "POST",
data: form_data,
});
};
And access the data in PHP using $_POST['clicked_id'] and so on...
jQuery's ajax accepts objects as data; it takes care of the serialization for you. So you can simply do
ajax_post({
clicked_id:$(this).attr('id'),
contest_id:$('#contest-id').val(),
contest_type: $('#contest_type').val()
});
If you want to do so, try using a form element and inputs (it can be hidden fields if it isn't a user submitted form) in your HTML code, and serialize it, so you can transmit the whole 'block of information' at one time with Ajax.
Look at rfunduk's answer at this question.

jQuery use ajax and json to switch page with button

Hi so I have a JS file with a function for my button, this button get value from different checkbox in a table. But now i want to get these value on another page (for invoice treatement).
Here is my Script :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
var jsonobj = {};
checked.each(function () {
var value = $(this).val();
jsonobj.value = value;
tab.push(jsonobj);
});
var data= { recup : tab };
console.log(data);
$.ajax({
type: 'POST',
url: 'genererfacture-facture_groupee.html',
data: data,
success: function (msg) {
if (msg.error === 'OK') {
console.log('SUCCESS');
}
else {
console.log('ERROR' + msg.error);
}
}
}).done(function(msg) {
console.log( "Data Saved: " + msg );
});
});
i use an MVC architecture so there is my controller :
public function facture_groupee() {
$_POST['recup'];
var_dump($_POST['recup']);
console.log(recup);
$this->getBody()->setTitre("Facture de votre commande");
$this->getBody()->setContenu(Container::loader());
$this->getBody()->setContenu(GenererFacture::facture_groupee());
and for now my view is useless to show.
I have probably make mistake in my code.
Thank you.
Nevermind after thinking, I have used my ajax.php page which get my another page thanks to a window.location :
my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
var data = {recup: tab};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.php?action=facture_groupee',
data: data,
success: function (idfac) {
console.log("Data Saved: " + idfac);
var id_fac = idfac;
window.location = "ajax.php?action=facture_groupee=" + id_fac;
}
});
});
my php :
public function facture_groupee() {
foreach ($_POST['recup'] as $p){
echo $p; }

Categories