pass two variables with ajax after push to array - php

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

Related

How to create jquery array from ajax data?

I wanna create array from ajax response. I took array from ajax and i have to create dynamic data for chips
materializecss autocomplete
response from ajax
var tag = '';
$(document).on('keyup', '.tags', function() {
var _this = $(this).val();
if(_this.length > 1) {
$.ajax({
url: '/story/searchTags',
type: 'POST',
dataType: 'JSON',
data: {
tag: _this
},
success: function(tags) {
tag = tags;
}
});
}
});
$('.chips-placeholder').chips({
placeholder: lang_('Your tag'),
secondaryPlaceholder: '+ tag',
autocompleteOptions: {
// I need data like this from response
data: {
'Google', null
'Googol', null
},
limit: 5,
minLength: 2
}
});
<div class="chips chips-placeholder chips-autocomplete input-field" style="background:#fff">
<input class="input tags" placeholder="tag" autocomplete="off" />
</div>
that's my code
Finally, thanks to #Vel to find right answer.
jsfiddle - work code
You need to do like this.
var tag = '';
$(document).on('keyup', '.tags', function() {
var _this = $(this).val();
if(_this.length > 1) {
/*$.ajax({
url: '/story/searchTags',
type: 'POST',
dataType: 'JSON',
data: {
tag: _this
},
success: function(tags) {
tag = tags;
}
});*/
// ['google', 'googol'] <- this array I take from ajax
tag = ['google', 'googol'];
var obj = {};
$(tag).each(function (index, value) {
obj[value] = null;
});
$('.chips').chips({
secondaryPlaceholder: '+ tag',
autocompleteOptions: {
data:obj,
}
});
}
});
fiddle link

I need to send my values using ajax twice first on page 1 then from that two page 2

I am trying to send my values using ajax from original page to the page one and then to page 2 this is my code but it seems to be not working.
This is the code on the original page here I have only given the script as I am just using the click event of my div to send the values
<script>
function displayRecords(numRecords, pageNum,x,catg) {
$.ajax({
type: "GET",
url: "button.php",
data: {
show:numRecords,
pagenum:pageNum,
val12:x,
catg12:catg,
},
cache: false,
success: function(data) {
$("#tabs1-html").html(data);
}
});
}
function changeDisplayRowCount(numRecords) {
displayRecords(numRecords, 1);
}
$(document).ready(function() {
$('.tab12').click(function(){
var catg=$('#cat').val();
var x =$(this).val();
displayRecords(5,1,x,catg);
});
});
</script>
now for the code on my page 1
here
<script type="text/javascript">
function get_data(no,x,catg) {
$.ajax({
type:'post',
url:'question_call.php',
data:{
row_no:no,
X:x,
category:catg,
},
success:function(response) {
document.getElementById("pagination_div").innerHTML=response;
}
});
}
$(document).ready(function() {
$('#tota_page_div').click(function(){
var catg = $category.val();
var x = $X.val();
get_data(no,x,catg);
});
});
</script>
and these are the values where i saved the previous ones
$X = $_GET['val12'];
$category = $_GET['catg12'];
Now when I try to use print_r on my page 2 it only shows row_no not catg12 and val12

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

Two ajax post simultaneously on one link click jquery

I am using one link which has class name next and id end.
On clcik on it both class name and id i am using jquery post.
The issue i am getting is sometimes the ajax request fires multiple times on one click.on one click i am getting data from one url and simultaneously saving these data into db by another url.So sometimes there are some issues coming while inserting into db.sometimes null values enters and sometimes multiple rows entering into db.So how can i write these two functions so that both will work perfectly?
$('.next').live('click', function (e) {
e.preventDefault();
var result = [];
var answer = [];
var le = '';
$('.answertext').each(function (index, element) {
result.push($(this).val());
});
$('.answer').each(function (index, element) {
answer.push($(this).val());
});
le = $('#level').val();
mle = $('#mainlevel').val();
$.ajax({
url: 'matchanswers.php',
type: 'POST',
data: {
result: result,
answer: answer,
level: le,
mle: mle
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data) {
$('.quizform').html(data);
}
});
});
$('#end').live('click', function (e) {
e.preventDefault();
var sublev = $('#level').val();
var score = $('#count').val();
if (sublev < 11) {
$.ajax({
url: 'submitanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data2) {}
});
} else {
$.ajax({
url: 'getanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data3) {
if (data3) {
$('.quizform').html("");
$('form :input').attr('disabled', 'disabled');
$('#logout').removeAttr("disabled");
var obj = $.parseJSON(data3);
$('#sum').html("Your Total Score for level - " + obj[0] + " is " + obj[1] + " in " + obj[2] + "secs");
}
}
});
}
});
You are firing click on same click even if id and class are different the link is same.
$('.next').live('click', function(e)
fires one ajax call and
$('#end').live('click', function(e)
fires another, what you can do is fire one ajax on success of other
$('.next').live('click', function(e) { ...
success: function(data) { $.ajax({
url: 'submitanswers.php', }
but this is not good practice
Simply check for the event trigger like :
$('.next').live('click', function (e) {
if(e.handled !== true){ // This will prevent event triggering more then once
e.handled = true;
//Your code
}
});
$('#end').live('click', function (e) {
if(e.handled !== true){ // This will prevent event triggering more then once
e.handled = true;
//Your code
}
});
By doing so, you will stop multiple event trigger which is quite a common problem and should solve your problem.
Edit :
Your full code will be :
$('.next').live('click', function (e) {
if (e.handled !== true) { // This will prevent event triggering more then once
e.handled = true;
//Your code
e.preventDefault();
var result = [];
var answer = [];
var le = '';
$('.answertext').each(function (index, element) {
result.push($(this).val());
});
$('.answer').each(function (index, element) {
answer.push($(this).val());
});
le = $('#level').val();
mle = $('#mainlevel').val();
$.ajax({
url: 'matchanswers.php',
type: 'POST',
data: {
result: result,
answer: answer,
level: le,
mle: mle
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data) {
$('.quizform').html(data);
}
});
}
});
$('#end').live('click', function (e) {
if (e.handled !== true) { // This will prevent event triggering more then once
e.handled = true;
//Your code
e.preventDefault();
var sublev = $('#level').val();
var score = $('#count').val();
if (sublev < 11) {
$.ajax({
url: 'submitanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data2) {}
});
} else {
$.ajax({
url: 'getanswers.php',
type: 'POST',
data: {
sublev: sublev,
score: score
},
async: true,
beforeSend: function () {
// show indicator
},
complete: function () {
// hide indicator
},
success: function (data3) {
if (data3) {
$('.quizform').html("");
$('form :input').attr('disabled', 'disabled');
$('#logout').removeAttr("disabled");
var obj = $.parseJSON(data3);
$('#sum').html("Your Total Score for level - " + obj[0] + " is " + obj[1] + " in " + obj[2] + "secs");
}
}
});
}
}
});

Cannot get variable to send using $.ajax({data}) to PHP

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.

Categories