How to save to database by using ajax - html

I have a code which is works fine, but the data cannot save to the database. I want to insert cost, currency_rate, profit_rate and pprice to database through Ajax. Here are the code of javascript and update.php, I have tried to modify the code to save in my Mysql server, but it didn't success. Can someone help with this?
javascript
$(".profitRate").change(function() {
var myArray = [];
//find closest table->next table
var elem = $(this).closest('table').next('table');
var action = elem.find('tr').data('action');
console.log(action)
var profitRate = Number($("#profitRate").val());
//looping
elem.find('tr').each(function() {
//get cost
var cost = $(this).find('input[name=cost]').val();
//get curency rate
var currecy_rate = $(this).find('select[name=currency_rate]').val();
//calculate profit
var profit_total = Math.round(cost * profitRate * currecy_rate)
$(this).find('input[name=pprice]').val(profit_total)
//add to json object
auto_array = {};
auto_array["cost"] = cost;
auto_array["currecy_rate"] = currecy_rate;
auto_array["pprice"] = profit_total;
myArray.push(auto_array) //push to array
});
console.log(myArray)
form_data = elem.find('tr').data('action');
$.ajax({
data: {
action: action,
form_data: form_data,
},
url: 'update.php',
type: 'post',
beforeSend: function() {
},
success: function(data) {
if(data == 1){
}
}
});
})
update.php
<?php
if ($_POST['action'] == 'update_price') {
parse_str($_POST['form_data'], $my_form_data);
$id = $my_form_data['id'];
$cost = $my_form_data['cost'];
$profit_rate = $my_form_data['profit_rate'];
$currency_rate = $my_form_data['currency_rate'];
$pprice = $my_form_data['pprice'];
$sql = $query = $finalquery = $sqlresult = '';
if ($cost){
$sql.="cost='$cost',";
}
if ($profit_rate){
$sql.="profit_rate='$profit_rate',";
}
if ($currency_rate){
$sql.="currency_rate='$currency_rate',";
}
if ($pprice){
$sql.="pprice='$pprice',";
$finalquery = rtrim($sql,',');
$query="UPDATE `gp_info` SET $finalquery where id=$id";
$sqlresult=mysql_query($query);
if($sqlresult){
$reback=1;
}else{
$reback=0;
}
echo $reback;
}
}

Related

JSON Call from view to controller and show JSON object data in view in ASP.NET Core 6 MVC

I have written code in an ASP.NET Core 6 controller and calling this from view. This code gives response to my view but I don't know how to parse the data in view.
Previously I was using JsonrequestBehaviour.Allowget which is now deprecated in .NET 6. Please help me for better appraoch of json call which can return any dynamic object.
Here is my controller code:
public IActionResult GetAccountLevelAndCode(Int32 GroupAccountID, Int32 Companyid)
{
string AccountLevels = ""; string Returnerror; string ReturnBranches;
DataTable AL = new GetDataClass().GetAccountNoAndAndLevels(GroupAccountID, Companyid, out Returnerror);
//a = (GLChartOFAccountModel)AL.Rows[0].ConvertDataRowToObject(a);
string Sql = #"select cab.BranchID from GLChartOFAccount ca inner join GLChartOfAccountBranchDetail cab on ca.GLCAID=cab.GLCAID where cab.GLCAID=" + GroupAccountID;
DataTable dt = new DataTable();
dt = StaticClass.SelectAll(Sql).Tables[0];
AccountLevels = JsonConvert.SerializeObject(AL);
ReturnBranches = JsonConvert.SerializeObject(dt);
Returnerror = JsonConvert.SerializeObject(Returnerror);
return Json(new { AccountLevels, ReturnBranches, Returnerror });
}
Following is my view call and response allocation:
function GetAccountNoandLevel() {
var DATA={"GroupAccountID" : $('#isParent').val(), Companyid : #Model.CompanyID }
var execCode = true;
$.ajax({
async: false,
type: "POST",
url: "/GLChartOFAccount/GetAccountLevelAndCode",
data: DATA,
dataType: "json",
success: function (data) {
try {
var c = JSON.parse(data.AccountLevels)
var b = JSON.parse(data.ReturnBranches)
var er = JSON.parse(data.Returnerror)
if (b.length>0) {
$("#BrachIDs option").each(function () {
var idParent = $(this).parent().attr("id");
this.disabled = true;
});
var dataarray = '';
for (var i = 0; i < b.length; i++) {
dataarray += b[i]["BranchID"] + ',';
}
dataarray = dataarray.replace(/,\s*$/, "");
var data = dataarray.split(",");
$("#BrachIDs").val(data);
$("#BrachIDs").change();
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
$("#BrachIDs option").filter("[value='" + data[i] + "']").attr('disabled', false);
}
}
}
else {
$("#BrachIDs option").each(function () {
var idParent = $(this).parent().attr("id");
this.disabled = false;
});
$("#BrachIDs option:selected").removeAttr("selected");
}
if (ShowErrorOK(er)) {
$('#GLCode').val('');
}else{
RowToFillValues(c)
}
} catch (e) {
//console.log(e + " GetAccountNoandLevel "); document.getElementById("DisplayErrorMessage").innerText = e.message; $('#btnTriggerMessage').click(); execCode = false; return false;
console.log(e + " GetAccountNoandLevel "); console.log(e.message)
}
},
error: function (err) {
//console.log(err.responseText); document.getElementById("DisplayErrorMessage").innerText = "AJAX error in request: " + JSON.stringify(err.statusText + " " + err.status) + " GetAccountNoandLevel::Unable To Get Details"; $('#btnTriggerMessage').click(); execCode = false; return false;
console.log("AJAX error in request: " + JSON.stringify(err.statusText + " " + err.status) + " GetAccountNoandLevel::Unable To Get Details")
}
});
if (execCode) {
}
}
The response data is showing undefined...
you don't need serialize and parse manually, it will be done automaticaly
return new JsonResult(new { AccountLevels=AL, ReturnBranches=dt, Returnerror= Returnerror });
and ajax
var c = data.AccountLevels;
var b = data.ReturnBranches;
var er = data.Returnerror;

Display JSON result in table Laravel 5.8

I want to display the JSON results to my HTML table in Laravel 5.8.
The result returned from the controller is as follows.
[[{"logged_on":"2019-06-24 00:00:00"},{"logged_on":"2019-06-21 00:00:00"}]]
My Ajax success function is as follows:
$.ajax({
url: url,
type: "get",
data: {user_id:user_id},
contentType: "application/json",dataType: "json",
success: function(data){ // What to do if we succeed
if(data){
alert(data);
var len = data.length;
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].logged_on){
txt += "<tr><td>"+data[i].logged_on;
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
else{
alert("fails");
}
}
});
Below is my controller function
$user_id = $requests->input('user_id');
$data = UserLogins::select('logged_on')->where('user_id',$user_id)->get()->toArray();
return response()->json(array($data));
But I am not getting the result in my table.
$user_id = $requests->input('user_id');
$data = UserLogins::select('logged_on')->where('user_id',$user_id)->get()->toArray();
return response()->json($data); // remove array() because $data return array

How can I turn part of my casperjs script into a function so I can use it multiple times

Okay, so here is a part of my casperjs script below which works fine
if(casper.exists(ac1)){
var uel = "https://example.ws/send.html?f=1099817";
this.thenOpen(uel, function() {
casper.wait(10000, function() {
casper.then(function() {
this.evaluate(function() {
var amount = 0.29
var result = amount * 0.019
var result2 = result.toFixed(6);
var fresult = amount - result2;
var needed = fresult.toFixed(3);
document.getElementById('account').value = 'ydfg028';
document.getElementsByName('data')[0].value = needed;
});
this.click("input#sbt.button[type='submit']");
casper.wait(10000, function() {
casper.then(function() {
this.capture("filenadfgmedsfg.jpg");
var el2 = this.getHTML();
fs.write('results23.html', el2, 'w');
});
});
});
});
});
} else {
this.exit();
}
The problem I have is over 14 of the following statements
if(casper.exists()){
So what I am trying to do, is use the casperjs steps as a function. This is what I have tried below, but it just does nothing and casperjs ends when it reaches the function. Here's what I am trying
This is the casperjs function I have made
function casperstep(amount, user, location) {
var uel = "https://example.ws/send.html?f=" + location;
this.thenOpen(uel, function() {
casper.wait(10000, function() {
casper.then(function() {
this.evaluate(function() {
var result = amount * 0.019
var result2 = result.toFixed(6);
var fresult = amount - result2;
var needed = fresult.toFixed(3);
document.getElementById('account').value = user;
document.getElementsByName('data')[0].value = needed;
});
this.click("input#sbt.button[type='submit']");
casper.wait(10000, function() {
casper.then(function() {
this.capture("filenadfgmedsfg.jpg");
var el2 = this.getHTML();
fs.write('results23.html', el2, 'w');
});
});
});
});
});
}
Then when I try the following
if(casper.exists(ac1)){
casperstep(0.29, "username", "3245324");
}
it just does not work at all. The casper steps just do not fire. How can I fix this in theory? It should have worked.
What I have been trying with your answers...
My function
casper.captchaget = function (selector) {
var Loc = this.getHTML(selector, true).match(/src="(.*?)"/)[1];
var Ilocation = 'https://perfectmoney.is' + Loc;
var image = Loc;
var imagesplit = image.split ('?');
var split1 = imagesplit[1];
var string = split1 + ".jpg";
this.download(Ilocation, string);
}
and how I am trying to use it
casper.then(function(){
this.captchaget('img#cpt_img');//this.casperstep(0.29, "username", "3245324");
});
I tried the above to test out using casper extension.
Well, you want to add your own method to a casper object instance : http://casperjs.readthedocs.org/en/latest/extending.html
so :
casper.casperstep = function (amount, user, location) {
{your instructions....}
}
Then call it :
casper.start();
casper.then(function(){
if(casper.exists(ac1)){
casper.casperstep(0.29, "username", "3245324");//this.casperstep(0.29, "username", "3245324");
}
})
.run(function() {
test.done();
});
Old-monkey patching :)
To see other ways to do it : Custom casperjs modules

comparing json submitted array and sql returned array and printing difference in text file

I am submitting a javascript array to another php page via ajax which runs a query and returns another array. Then i would like to compare these two arrays and print the difference in a text file. The code give below is creating a text file with no data in it.
Here is the code
$('#tabletomodify').on('change','.street',
function (event)
{
event.preventDefault();
var row=( $(this).closest('tr').prop('rowIndex') );
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var ideSelected= this.id;
var values = '[';
values+=valueSelected+",";
for ($i=3;$i<row;$i++)
{
var dv="selectcity"+$i;
var dv1=document.getElementById(dv).value;
var sl="street"+$i;
var sl1=document.getElementById(sl).value;
var po="building"+$i;
var po1=document.getElementById(po).value;
var concat=dv1+sl1+po1;
values+=''+concat+',';
}
values = values.substring(0,values.length-1);
values += ']';
$.ajax({
url: "get_buildings.php",
type: 'POST',
data: {data: values} ,
success: function(){
alert("Success!")
}
});
the value sent to the get_buildings.php is
[newyork::roosevelt st,springfieldevergreen terraceno42,quahogspooner streetno43]
Php code get_buildings.php:-
$a1='newyork::roosevelt st';
$sl= explode("::",$a1);
$a=$sl[1];
$connection_buildings= mysqli_connect('localhost', 'xxxx', 'xxxx', 'DETAILS') or die ('Cannot connect to db');
$sql_query_3 = "select buildings from $a";
$result_query_3=mysqli_query($connection_buildings,$sql_query_3) or die ("check it");
$options=array();
while ($row = $result_query_3->fetch_assoc())
{
$name = $row['buildings'];
$val=$a.$sl[0].$name;
array_push($options,$val);
}
$result = array_diff($_POST['data'], $options);
$fp = fopen("textfile.txt", "w");
fwrite($fp, $result);
fclose($fp);
mysqli_close($connection_buildings);

jquery cookies for different countries link

I am trying to do cookie stuff in jquery
but it not getting implemented can you guys fix my problem
html code
<a rel="en_CA" class="selectorCountries marginUnitedStates locale-link" href="http://www.teslamotors.com/en_CA">united states</a>
<a rel="en_US" class="selectorCountries marginSecondCountry locale-link" href="http://www.teslamotors.com/en_CA">canada</a>
<a rel="en_BE" class="selectorCountries marginCanadaFrench locale-link" href="http://www.teslamotors.com/en_BE">canada(french)</a>
i am providing my js code below
http://jsfiddle.net/SSMX4/76/
when i click the different country links in the pop up it should act similar to this site
http://www.teslamotors.com/it_CH
$('.locale-link').click(function(){
var desired_locale = $(this).attr('rel');
createCookie('desired-locale',desired_locale,360);
createCookie('buy_flow_locale',desired_locale,360);
closeSelector('disappear');
})
$('#locale_pop a.close').click(function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',3,360);
}
else if (show_blip_count < 3 ) {
eraseCookie('show_blip_count');
createCookie('show_blip_count',3,360);
}
$('#locale_pop').slideUp();
return false;
});
function checkCookie(){
var cookie_locale = readCookie('desired-locale');
var show_blip_count = readCookie('show_blip_count');
var tesla_locale = 'en_US'; //default to US
var path = window.location.pathname;
// debug.log("path = " + path);
var parsed_url = parseURL(window.location.href);
var path_array = parsed_url.segments;
var path_length = path_array.length
var locale_path_index = -1;
var locale_in_path = false;
var locales = ['en_AT', 'en_AU', 'en_BE', 'en_CA',
'en_CH', 'de_DE', 'en_DK', 'en_GB',
'en_HK', 'en_EU', 'jp', 'nl_NL',
'en_US', 'it_IT', 'fr_FR', 'no_NO']
// see if we are on a locale path
$.each(locales, function(index, value){
locale_path_index = $.inArray(value, path_array);
if (locale_path_index != -1) {
tesla_locale = value == 'jp' ? 'ja_JP':value;
locale_in_path = true;
}
});
// debug.log('tesla_locale = ' + tesla_locale);
cookie_locale = (cookie_locale == null || cookie_locale == 'null') ? false:cookie_locale;
// Only do the js redirect on the static homepage.
if ((path_length == 1) && (locale_in_path || path == '/')) {
debug.log("path in redirect section = " + path);
if (cookie_locale && (cookie_locale != tesla_locale)) {
// debug.log('Redirecting to cookie_locale...');
var path_base = '';
switch (cookie_locale){
case 'en_US':
path_base = path_length > 1 ? path_base:'/';
break;
case 'ja_JP':
path_base = '/jp'
break;
default:
path_base = '/' + cookie_locale;
}
path_array = locale_in_path != -1 ? path_array.slice(locale_in_path):path_array;
path_array.unshift(path_base);
window.location.href = path_array.join('/');
}
}
// only do the ajax call if we don't have a cookie
if (!cookie_locale) {
// debug.log('doing the cookie check for locale...')
cookie_locale = 'null';
var get_data = {cookie:cookie_locale, page:path, t_locale:tesla_locale};
var query_country_string = parsed_url.query != '' ? parsed_url.query.split('='):false;
var query_country = query_country_string ? (query_country_string.slice(0,1) == '?country' ? query_country_string.slice(-1):false):false;
if (query_country) {
get_data.query_country = query_country;
}
$.ajax({
url:'/check_locale',
data:get_data,
cache: false,
dataType: "json",
success: function(data){
var ip_locale = data.locale;
var market = data.market;
var new_locale_link = $('#locale_pop #locale_link');
if (data.show_blip && show_blip_count < 3) {
setTimeout(function(){
$('#locale_msg').text(data.locale_msg);
$('#locale_welcome').text(data.locale_welcome);
new_locale_link[0].href = data.new_path;
new_locale_link.text(data.locale_link);
new_locale_link.attr('rel', data.locale);
if (!new_locale_link.hasClass(data.locale)) {
new_locale_link.addClass(data.locale);
}
$('#locale_pop').slideDown('slow', function(){
var hide_blip = setTimeout(function(){
$('#locale_pop').slideUp('slow', function(){
var show_blip_count = readCookie('show_blip_count');
if (!show_blip_count) {
createCookie('show_blip_count',1,360);
}
else if (show_blip_count < 3 ) {
var b_count = show_blip_count;
b_count ++;
eraseCookie('show_blip_count');
createCookie('show_blip_count',b_count,360);
}
});
},10000);
$('#locale_pop').hover(function(){
clearTimeout(hide_blip);
},function(){
setTimeout(function(){$('#locale_pop').slideUp();},10000);
});
});
},1000);
}
}
});
}
This will help you ALOT!
jQuery Cookie Plugin
I use this all the time. Very simple to learn. Has all the necessary cookie functions built-in and allows you to use a tiny amount of code to create your cookies, delete them, make them expire, etc.
Let me know if you have any questions on how to use (although the DOCS have a decent amount of instruction).