Send JSON Array to MySql database - javascript

I need to send array to my mysql database.
I've created a JSON array and dont know how to post it to php to transfer to db.
$( function () {
$( '#orderForm' ).on( 'submit', function ( event ) {
event.preventDefault();
var myData = [],
keys = ['item', 'qty', 'price'],
url = this.action;
$( '#orderTable' ).find( 'tr:gt(0)' ).each( function ( i, row ){
var oRow = {};
$( row ).find( 'td' ).each( function ( j, cell ) {
oRow[keys[j]] = $( cell ).text();
} );
myData.push( oRow );
} );
console.log( myData );
console.log( JSON.stringify( myData ) );
} );
} );
I need to post it item->item, qty->qty, price->price to the db.
I've tried :
$.ajax( {
url: 'tc_menu',
type: 'POST',
data: JSON.stringify( myData ),
success: function ( data ) {
console.log( "success:", data );
},
failure: function ( errMsg ) {
console.error( "error:", errMsg );
}
} );
Data stores whole page, but not (stringified myData). And I still cant get it at php code by $_POST and json_decode
Data stores whole page, but not stringified myData and I can't get it at php code by $_POST and json_decode
php code
`if(isset($_POST['submitted_m'])){
$myData = serialize($_POST['data']);
$sqli = "INSERT INTO tc_cafe_orders SET item='".$myData."' ";
if (mysqli_query($db, $sqli)) {
$msg = "New Order added!";
echo "<script>
alert(\"$msg\");
window.location.replace('tc_menu.php');
</script>";}
else {echo "Error:".$sql."<br>".mysqli_error($db);}}`

Try this one for js
$(function () {
$('#orderForm').on( 'submit', function ( event ) {
event.preventDefault();
var myData = [],
keys = ['item', 'qty', 'price'],
url = this.action;
$( '#orderTable' ).find( 'tr:gt(0)' ).each( function ( i, row ){
var oRow = {};
$( row ).find( 'td' ).each( function ( j, cell ) {
oRow[keys[j]] = $( cell ).text();
} );
myData.push( oRow );
} );
console.log( myData );
console.log( JSON.stringify( myData ) );
data_to_server = JSON.stringify(myData);
});
$.post("*your_php_file*", {
data: data_to_server;
}).done(function (data_returned) {
// any your code
});
});
And seems you have mismatch in PHP code - trying to serialize() instead of json_decode()

Remove nested click event and closure.
e.g.
$( '#orderForm' ).on( 'submit', function ( event ) {
$( '#orderForm' ).on( 'submit', function ( event ) {
} );
} );
Than try again.
And your MySQL insert statement in php
$sqli = "INSERT INTO tc_cafe_orders SET item='".$myData."' ";
is not ok.
Learn more about MySQL insert statement here https://www.w3schools.com/php/php_mysql_insert.asp

Related

jQuery Autocomplete, pass parameters into database

Hlleo, please help me in figuring this our from an example i took this and is working fine,
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
var availableTags = [
{key: "1",value: "NAME 1"},{key: "2",value: "NAME 2"},{key: "3",value: "NAME 3"},{key: "4",value: "NAME 4"},{key: "5",value: "NAME 5"}
];
$( "#project-name" ).autocomplete({
minLength: 0,
source: availableTags,
focus: function( event, ui ) {
$( "#project-name" ).val( ui.item.value );
return false;
},
select: function( event, ui ) {
$( "#project-name" ).val( ui.item.value );
$( "#project-id" ).val( ui.item.key );
return false;
}
});
});
</script>
<form action="search" method="post" >
<input id="project-name" name="project2" id="searchbox"/>
<input type="text" id="project-id" />
</form>
but for me i need it from database so i called the source as url and passed data to it as parameters like this
but in here only the console part works but the input is not populated,
What i want is to populate the input with label value(header Id) and store the id(task_summary_id) came along with it in another hidden input field when the item is selected from the list
So i did this to the original code
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
// var output = '';
// $('#project-name').keyup(function(){
// var query = $(this).val();
// if(query != '')
// {
// console.log(query);
// $.ajax({
// url:"autoCompleteNew.php",
// method:"POST",
// data:{query:query,cl:4},
// success:function(data)
// {
// console.log(data);
// output = data;
//
//
//
//
// }
// });
// }
// });
$("#project_name").autocomplete({
//var output = '';
source: function(request, response) {
console.log(request.term);
$.ajax({
url: 'autoCompleteNew.php',
method:"POST",
data: {
query : request.term,
cl : 4
},
success: function(data) {
//response(data);
// output = data;
console.log(data); //here i am getting the correct log
// var parsed = JSON.parse(data);
},
// console.log(output);
});
},
focus: function( event, ui ) {
$( "#project_name" ).val( ui.item.value );// nothing here nothing in autocomplete
return false;
},
select: function( event, ui ) {
$( "#project_name" ).val( ui.item.value );// but nothing here
$( "#project-id" ).val( ui.item.key );
return false;
}
});
// $( "#project_name" ).autocomplete({
// minLength: 2,
// source: 'autoCompleteNew.php',
// data:{query:'gb',cl:4},
// focus: function( event, ui ) {
// $( "#project_name" ).val( ui.item.value );
// return false;
// },
// select: function( event, ui ) {
// $( "#project-name" ).val( ui.item.value );
// $( "#project-id" ).val( ui.item.key );
//
// return false;
// }
// });
// var availableTags = [
// {key: "1",value: "Mukund"},{key: "2",value: "Nandu"},{key: "3",value: "Dimble"},{key: "4",value: "Alisha"},{key: "5",value: "Parvathy"}
// ];
});
</script>
<form action="search" method="post" >
<input id="project_name" name="project2" id="searchbox"/>
<input type="text" id="project-id" />
</form>
please help me in figuring this out
my php code
$usr = $_POST['term'];
$cl = $_POST['cl'];
//$usr = 'm';
$output = '';
$usr = strtolower($usr);
//$retVar = array();
$db_handle = new DBController();
$query = "select task_summary_id as 'key',task_header_id as 'value' from gb_task_summary where LCASE(task_header_id) like '$usr%' and task_header_client_id = $cl";
//echo $query;
$i=0;
// $output = '<ul class="list-unstyled" id ="listUl">';
$results = $db_handle->runQuery($query);
if(!empty($results))
{
$retVar=$results;
}
else
{
$retVar = 'N';
}
// foreach ($retVar as $key => $value) {
// $output .= '<li id ="listLI">'.$value["task_header_id"].'</li>';
// $output .='<ul id ="listUl">';
// $output .= '<dd class="unselectable" id ="listDD">'.$value["task_header_name"].'</dd>';
// $output .='</ul>';
//
// }
//
// $output .= '</ul>';
echo json_encode($retVar);
my json response for '1111'
[{"key":"499","value":"1111"},{"key":"500","value":"1134"},{"key":"501","value":"1195"},{"key":"502","value":"1211"},{"key":"503","value":"1197"},{"key":"504","value":"1085"},{"key":"505","value":"1193"},{"key":"506","value":"1090"},{"key":"507","value":"1076"},{"key":"508","value":"1196"},{"key":"543","value":"1471"},{"key":"544","value":"1472"},{"key":"566","value":"1111"},{"key":"569","value":"1111"},{"key":"570","value":"1111"},{"key":"571","value":"1111"},{"key":"577","value":"1111"},{"key":"584","value":"1475"},{"key":"585","value":"1454"},{"key":"586","value":"1476"},{"key":"587","value":"1705"},{"key":"588","value":"1541"},{"key":"589","value":"1707"},{"key":"590","value":"1722"},{"key":"591","value":"1721"},{"key":"592","value":"1720"},{"key":"593","value":"1719"},{"key":"594","value":"1718"},{"key":"595","value":"1717"},{"key":"596","value":"1711"},{"key":"597","value":"1710"},{"key":"598","value":"1709"},{"key":"599","value":"1701"},{"key":"600","value":"1704"},{"key":"601","value":"1751"},{"key":"602","value":"1746"},{"key":"603","value":"1784"},{"key":"604","value":"1736"},{"key":"622","value":"1755"},{"key":"623","value":"1769"},{"key":"624","value":"1796"},{"key":"625","value":"1797"},{"key":"626","value":"1803"},{"key":"647","value":"1789"},{"key":"648","value":"1811"},{"key":"649","value":"1813"},{"key":"650","value":"1820"},{"key":"651","value":"1825"},{"key":"652","value":"1828"},{"key":"658","value":"1836"},{"key":"659","value":"1839"},{"key":"660","value":"1847"},{"key":"661","value":"1706"},{"key":"673","value":"1869"},{"key":"674","value":"1872"},{"key":"686","value":"1899"},{"key":"687","value":"1901"},{"key":"691","value":"1907"},{"key":"692","value":"1908"},{"key":"693","value":"1917"},{"key":"701","value":"1803"},{"key":"702","value":"1807"},{"key":"703","value":"1879"},{"key":"704","value":"1880"},{"key":"705","value":"1881"},{"key":"706","value":"1810"},{"key":"707","value":"1858"},{"key":"708","value":"1902"},{"key":"709","value":"1918"},{"key":"710","value":"1893"},{"key":"730","value":"1952"},{"key":"734","value":"1954"},{"key":"735","value":"1958"},{"key":"736","value":"1954"},{"key":"737","value":"1959"},{"key":"746","value":"1958"},{"key":"749","value":"1990"},{"key":"750","value":"1993"},{"key":"751","value":"1997"},{"key":"754","value":"1976"},{"key":"776","value":"1998"},{"key":"785","value":"1948"},{"key":"894","value":"1705"},{"key":"1008","value":"1111"},{"key":"1031","value":"1976"},{"key":"1375","value":"1111"},{"key":"1556","value":"1976"},{"key":"1819","value":"1624"},{"key":"1838","value":"1111"}]

How to store Javascript value in php variable shown in alert

How to pass javascript variable to php variable my code is- I want to store alert value in php variable.
<script type="text/javascript" >
$(document).ready( function() {
$( '#container' ).html( '<ul class="filetree start"><li class="wait">' + 'Generating Tree...' + '<li></ul>' );
getfilelist( $('#container') , 'Sample' );
function getfilelist( cont, root ) {
$( cont ).addClass( 'wait' );
$.post( 'Foldertree.php', { dir: root }, function( data ) {
$( cont ).find( '.start' ).html( '' );
$( cont ).removeClass( 'wait' ).append( data );
if( 'Sample' == root )
$( cont ).find('UL:hidden').show();
else
$( cont ).find('UL:hidden').slideDown({ duration: 500, easing: null });
});
}
$( '#container' ).on('click', 'LI A', function() {
var entry = $(this).parent();
if( entry.hasClass('folder') ) {
if( entry.hasClass('collapsed') ) {
entry.find('UL').remove();
getfilelist( entry, escape( $(this).attr('rel') ));
entry.removeClass('collapsed').addClass('expanded');
window.alert($(this).attr('rel'))
$( '#selected_file1' ).text( "Folder: " + $(this).attr( 'rel' ));
<?php
?>
}
else {
entry.find('UL').slideUp({ duration: 500, easing: null });
entry.removeClass('expanded').addClass('collapsed');
}
} else {
$( '#selected_file' ).text( "File: " + $(this).attr( 'rel' ));
}
return false;
});
});
</script>
There is difference between Javascript and PHP, PHP is a server-side script language while Javascript is a client-side script language. See https://www.sqa.org.uk/e-learning/ClientSide01CD/page_18.htm
Use the advantage of AJAX instead for your problem

database connectivity not working in ajax call- laravel

My javascript is:
$( "#exerciseFetch" ).change(function( event ) { //alert("super");
// var _token = $( this ).find( 'input[name=_token]' ).val()
var mytoken = $('#mytoken').attr('value');
ajaxContent = [
{"_token": mytoken},
{"val" : $( "#exerciseFetch" ).val()}
]
$.ajax({
type: "POST",
url: 'exerciseFetchAjaxCall',
data: { ajaxContent }
// data: { "_token": mytoken }
}).done(function( msg ) {
alert( msg );
var reqContent = msg;
$("#dynamic").html(reqContent);
});
});
my route:
Route::group(array('prefix' => 'admin', 'namespace' => 'App\Controllers\Admin'), function()
{
Route::post('exerciseFetchAjaxCall', 'ExerciseController#exerciseAjaxCall');
});
my controller code:
public function exerciseAjaxCall(){
$row = $_POST['ajaxContent'];
// $row[1]['val']
$muscles = Muscular::whereIn('Status',array(1))->orderBy('id', 'desc')->paginate(10);
// return $this->content = View::make('admin.exercise.displayMusclarGroupAjax',array('row' => $row ));
return $this->content = View::make('admin.exercise.displayMusclarGroupAjax',array('muscles' => $muscles ));
}
my view code:
#if($muscles && count($muscles) > 0)
#foreach($muscles as $muscular)
<?php
$icons = ["fa-icon-user", "fa-icon-user", "fa-icon-user inactive"];
$typeArray = [
'1'=> 'Resistance',
'2'=> 'Cardio'
];
$typeArray[3] = 'Resistance & Cardio';
?>
<tr>
<td data-title="muscular_name">{{ ucfirst($muscular->muscular_name) }}</td>
<td data-title="muscular_type">{{ $typeArray[$muscular->type]}}</td>
</tr>
<?php
$i++;
?>
#endforeach
#endif
#if(isset($row) && count($row) > 0)
<?print_r($row);?>
#endif
If I comment out the row contents and comment the muscles content in controller the code returns the values passed but the contents of the muscles are not displayed if uncommented.
I have displayed the muscle contents with the same code in its listing page (but without ajax call) dont know why its not working as I am new to laravel.
Any suggestions would be helpful...
You have syntax error in ajax script, Try this simple $.post() api to make ajax call
$( "#exerciseFetch" ).change(function( event ) { //alert("super");
// var _token = $( this ).find( 'input[name=_token]' ).val()
var mytoken = $('#mytoken').attr('value'),
ajaxContent = {
"_token" : mytoken,
"val" : $( "#exerciseFetch" ).val()
};
//make ajax call
$.post( "exerciseFetchAjaxCall", ajaxContent ).done(
function( msg ) {
alert( msg );
var reqContent = msg;
$("#dynamic").html(reqContent);
}
);
});
Above should do, If nothing is returning from DB please try dd() in controller to see the returned result
//are you sure `Status` is not in small case
$muscles = Muscular::whereIn('Status',array(1))->orderBy('id', 'desc')->paginate(10);
dd($muscles);

jquery combobox not pulling data with ajax

I'm using the jQuery combobox widget which works fine, but is causing some issues when added dynamically.
What should happen
Visitor uses the combobox to filter/select valid users to add to a
list.
The list has no max number of users that can be added.
There's a [+] toggle button at the end of each user field that allows the Visitor to add another user to the list.
Clicking the button makes an ajax call to add more users to the list, allowing there to be no limit to the max number of users.
Initially, 10 user fields are loaded on screen, and then when they click the [+] button towards the end, the ajax call adds another 10 to the list.
What's Happening
When the form with the list of users is submitted, the users from the initial 10 fields appear fine, but any fields added as part of the ajax call are returned as empty.
Here's the code:
combobox:
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var input,
that = this,
wasOpen = false,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = this.wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
function removeIfInvalid( element ) {
var value = $( element ).val(),
matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( value ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
}
}
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.addClass( "ui-state-default ui-combobox-input " )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
that._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
removeIfInvalid( this );
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
// .tooltip()
.appendTo( wrapper )
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-combobox-toggle" )
.mousedown(function() {
wasOpen = input.autocomplete( "widget" ).is( ":visible" );
})
.click(function() {
input.focus();
// close if already visible
if ( wasOpen ) {
return;
}
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
// input.tooltip({
// // tooltipClass: "tool_toplft"
// });
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
})( jQuery );
ajax code:
$('body').on('click','.add_usr', function(){
if($('.box.noshow').length == 3){
$(this).fadeOut(800);
var count = parseInt($(this).attr('data-ctr')) +1;
$.post('/base/process.php', {action: 'team_add_usr_select', 'count': count}, function(data){
$('.box:last').after(data.output);
});
}
$('.box.noshow').first().fadeIn(800).removeClass('noshow');
$('.box').children('select').removeAttr('disabled');
$('.box.noshow').each(function(){
$(this).children('select').attr('disabled', 'disabled');
});
$('.add_usr').css('display','none');
$('.box:visible').last().children('.add_usr').css('display','inline-block');
if($('.box:visible').length > 1){
$('.del_usr').css('display', 'inline-block');
}
return false;
});
Again, the combobox is working correctly, but when I submit the form, the fields are present but blank.
UPDATE
data outputs an object with the details for me, including the original form information.Here's an example of the output:
form: Object
form: "team_add"
id_leader: "1"
id_team: ""
team_name: "test"
usr: Object
1: "1"
2: "13"
3: "521"
4: "533"
5: "2"
6: "3"
7: "816"
This example was sent with 12 users added. The new fields are added to the form after entry #7 is filled and clicked. Also, I've noticed in this instance it stopped showing additional fields. Previously when testing, it would list 8: "". Now I'm more confused.

show html in auto complete jqueryUi

i use jqueryui for search in my site just like facebook
jquery code:
//search main
function split( val ) {
return val.split( );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#mainsearch" ).bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "/block/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
window.location.replace(ui.item.url);
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
php code:
while($f = mysqli_fetch_array($s,MYSQLI_ASSOC)){
if($userid != $f['id']){
$name = $f['name'].' '.$f['family'];
$url = $siteurl.$f['username'].'/';
array_push($results, array('id' => $f['id'],'value' => $name,'url' => $url));
}
}
echo json_encode($results);
but if i insert image tag like:
<img src='something'>
its just show < img > text not an image when its show result
there is anyway to solve it?
thank you
From the jQuery-ui docs: "If you want the label to be treated as html you can use Scott González' html extension".
ok i solve this problem with code blow:
function split( val ) {
function extractLast( term ) {
return split( term ).pop();
}
$( "#mainsearch" ).autocomplete({
source: function( request, response ) {
$.getJSON( "/block/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
window.location.replace(ui.item.url);
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li style='clear:both'>" )
.append( ""+item.value+"")
.appendTo( ul );
};return val.split( );
}
and php code:
while($f = mysqli_fetch_array($s,MYSQLI_ASSOC)){
if($userid != $f['id']){
$name = $f['name'].' '.$f['family'];$img = getimagesizes($f['image'],50);
$url = $siteurl.$f['username'].'/';
array_push($results, array('id' => $f['id'],'img' => $img,'value' => $name,'url' => $url));
}
}
echo json_encode($results);
.data must convert to html and show your result
as you can see in my qustion example in jqueryui is completely diffrent with this
but with this you can put html in your auto complete :)

Categories

Resources