It looks like that i got wrong type or something going on
function updateCart()
{
var dataArray= [];
var i=0;
var item;
$('.cd-cart .wrapper .body .product').each(function()
{
var item=new Array();
i++;
var $element = $(this)
qty=parseInt($element.find('select').val());
name=$element.find('h3 a').html();
price=parseInt($element.find('.price1').text().replace('₽',''));
id=parseInt($element.attr('id').replace('product_',''));
image=$element.find('img')[0].src;
item['id']=id;
item['price']=price;
item['name']=name;
item['qty']=qty;
item['image']=image;
dataArray.push(item);
});
var jObject={};
jObject = JSON.stringify(dataArray);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/updateCart',
type: 'get',
dataType:'json',
data: ({dataArray:jObject}),
success:function(data){
console.log(data);
},
error:function(error){
console.log(error);
}
});
}
Server-side got return $_GET;
I got this response from the server :Object {dataArray: "[[],[]]"}
What can i do to get Normal response?
P.S dataArray is an array of an array
I did some reformatting here while I was trying to run down your codes flow. Generally if you need an associative array style grouping in JavaScript you want to use an object, not an array. Arrays are indexed, Objects keyed. In my example I used a constructor function to build your item. You could also let data = {}; and then build the keys like data.id = 1.
// formatted for readability.
function updateCart() {
const data = buildCart();
let dataObj = JSON.stringify(data)
makeRequest('/updateCart', dataObj);
}
function buildCart() {
let data = [];
$('.cd-cart .wrapper .body .product').each(function() {
const $element = $(this);
let qty = parseInt($element.find('select').val())
, name = $element.find('h3 a').html()
, price = parseInt($element.find('.price1').text().replace('₽',''))
, id = parseInt($element.attr('id').replace('product_',''))
, image = $element.find('img')[0].src;
data.push(new Item(id, price, name, qty, image));
});
return data;
}
function Item(id, price, name, qty, image)
{
this.id = id
this.price = price;
this.name = name;
this.qty = qty;
this.image = image;
}
function makeRequest(url, dataObj)
{
let token = $('meta[name="csrf-token"]').attr('content');
let jqXHR = $.ajax({
url: url,
type: 'GET',
headers: 'X-CSRF-TOKEN': token,
dataType: 'json',
jsonp: false,
data: {dataArray: dataObj}
});
jqXHR.done(function(data, status, jqXHR) {
// success
});
jqXHR.fail(function(jqXHR, status, error) {
// failure
});
}
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');
}
});
});
Please help. I have this jQuery code
$('.modal-footer').on('click', '.edit', function() {
var serializedData = $(".form-horizontal").serialize();
var criscore = new Array();
$('input[name^=criscore]').each(function(){
criscore.push({score:$(this).val(), criid:$(this).data('criid')});
});
for (var key in criscore) {
var score = criscore[key].score;
var criid = criscore[key].criid;
//console.log(score +" s "+ criid);
$.ajax({
method: 'post',
url: '/judges/candidates/scorecandidates',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {
'_token': $('input[name=_token]').val(),
'canId': $('input[name=canId]').val(),
'catId': $('input[name=catId]').val(),
'criId': criid,
'score': score,
'judgeId': $('input[name=judgeId]').val()
},
success: function(data) {
console.log(data);
}
});
}
});
and in my controller is
public function scorecandidates(Request $req)
{
$data = new Score();
$data->canId = $req->canId;
$data->catId = $req->catId;
$data->criId = $req->criId;
$data->score = $req->score;
$data->judgeId = $req->judgeId;
$data->save();
return response()->json($data);
}
my problem is that it is still keeps having an 500 (Internal Server Error)
Even though I already put the csrf token is different ways.. Can any body help me?
Thank you
i have to select multiple tests and date and when clicked on submit based on the test,laboratory names are loaded in select option
Ajax script
$('[name=submits]').click(function(e)
{
e.preventDefault();
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
var testdate = $("#appointmentdate10").val();
//here make your ajax call to a php file
$.ajax({
type: "POST",
url: "http://localhost/refer/index.php/details",
data: { laboratory_tests: array, testdate: testdate },
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
for (i=0;i<data.length;i++)
{
var id = data[i]['laboratory_id'];
var val = data[i]['laboratory_name'];
selOpts += "<option value='"+id+"'>"+val+"</option>";
}
$('#yourSelect').append(selOpts);
}
});
});
Ajax success response is:
[
{"laboratory_id":"19","laboratory_name":"ghc","laboratory_address":"cgc","laboratory_place":"jhggj","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"20","laboratory_name":"BBNB","laboratory_address":"sdfds","laboratory_place":"sdfsd","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"22","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"}
]
html
<select class="form-control" id="yourSelect">
</select>
but i am not able to display in select tag
$.ajax({
url: config.routes.profitsReport,
type: "POST",
dataType: 'json',
success: function (result) {
$.each(result, function (i, value) {
$('#category_profit').append('<option id=' + JSON.stringify(value.id) + '>' + JSON.stringify(value.name) + '</option>');
});
},
error: function (request, status, error) {
alert(request.statusText + "[" + request.status + "]");
alert(request.responseText);
$('button#form_salesReport_button').html(config.messages.searchReport);
}
});
Try to loop through the result like this:
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
$.each(data, function(k, v)
{
var id = data[k].laboratory_id;
var val = data[k].laboratory_name;
selOpts += "<option value='"+id+"'>"+val+"</option>";
});
$('#yourSelect').append(selOpts);
}
You can loop
[
{"laboratory_id":"19","laboratory_name":"ghc","laboratory_address":"cgc","laboratory_place":"jhggj","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"20","laboratory_name":"BBNB","laboratory_address":"sdfds","laboratory_place":"sdfsd","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"},
{"laboratory_id":"22","laboratory_name":"Anand","laboratory_address":"bsk","laboratory_place":"bengaluru","laboratory_tests":"MRI R\/L SHOULDER WITH CONTRAST"}
]
via
var options = "";
for (let item in array) {
options += `<option value=${item.id}>${item.laboratory_name}</option>`;
}
document.getElementById("yourSelect").innerHTML = options;
If it's a String, you can convert it to an array via JSON.parse.
If you are expecting json data from ajax request then you need to require to add dataType as json.
$('[name=submits]').click(function(e)
{
e.preventDefault();
var array = [];
$('select :selected').each(function(i,value)
{
array[i] = $(this).val();
});
var testdate = $("#appointmentdate10").val();
//here make your ajax call to a php file
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/refer/index.php/details",
data: { laboratory_tests: array, testdate: testdate },
success: function(data){
// alert(data);
console.log(data);
var selOpts = "";
for (i=0;i<data.length;i++)
{
var id = data[i]['laboratory_id'];
var val = data[i]['laboratory_name'];
selOpts += "<option value='"+id+"'>"+val+"</option>";
}
$('#yourSelect').append(selOpts);
}
});
});
I am trying to make an ajax call on click on anchor tag dynmically generated from $.each loop for a JSON response.
For Information : #records is my table and .update is the class of anchor tag in that table.
Please be informed that the table is generated dynamically.
Now the problem is that my ajax call is returning nothing even i have checked it error: but no response received. I have tried alerting my var data just before the ajax call and it worked.So the problem starts from the ajax call. Moreover, my server side code is running fine.
// Update existing customers
$("#records").on('click', ".update", function() {
var data = '?'+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data: data,
success: function(response) {
console.log(response);
}
});
});
Thanks in advance.
For reference below is the code that generates the table.
// Function to make datagrid
function getRecords() {
$.getJSON("viewcustomers.php", function(data) {
var items = [];
var xTd = '';
var xTr = '';
$.each(data, function(key, val) {
var c = 0;
var id = 0;
$.each(val, function(key1, val1) {
if (c == 0)
{
id = val1;
}
c++;
xTd += '<td>' + val1 + '</td>';
});
xTd += '<td>Edit</td>';
xTd += '<td>Delete</td>';
xTr = '<tr>' + xTd + '</tr>';
items.push(xTr);
xTd = '';
xTr = '';
});
$("#records").append(items);
});
}
Updated the server side code:
page url : localhost/hotel/viewcustomers.php
/**
* Fetch single row for the purpose of update / delete.
*/
if(isset($_GET['update'])){
$customer = new Customers;
$Id = $_GET['update'];
$customer_single = $customer->View_Single_Customer($Id);
echo json_encode($customer_single);
unset($customer);
}
This line is not used the right way var data = '?'+ $(this).attr('id');
Change it like this: var my_id = $(this).attr('id');
Then update the line data: data with data : {id:my_id}
Complete code :
$("#records").on('click', ".update", function() {
var my_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data : {id : my_id},
success: function(response) {
console.log(response);
}
});
});
Or do it like this:
$("#records").on('click', ".update", function() {
var param = '?id='+ $(this).attr('id'); /*notice that I have added "id=" */
$.ajax({
type: "GET",
url: "viewcustomers.php" + param,
/* remove the data attribute */
success: function(response) {
console.log(response);
}
});
});
Modify it as
$("#records").on('click', ".update", function() {
var request = '?id='+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php" + request,
success: function(response) {
console.log(response);
}
});
});
sorry for the long question. I am trying to ajax post to collect a contacts position history and then add the markers to the map.
The ajax post returns the positions data json encoded like:
[{"name":"Chris","data":{"user":"447967048843","data":[{"timestamp":1332840872,"longitude":-1.549517,"latitude":53.973174},{"timestamp":1332841510,"longitude":-1.444133,"latitude":53.997148}]},"contacts":null},{"name":"Jason","data":{"user":"447879896697","data":[{"timestamp":1332839836,"longitude":-1.566667,"latitude":53.978533},{"timestamp":1332840447,"longitude":-1.567654,"latitude":53.977927}]},"contacts":null}]
Here is the getHistory function which is called on form submit after the contact has been selected.
function getHistory() {
var contact = $("#contact").val()
var days = $("#days").val()
$.ajax({
type: 'post',
url: 'temp_history.php',
data: {contact: contact, days: days},
context: document.body,
beforeSend: function() {
},
success: function(succ){
var obj = jQuery.parseJSON(succ);
var divs="",tabs="",counts=0;
jQuery("#gMap").gmap3({
action: 'clear'});
jQuery(".marker").remove();
jQuery.each(obj,function(i,item){
tabs +=item.contacts;
if(item.data.latitude != null && item.data.longitude!=null)
{
addMarker(item.name, item.data.timestamp,item.data.latitude,item.data.longitude,item.data.user_id);
}
});
}
});
}
I think the problem is i need to nest the jQuery.each function but not sure how?
The addMarker function is:
function addMarker(name, timestamp, lati, longi, user_id) {
jQuery("#gMap").gmap3({
action: 'addMarkers',
markers:[
{lat:lati, lng:longi, data:name}
]
});
}
Thank you
You're right - your traversal of your JSON was incorrect, try this in your success handler:
success: function(data){
var json = jQuery.parseJSON(data); // If you're returing json, this shouldn't be required
var divs = "", tabs = "", counts = 0;
jQuery("#gMap").gmap3({ action: 'clear' });
jQuery(".marker").remove();
jQuery.each(json, function(i, item) {
var name = item.name;
var userId = item.data.user;
jQuery.each(item.data.data, function(i, nav) {
var ts = nav.timestamp;
var lat = nav.latitude;
var long = nav.longitude;
if (lat != null && long != null) {
addMarker(name, ts, lat, long, userId);
}
});
})
}
Also, it would be worth making the object names in your JSON more semantic, especially as you have data listed in multiple levels.