I have tried these JS code combos:
var aion_settings = [];
function aion_save_settings(){
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: function(){
return aion_settings;
},
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
and...
function aion_save_settings(){
var aion_settings = [];
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: aion_settings,
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
..and
var aion_settings = [];
function aion_save_settings(){
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: aion_settings,
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
..and these combos with:
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:aion_settings,
success:function(result){
console.log(result);
}
});
On this JQuery page it even has this example:
var xmlDocument = [create xml document];
var xmlRequest = $.ajax({
url: "page.php",
processData: false,
data: xmlDocument
});
xmlRequest.done(handleResponse);
On the receiving side, I have this PHP code:
$app->post('/save_settings',function() use ($app){
$aion_settings=$app->request()->post();
var_dump($aion_settings);
//Save the aion_settings
if(aion_logged_in_user_super()){
global $aion_db;
if(is_array($aion_settings)) foreach($aion_settings as $setting_key => $setting){
//Get the setting's ID
$current_setting = array();
$current_setting = $aion_db->queryFirstRow("SELECT id FROM settings WHERE setting_key=%s",$setting_key);
if(!isset($current_setting['id'])) $current_setting['id']=NULL;
$aion_db->insertUpdate('settings',array(
'id'=>$current_setting['id'],
'setting_key'=>$setting_key,
'value'=>serialize($setting)
));
}
}
});
The aion_settings is setup correctly just before the $.ajax request is sent. But, the object settings is not caught on the PHP side, though other_data is caught? The last line below shows the object ready via console.log but not set via $.ajax. I'm stumped, any help?
The data parameter of your $.ajax function should have the following format:
data: {
'settings': aion_settings,
'other_data': 'Other Data'
},
This is how I fixed it:
JS Side:
function aion_save_settings(){
var aion_settings = new Object();
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:aion_settings,
success:function(result){
console.log(result);
}
});
}
PHP Side:
$app->post('/save_settings',function() use ($app){
$aion_settings=$app->request()->post();
var_dump($aion_settings);
//Save the aion_settings
if(aion_logged_in_user_super()){
global $aion_db;
if(is_array($aion_settings)) foreach($aion_settings as $setting_key => $setting){
//Get the setting's ID
$current_setting = array();
$current_setting = $aion_db->queryFirstRow("SELECT id FROM settings WHERE setting_key=%s",$setting_key);
if(!isset($current_setting['id'])) $current_setting['id']=NULL;
$aion_db->insertUpdate('settings',array(
'id'=>$current_setting['id'],
'setting_key'=>$setting_key,
'value'=>serialize($setting)
));
}
}
});
Please compare with my question above.
Related
I'm trying to make this code to work but it look I'm doing something wrong when passing the two variables with ajax, please help, here is the code, basically is a drag and drop code to move items between boxes and organize inside each box.
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data,
page: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
You can make it using this way:
$('.spremiUredivanje').click(function(){
ai = document.getElementById('ai_mjerila_edit').value;
broj_mjerila = document.getElementById('broj_mjerila_edit').value;
adresa = document.getElementById('adresa_edit').value;
stanje = document.getElementById('stanje_edit').value;
$( "#datum_edit" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
datum = document.getElementById('datum_edit').value;
operater = document.getElementById('operater_edit').value;
$.ajax({
url: 'test.php',
type: 'POST',
data: {
post1: broj_mjerila, post2: adresa, post3:stanje, post4: datum, post5: operater, post6:ai
},
beforeSend: function(){
$('#loaderEdit').show();
},
So your php file should look like this:
$broj_mjerila = $_POST['post1'];
$adresa = $_POST['post2'];
$stanje = $_POST['post3'];
$datum = $_POST['post4'];
$operater = $_POST['post5'];
$ai = $_POST['post6'];
To control your response use success inside ajax call:
success: function(response) {
if(response == 1) {
//alert("success!");
$('#editUspjesan').show();
$('#loaderEdit').hide();...
Can you explain your requirement clear. Are you trying to get page number and id in 2 separate array?
// If page no and id need to be in separate array
var position = [], pages = [];
$('.sortable-list>li').each(function() {
position.push($(this).attr("id"));
pages.push($(this).attr("pagenum"));
});
updateOrder(position, pages);
function updateOrder(position, page) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: position,
page: page
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
// If page no and id can be combined use objects
var selectedData = [];
$('.sortable-list>li').each(function() {
selectedData.push({id: $(this).attr("id"), page: $(this).attr("pagenum")})
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data
},
success: function() {
/* alert('your change successfully saved');*/
}
})
}
<script type="text/javascript">
$(document).ready(function() {
// Example 1.3: Sortable and connectable lists with visual helper
$('#sortable-div .sortable-list').sortable({
connectWith: '#sortable-div .sortable-list',
placeholder: 'placeholder',
delay: 150,
stop: function() {
var selectedData = new Array();
$('.sortable-list>li').each(function() {
selectedData.push([$(this).attr("id"), $(this).attr("pagenum")])
});
updateOrder(selectedData);
}
});
});
function updateOrder(data) {
$.ajax({
url: "ajaxPro.php",
type: 'post',
data: {
position: data.id,
page: data.pagenum
},
dataType:'json',
success: function() {
/* alert('your change successfully saved');*/
}
})
}
</script>
Let's try this one
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');
}
});
});
I would search for the solution, but I don't know what exactly do I have to search.
The task is to grab texts with ID's (#ftext_1,..._2,..._3,..._4) in html file and send them to php file. After some manipulation with texts in php file I have to insert them back into their ID's in html file.
Here is the code:
var text_1_Replace = $('#ftext_1').text();
var text_2_Replace = $('#ftext_2').text();
var text_3_Replace = $('#ftext_3').text();
var text_4_Replace = $('#ftext_4').text();
$('#ID').on('click', function(){
var text= {
ftext_1: text_1_Replace,
ftext_2: text_2_Replace,
ftext_3: text_3_Replace,
ftext_4: text_4_Replace
}
var targetFile = 'ajax/file.php';
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text),
contentType: 'application/JSON'
}).done(function(data) {
console.log(data);
});
});
How do I edit .done function to place new texts in their old ID's(#ftext_1,..._2,..._3,..._4)? The variable with texts array is $result.
so the answer is :
}).done(function(data) {
var text = JSON.parse(data);
var text1 = text.ftext_1;
var text2 = text.ftext_2;
var text3 = text.ftext_3;
var text4 = text.ftext_4;
$('#ftext_1').text(text1);
$('#ftext_2').text(text2);
$('#ftext_3').text(text3);
$('#ftext_4').text(text4);
So, the last update for the topic: The real and nice answer is:
.done(function(data) {
var text = JSON.parse(data);
$.each(text, function(i, val){
$("#" + i).text(val);
});
This code is the solution to my question in this topic. Thank you all, who responded!
The best for you would be send named property that looks like this
$.ajax({
method: 'post',
url: targetFile ,
data: {data: text},
dataType: "json",
success: function(response){
$.each(response, function(element){
$("#"+element.name).text(element.text);
});
}
});
Then in your php you could easily iterate data from post
<?php
$data = $_POST['data'];
$response = [
];
foreach($data as $elementName => $text){
// some text management
$response[] = ['name' => $elementName, 'text' => $text];
}
return json_encode($response);
When you change your received values in php you put them in an array so that you
can call it later easily
PHP
$values = array("one"=>5,
"two"=>"something",
"three"=>$something);
echo json_encode($values);
You need to add
dataType:'json'
in Jquery since you're returning json
JQuery
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text), # or data: {"value1":value,"value2":value2},
contentType: 'application/JSON',
dataType:'json',
success: function(response){
console.log(response.one); #Will console 5
console.log(response.two); #Will console "something"
console.log(response.three); #Will console whatever $something holds in php
}
});
You can call it however you want it (response) or (mydata)...
And then you just type response.yourdata (that you declared in php)
Hello overflowers!
I can't seem to manage to send my ajax data over to my php page correctly, it has worked perfectly fine before but now it is not working.
I'm getting the correct data via console.log but on my php page i'm getting Undefined index error.
Jquery
var task_takers_pre = [];
var task_takers = [];
var i = 1;
$(".new-task-takers ul.select_takers li").on('click', function(){
$(this).each(function(){
$(this).toggleClass("active");
if($(this).find('.fa').length > 0){
$(this).find('.fa').remove();
i -= 1;
var removeItem = $(this).data("id");
task_takers_pre.remove(removeItem);
console.log(task_takers_pre);
}else{
$('<i class="fa fa-check" aria-hidden="true"></i>').insertBefore($(this).find("div"));
i += 1;
task_takers_pre[i] = $(this).data("id");
console.log(task_takers_pre);
}
$.each(task_takers_pre, function (index, value) {
if ($.inArray(value, task_takers) == -1) {
task_takers.push(index, value);
}
});
});
});
$("#new-task").on('submit', function(){
console.log(task_takers_pre);
$.ajax({
type: 'POST',
url: '',
cache: false,
data: {task_takers_pre : task_takers_pre },
success: function(data) {
//console.log(data)
}
});
});
PHP
if(isset($_POST['task_submit'])){
$task_takers = $_POST['task_takers_pre'][0];
var_dump($task_takers);
}
EDIT
jQuery
var task_takers_pre = [];
var task_takers = [];
var i = 1;
$(".new-task-takers ul.select_takers li").on('click', function(){
$(this).each(function(){
$(this).toggleClass("active");
if($(this).find('.fa').length > 0){
$(this).find('.fa').remove();
i -= 1;
var removeItem = $(this).data("id");
task_takers_pre.remove(removeItem);
console.log(task_takers_pre);
}else{
$('<i class="fa fa-check" aria-hidden="true"></i>').insertBefore($(this).find("div"));
i += 1;
task_takers_pre[i] = $(this).data("id");
console.log(task_takers_pre);
}
$.each(task_takers_pre, function (index, value) {
if ($.inArray(value, task_takers) == -1) {
task_takers.push(index, value);
}
});
});
});
$(".assign").on('click', function(){
console.log(task_takers_pre);
$.ajax({
type: 'POST',
url: './core/includes/new_task.php',
cache: false,
data: {task_takers_pre : task_takers_pre},
success: function(data) {
//console.log(data)
}
});
$.ajax({
type: 'POST',
url: '',
cache: false,
data: {'task_takers_pre' : task_takers_pre},
success: function(data) {
//console.log(data)
}
});
});
PHP
if(isset($_POST['task_takers_pre'][0])){
$task_takers = $_POST['task_takers_pre'][0]; // Just for testing
var_dump($task_takers); // Just for testing
}
if(isset($_POST['task_takers_pre'])){
$task_takers2 = $_POST['task_takers_pre']; // Just for testing
var_dump($task_takers2); // Just for testing
}
What you are attempting to do is use the same PHP code to handle the Button Press from the Form AND the AJAX Call. Don't!
(note: This answer is Only based upon the code that has been provided and what is trying to achieved with this code.)
So your current PHP is, which I am guessing is what you call when you click the submit button... In that case $_POST['task_takers_pre'] will not exist as you are generating that from the JS and sending it in the AJAX Call.
Write a separate AJAX Call.
You need to create a separate file to handle your AJAX calls and have it perform what duties it needs to perform.
// This is just for testing my AJAX Call
public function ajax_post(){
if(isset($_POST['task_takers_pre'])){
$task_takers = $_POST['task_takers_pre'][0]; // Just for testing
var_dump($task_takers); // Just for testing
die();
}
else {
// Illegal access/entry do something...
echo 'Error - I had better check what I am posting.';
die();
}
}
If you juse want to send some data in the AJAX Call when you click the submit button,you could return false to prevent form submission in the submit event.
$("#new-task").on("submit", function(){
$.ajax({
type: "POST",
url: "",
cache: false,
data: {task_submit:1, task_takers_pre: task_takers_pre},
success: function(data){
console.log(data);
}
});
return false;
});
I am using jquery's AJAX in my project. Today, I used it somewhere else with all same themethods but it doesn't work.
Is there something wrong with my script?
HTML:
<a class='btn edit_receipe_btn' id='myreceipe-52'>Edit</a>
JQuery:
(Click function works. When I put alert(instance) after var instance line, it works)
$(document).ready(function(){
$('.edit_receipe_btn').click(function(){
var instance = $(this).attr('id');
var dataString = 'process=userReceipeEdit&instance='+instance;
$.ajax({
type: 'POST',
url: 'ajax/ajaxs.php',
data: dataString,
cache: false,
success: function(msg) {
alert(msg);
}
});
});
});
PHP:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
return $instance;
}
It appears the problem is in the PHP. What am I doing wrong?
Is that the entire PHP page? if so, you should echo instead of return
As Jasper De Bruijn notified me, the problem was in my php script. I should use echo instead of return:
Wrong usage:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
return $instance;
}
Correct usage:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
echo $instance;
}
Two things, output the error and check to make sure instance is not undefined.
Output the error like this:
$('.edit_receipe_btn').click(function(){
var instance = $(this).attr('id');
var dataString = 'process=userReceipeEdit&instance='+instance;
$.ajax({
type: 'POST',
url: 'ajax/ajaxs.php',
data: dataString,
cache: false,
success: function(msg) {
alert(msg);
},
error: function(response, status, error)
{
alert(response.responseText);
alert(status);
alert(error);
}
});
});
I think you have formed this POST like a get, not sure why. Try doing this in JS:
var dataString =
{
"process" : "userReceipeEdit",
"instance" : instance
};