Sent AJAX to PHP, update DB, get new JSON - php

I have the following code:
$(document).ready(function() {
$.getJSON('model.php',function(data) {
$('h1').append(data['event']);
$('.img-circle').attr('src',data['image'])
$('a').attr('href',data['url']);
var eventname = data['event'];
$('.starter-template').on("swipeleft",function() {
var events = {'event': eventname};
$.ajax({
type: "POST",
url: "getchoices.php",
dataType: 'json',
data: {event: JSON.stringify(eventname) }
});
})
})
})
It takes a swipe, and sends that data to the database. The change in the database then updates the model.php JSON, which I would like to then read the new values into the document, but I am stuck on how to do this. Originally I repeated the original section like so:
$(document).ready(function() {
$.getJSON('model.php',function(data) {
$('h1').append(data['event']);
$('.img-circle').attr('src',data['image'])
$('a').attr('href',data['url']);
var eventname = data['event'];
$('.starter-template').on("swipeleft",function() {
var events = {'event': eventname};
$.ajax({
type: "POST",
url: "getchoices.php",
dataType: 'json',
data: {event: JSON.stringify(eventname) }
});
$.getJSON('model.php',function(data) {
$('h1').append(data['event']);
$('.img-circle').attr('src',data['image'])
$('a').attr('href',data['url']);
var eventname = data['event'];
})
})
})
})
But this seems to always send the same data['event'] to the PHP, rather than changing each time.

You assign eventname on every swipe like this:
$.getJSON('model.php',function(data) {
$('h1').append(data['event']);
$('.img-circle').attr('src',data['image'])
$('a').attr('href',data['url']);
var eventname = data['event'];
})
The thing is that you do not alter your global eventname variable which is defined
above. Changing your code (2nd $.getJSON) to following should do the job:
$.getJSON('model.php',function(data) {
...
eventname = data['event']; // omit var
})

Related

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

How to pass foreach data to ajax

I have stored two JSON arrays in local storage i.e,
viewbody=>json data1 , viewcollar=>json data2. I am fetching these arrays in foreach loop from local storage with data name attribute dynamically. But am not able to pass two arrays data to php ajax. Kindly help me, someone.
Below is my code,
$(document).on('click','.startDesignbtn', function() {
var product_id = $(this).data("id");
$(".getoption").each(function(){
var option_name = $(".getoption").data("name");
// alert(option_name);
var views = localStorage.getItem("view"+option_name);
});
$.ajax({
url: 'index.php?route=product/design/designMultiImage',
type: 'post',
//dataType: 'text',
data:{
'product_id': product_id,
'views' : views,
},
success: function(data) {
alert(data);return false;
var intValArray = data.split(',');
var count = 0;
$.each(intValArray,function(i){
localStorage.setItem("view_"+count,intValArray[i]);
count++;
});
localStorage.setItem('design-image',data);
localStorage.setItem('parent-id',product_id);
// var custom_link = data;
window.location = "<?php echo $customize_link;?>";
}
});
});
Use array.push() to append values to an array. Also, you need to define the array outside of the each loop otherwise you reset it every time. Also, inside the loop, use $(this) as opposed to targeting the element by class. Fixed your click function below:
$(document).on('click','.startDesignbtn', function() {
var product_id = $(this).data("id");
var views = [];
$(".getoption").each(function(){
var option_name = $(this).data("name");
// alert(option_name);
views.push("view"+option_name);
});
$.ajax({
url: 'index.php?route=product/design/designMultiImage',
type: 'post',
//dataType: 'text',
data:{
'product_id': product_id,
'views' : views,
},
success: ...

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.

Get repeated data from database when mousemove using jquery ajax

I have data which I got from database and It's in display.php.
Then mousemove is used to display data. But the data keeps repeating when I do mouseover. This is the code to mouse move
$(line.node).mousemove(get_over_handler(country));
and this is some code in function get_over_handler(country)
function get_over_handler(country) {
return function (event) {
color_country(country, selected_color);
var country_name = $("#country_name_popup");
country_name.empty();
country_name.append("<span id='popup_country_name'> " + code_to_name[country] + "</span><table width='100%' style='border-spacing:20px;'>");
var id_dataset = $("#dataset_select").find('option:selected').attr('id');
$.ajax({
type: "POST",
url: "display.php",
data: {ibukota: country, id_dataset: id_dataset},
success: function (data) {
country_name.append(data);
}
});
My question is how to prevent repeated data I got from database?
Rewrite your function to:
function get_over_handler(country) {
return function (event) {
color_country(country, selected_color);
var id_dataset = $("#dataset_select").find('option:selected').attr('id');
$.ajax({
type: "POST",
url: "display.php",
data: {ibukota: country, id_dataset: id_dataset},
success: function (data) {
var country_name = $("#country_name_popup");
country_name.empty();
country_name.append("<span id='popup_country_name'> " + code_to_name[country] + "</span><table width='100%' style='border-spacing:20px;'>");
country_name.append(data);
}
});
}
}

How do i get a single value from a row in my datatable

I am using the jquery plugin DATATABLE.
I want to get a single value from a selected row in my datatable (the ID) but i dont how to do so. The value should be saved and given to a textbox.
Here is my Code:
var oTable = $('#dataTable').dataTable();
$.ajax({
url: 'process.php?method=fetchdata',
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
]);
}
},
error: function(e){
console.log(e.responseText);
}
});
$('#dataTable tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
oTable.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
Hopefully someone can help me!
in php:
$id = $_POST['id'];
$row = mysql_query("select * from _yourtable_ where id='$id'");
...
in the js:
You must send id to the file process.php by POST or GET method:
id = $('#textBoxSelector').val();
$.ajax({
url: 'process.php?method=fetchdata&id='+id,
method: 'post',
dataType: 'json',
success: function(s){
console.log(s);
...
}
});

Categories