Getting data from jQuery ajax - javascript

I am trying to make an AJAX filter for car list and I got stuck in the last stage. I have two files, index.php and filter.php.
In index.php I have form with drop-down lists and sliders. Code for sending the form is as follows:
$(document).ready(function(){
$("#send").click(function(){
var salon=$("#salon-list").val();
var make=$("#make-list").val();
var model=$("#model-list").val();
var cenaLow=$("#cenaLow").val();
var cenaHigh=$("#cenaHigh").val();
var tachometrLow=$("#tachometrLow").val();
var tachometrHigh=$("#tachometrHigh").val();
var palivo=$("#palivo-list").val();
var karoserie=$("#karoserie-list").val();
var prevodovka=$("#prevodovka-list").val();
var pohon=$("#pohon-list").val();
var barva=$("#barva-list").val();
var dvere=$("#dvere-list").val();
var objem=$("#objem-list").val();
var stav=$("#stav-list").val();
$.ajax({
type:"post",
url:"filter.php",
data:"salon="+salon+"&make="+make+"&model="+model+"&cenaLow="+cenaLow+"&cenaHigh="+cenaHigh
+"&tachometrLow="+tachometrLow+"&tachometrHigh="+tachometrHigh+"&palivo="+palivo+"&karoserie" +
"="+karoserie+"&prevodovka="+prevodovka+"&pohon="+pohon+"&barva="+barva+"&dveře="+dvere+"&objem" +
"="+objem+"&stav="+stav,
success:function(data){
$("#result").html(data);
}
});
});
});
In the filter.php file I get the data from $_POST and then I search through database. After that I want to echo results into #result div but it does not work. Any echo statement doesn't work, variables I want to list aren't empty, I checked.
echo 'iAmHere'; /*just checking*/
$post["salon"] = htmlspecialchars($_POST["salon"]);
$post["make"] = htmlspecialchars($_POST["make"]);
$post["model"] = htmlspecialchars($_POST["model"]);
$post["cenaLow"] = htmlspecialchars($_POST["cenaLow"]);
$post["cenaHigh"] = htmlspecialchars($_POST["cenaHigh"]);
$post["rokLow"] = htmlspecialchars($_POST["rokLow"]);
$post["rokHigh"] = htmlspecialchars($_POST["rokHigh"]);
$post["tachometrLow"] = htmlspecialchars($_POST["tachometrLow"]);
$post["tachometrHigh"] = htmlspecialchars($_POST["tachometrHigh"]);
$post["palivo"] = htmlspecialchars($_POST["palivo"]);
$post["karoserie"] = htmlspecialchars($_POST["karoserie"]);
$post["prevodovka"] = htmlspecialchars($_POST["prevodovka"]);
$post["pohon"] = htmlspecialchars($_POST["pohon"]);
$post["barva"] = htmlspecialchars($_POST["barva"]);
$post["dvere"] = htmlspecialchars($_POST["dvere"]);
$post["objem"] = htmlspecialchars($_POST["objem"]);
$post["stav"] = htmlspecialchars($_POST["stav"]);
echo '<p class="make">'.$post["make"].'</p>'; /*does not work*/
echo "<script>window.alert('".$_POST["make"]."');</script>"; /*another checking, this works*/
Thanks for any help.

Try this :
$(document).ready(function(){
$("#send").click(function(){
var salon=$("#salon-list").val();
var make=$("#make-list").val();
var model=$("#model-list").val();
var cenaLow=$("#cenaLow").val();
var cenaHigh=$("#cenaHigh").val();
var tachometrLow=$("#tachometrLow").val();
var tachometrHigh=$("#tachometrHigh").val();
var palivo=$("#palivo-list").val();
var karoserie=$("#karoserie-list").val();
var prevodovka=$("#prevodovka-list").val();
var pohon=$("#pohon-list").val();
var barva=$("#barva-list").val();
var dvere=$("#dvere-list").val();
var objem=$("#objem-list").val();
var stav=$("#stav-list").val();
var data= {
make: make,
model: model,
cenaLow: cenaLow,
cenaHigh: cenaHigh,
tachometrLow: tachometrLow,
tachometrHigh: tachometrHigh,
palivo: palivo,
karoserie: karoserie,
prevodovka: prevodovka,
pohon: pohon,
barva: barva,
objem: objem,
stav : stav
};
$.ajax({
type:"post",
url:"filter.php",
data:data,
success:function(data){
$("#result").html(data);
}
});
});
});

From here:
JavaScript inserted as DOM text will not execute.
And this says:
You have to use eval() to execute any script code that you've
inserted as DOM text.
So you can try an alternate approach to test your code (though I've not tested).
In filter.php:
<?php
$post["salon"] = htmlspecialchars($_POST["salon"]);
$post["make"] = htmlspecialchars($_POST["make"]);
$post["model"] = htmlspecialchars($_POST["model"]);
$post["cenaLow"] = htmlspecialchars($_POST["cenaLow"]);
$post["cenaHigh"] = htmlspecialchars($_POST["cenaHigh"]);
$post["rokLow"] = htmlspecialchars($_POST["rokLow"]);
$post["rokHigh"] = htmlspecialchars($_POST["rokHigh"]);
$post["tachometrLow"] = htmlspecialchars($_POST["tachometrLow"]);
$post["tachometrHigh"] = htmlspecialchars($_POST["tachometrHigh"]);
$post["palivo"] = htmlspecialchars($_POST["palivo"]);
$post["karoserie"] = htmlspecialchars($_POST["karoserie"]);
$post["prevodovka"] = htmlspecialchars($_POST["prevodovka"]);
$post["pohon"] = htmlspecialchars($_POST["pohon"]);
$post["barva"] = htmlspecialchars($_POST["barva"]);
$post["dvere"] = htmlspecialchars($_POST["dvere"]);
$post["objem"] = htmlspecialchars($_POST["objem"]);
$post["stav"] = htmlspecialchars($_POST["stav"]);
echo $post["make"];
In index.php:
$.ajax({
...
success:function(res){
$("#result").html(res);
alert(res);
}
});

Try this:
die('<p class="make">'.$post["make"].'</p>');
or
echo '<p class="make">'.$post["make"].'</p>';exit;
instead of
echo '<p class="make">'.$post["make"].'</p>'; /*does not work*/
echo "<script>window.alert('".$_POST["make"]."');</script>"; /*another checking, this works*/
It does not work without an exit. I do not know why but it should do the trick. Also, your code has a lot of room for improvement. Do keep looking for better ways to enhance your skills!! Enjoy!!

Related

How do I pass multiple return value to a laravel controller using ajax

I wan't to pass multiple variable to a laravel controller using ajax that has multiple return value.
JavaScript
$(function(){
var standard = standardRoom();
var n_standard = standard[0];
var xSumStandard = standard[1];
var totalStandard = standard[2];
var quad = quadRoom();
var n_quad = quad[0];
var xSumQuad = quad[1];
var totalQuad = quad[2];
var family = familyRoom();
var n_family = family[0];
var xSumFamily = family[1];
var totalFamily = family[2];
var barkada = barkadaRoom();
var n_barkada = barkada[0];
var xSumBarkada = barkada[1];
var totalBarkada = barkada[2];
$('#formSubmit').on('click', function(){
$.ajax({
url: APP.baseUrl + '/check/next',
data: {'_token': window.Laravel.csrfToken, 'n_standard': n_standard, 'xSumStandard': xSumStandard, 'totalStandard': totalStandard,'n_quad': n_quad,'xSumQuad': xSumQuad,'totalQuad': totalQuad,'n_family': n_family,'xSumFamily': xSumFamily,'totalFamily': totalFamily, 'n_barkada': n_barkada,'xSumBarkada': xSumBarkada,'totalBarkada': totalBarkada},
type: 'POST',
success: function (data) {
console.log('Success')
},
});
});
});
{!! Form::open(['url' => '/request', 'id' => 'formSubmit']) !!}
<input type="submit" id="submitbutton" value="NEXT" style="width:310px;background-color:#5d0b0b">
{!! Form::close() !!}
I tried to follow an instruction on how to access multiple return value here in stack and come up with this. I don't know if this is working or not. But what I need is to just pass all the value that is in the data:
Route
Route::post('check/next', 'Reservation#getRequest');
Now what is the next step in this? How do I get this in the controller? I'm new to laravel and ajax so I'm having a hard time understanding this process
The problem is I'm getting an Undefined index: n_standard
Edit
Controller
public function getRequest(Request $request){
$n_standard = $_GET['n_standard'];
$xSumStandard = $_GET['xSumStandard'];
$totalStandard = $_GET['totalStandard'];
$n_quad = $_GET['n_quad'];
$xSumQuad = $_GET['xSumQuad'];
$totalQuad = $_GET['totalQuad'];
$n_family = $_GET['n_family'];
$xSumFamily = $_GET['xSumFamily'];
$totalFamily = $_GET['totalFamily'];
$n_barkada = $_GET['n_barkada'];
$xSumBarkada = $_GET['xSumBarkada'];
$totalBarkada = $_GET['totalBarkada'];
}
In controller, first of all you should replace $_GET to $_POST / $_REQUEST because your are sending data from ajax through POST.
or
You can also check, you are getting request value or not using below given code.
use Illuminate\Support\Facades\Request;
public function getRequest(Request $request){
$request->all()
}

What does datatable.columns().search().draw() requests or posts in server-side php?

$(document).ready(function() {
var taskList = $("#tasklist").DataTable({
"bProcessing" : true,
"bServerSide" : true,
"sAjaxSource" : 'response.php'
});
$(".search-select").on('change', function() {
var i = $(this).attr('data-column');
var f = $(this).val();
taskList.columns(i).search(f).draw();
});
$(".search-text").on('keyup', function() {
var i = $(this).attr('data-column');
var f = $(this).val();
taskList.columns(i).search(f).draw();
});
});
this is the script i have written and except filtering everything is working.
I don't know in which variable or object I can get the searched row and value.
I have tried : $_REQUEST['columns'][0]['search']['value']
but it is not in the $_REQUEST object.
What should I try now?
If you have Chrome / FF or other browsers developer tools, go to the Network tab and inspect the requests! It could not be more easy. You will see something like
response.php
?sEcho=1
&iColumns=6
&sColumns=%2C%2C%2C%2C%2C
&iDisplayStart=0
&iDisplayLength=10
//>> this section repeats itself for every column, mDataProp_1, mDataProp_2 etc
&mDataProp_0=0
&sSearch_0=
&bRegex_0=false
&bSearchable_0=true
&bSortable_0=true
//<<<
&sSearch=
&bRegex=false
&iSortCol_0=0
&sSortDir_0=asc
&iSortingCols=1
&_=1513773711430
So you get the search term for a columns(i).search(f).draw() serverside by
$columnCount = $_GET['iColumns'];
$searchColumn = -1;
$searchTerm = '';
for ($i=0; $<$columnCount; $i++) {
if (isset($_GET['sSearch_'.$i]) && $_GET['sSearch_'.$i] != '') {
$searchColumn = $i; //i
$searchTerm = $_GET['sSearch_'.$i]; //f
}
}
Try the following code
$searchValue = $_REQUEST['search']['value']

PHP Table inline editing - Javascript Function

I am trying to create an inline edit function on my table, the user should be able to retype the values, and click the 'Save' button to update the database record.
I've hit a problem with the javascript function, its not reverting me to the next page as per 'window.location.href', which would be the php update qry page, that reverts me back to the original page to view the changes made.
The javascript function is meant to get the old id , and all of the possibly new td's within the record, which the user may have inline edited.
I had this working for the id itself, but with the addition of all the new values, ive messed up either on the js function or the action but (may the 'this'?) not exactly sure. I know mysql is rubbish and so on, im focusing on functionality at the time being.
JS FUNCTION
function edit_user(id,a,b,c,d,e,f,g,h,i,j,k) {
var tr = a.parentNode.parentNode;
var awb = String(tr.querySelector(".a").innerHTML);
var tb = b.parentNode.parentNode;
var del = String(tb.querySelector(".b").innerHTML);
var tc = c.parentNode.parentNode;
var vsl = String(tc.querySelector(".c").innerHTML);
var td = d.parentNode.parentNode;
var cli = String(td.querySelector(".d").innerHTML);
var te = e.parentNode.parentNode;
var pcs = String(te.querySelector(".e").innerHTML);
var tf = f.parentNode.parentNode;
var wgt = String(tf.querySelector(".f").innerHTML);
var tg = g.parentNode.parentNode;
var car = String(tg.querySelector(".g").innerHTML);
var th = h.parentNode.parentNode;
var snd = String(th.querySelector(".h").innerHTML);
var ti = i.parentNode.parentNode;
var stt = String(ti.querySelector(".i").innerHTML);
var tj = j.parentNode.parentNode;
var ard = String(tj.querySelector(".j").innerHTML);
var tk = k.parentNode.parentNode;
var ctm = String(tk.querySelector(".k").innerHTML);
// run query on server:
window.location.href = 'http://at-web2.comp.glam.ac.uk/students/14075377/14075377/php/edit-livedashboard-import.php?id='+id+'&newawb='+awbno+'&newvsl='+vsl+'&newcli='+cli+'&newpcs='+pcs+'&newwgt='+wgt+'&newcar='+car+'&newsnd='+snd+'&newstt='+stt+'&neward='+ard;;
return false;}
TABLE ACTION BUTTON
$awb = $get_info["AwbNo"];
echo "<a href='' onclick='return edit_user($awb,here,here,here,here,here,here,here,here,here);'>&nbspSave&nbsp</a>";
PHP UPDATE
include("../dbinfo.inc.php");
$comm=#mysql_connect(localhost,$username,$password);
$rs=#mysql_select_db($database) or die( "Unable to select database");
$id = $_GET['id'];
$newawb = $_GET['awbno'];
$newvsl = $_GET['vsl'];
$newcli = $_GET['cli'];
$newpcs = $_GET['pcs'];
$newwgt = $_GET['wgt'];
$newcar = $_GET['car'];
$newsnd = $_GET['snd'];
$newstt = $_GET['stt'];
$neward = $_GET['ard'];
$sql = "UPDATE tbl_import SET AwbNo='$newawb',ClientCode='$newcli',VesselName='$newvsl',Pieces='$newpcs',Weight='$newwgt',Carrier='$newcar',Sender='$newsnd',Status='$newstt',ArrivalDate='$neward',WHERE AwbNo='$id';";
echo ("id=$id,awb=$newawb,vsl=$newvsl,cli=$newcli,pcs=$newpcs,wgt=$newwgt,car=$newcar,send=$newsnd, status=$newstt, date=$neward .\n\n\n");
mysql_query($sql)or die("Update Error: ".mysql_error());
mysql_close();
//commented header so can see echoed vals sent from js
//header("Location: ../livedashboard.php"); //redirect to relevant page
First thing try to print:
console.log('php/edit-livedashboard-import.php?id='+id+awb+del+vsl+cli+pcs+wgt+car+snd+stt+ard+ctm);
it should be like this:
'php/edit-livedashboard-import.php?id='+id+ '&awb='+awd+'&del='+del...etc;
Second thing:
Add full url instead of dir :
window.location.href = 'php/edit-livedashboard-import.php?id='+id+aw...;
ex.
window.location.href = 'http://example.com/php/edit-livedashboard-import.php?id=...';

Can't create desired json data and read their values correctly (php, ajax)

I'm making a clothes store and I want to display data in modal when product link is clicked. Each product can have more sizes and each size have its quantity.
This line opens modal (this work fine)
<span>View</span>
The code below sends "id" to fetch_id.php file and displays data in modal
<script type="text/javascript">
$(document).ready(function() {
$('.quick-view-btn').bind('click', function() {
var id=$(this).attr("id");
$.ajax({
url:"fetch_id.php",
cache:false,
data:'id='+id,
dataType: "json",
success:function(data){
var aslika = data['artikli']['artslika']; //get picture
var aime = data['artikli']['artime']; //get name
var acijena = data['artikli']['artcijena']; //get price
var artcode = data['artikli']['artcode']; //get art code
var aopis = data['artikli']['artopis'];
$('.a_slika').attr("src", 'slike/'+aslika);
$('.a_ime').html(aime);
$('.a_cijena').html(acijena+' Kn');
$('.a_artcode').html('šifra: '+artcode);
$('.a_opis').html(aopis);
$('.a_id').attr("href", 'single-product.php?id='+artcode);
}
});
});
});
</script>
Here is my fetch_id.php file
$prid = $_GET['id'];
$active = 1;
if ($stmtart = $mysqli->prepare("SELECT aid, art_code, glkat, kat, ime_a, opis, kolicina, cijena, stara_cijena, ocjena, slika, status, datum, xs, s, m, l, xl, xxl, xxxl FROM artikli WHERE status = ? and aid = ? LIMIT 1")) {
$stmtart->bind_param('ii', $active, $prid );
$stmtart->execute();
$stmtart->store_result();
$stmtart->bind_result($a_id, $aart_code, $a_glkat, $a_kat, $a_ime, $a_opis, $a_kolicina, $a_cijena, $a_scijena, $a_ocjena, $a_slika, $a_status, $a_datum, $a_xs, $a_s, $a_m, $a_l, $a_xl, $a_xxl, $a_xxxl);
$stmtart->fetch();
}
if ($stmtvelicine = $mysqli->prepare("SELECT vid, oznaka, kolicina FROM velicine WHERE artid = ? ORDER BY vid ASC")) {
$stmtvelicine->bind_param('i', $prid );
$stmtvelicine->execute();
$stmtvelicine->store_result();
$stmtvelicine->bind_result($v_id, $v_oznaka, $v_kolicina);
}
$artikli = array("artikli" => array("artslika"=>$a_slika, "artime"=>$a_ime, "artcijena"=>$a_cijena, "artcode"=>$aart_code, "artopis"=>$a_opis));
$counter = 0;
while($stmtvelicine->fetch()) {
$counter = $counter + 1;
$velicine = array('vel'.$counter => $v_oznaka);
$komada = array('kom'.$counter => $v_kolicina);
array_push($artikli, $velicine);
array_push($artikli, $komada);
}
$json = json_encode($artikli);
echo $json;
The result I'm receiving is in this format...
{"artikli":{"artslika":"sn.jpg","artime":"Dress","artcijena":"129.56","artcode":"PD1001","artopis":"Default Description"},"0":{"vel1":"XS"},"1":{"kom1":5},"2":{"vel2":"L"},"3":{"kom2":2},"4":{"vel3":"XL"},"5":{"kom3":4}}
The problem is that my "while loop" creates numbers as keys so if some product have many sizes it will have many unknown keys.
Can you help me to read their values with ajax? Is there a better way to solve this?
Thank you very much,
Ivan.

pass angular scope to jquery

anyone has any case like me ? i have to connect another service to my system. the problem is that service is unsupported on JS front-end (im using angularJS). to show form for service i need to complete jQuery form like this :
<script type="text/javascript">
$(function() {
var data = new Object();
data.req_merchant_code = '1';
data.req_chain_merchant = 'NA';
data.req_payment_channel = '15'; // ‘15’ = credit card
data.req_transaction_id = '<?php echo $invoice ?>';
data.req_currency = '<?php echo $currency ?>';
data.req_amount = '<?php echo $amount ?>';
data.req_words = '<?php echo $words ?>';
data.req_form_type = 'full';
getForm(data);
});
</script>
like you see that PHP variable on there with echo, can anyone help me to pass scope variable to that jQuery. i set that variable like this
$scope.dokuPayment = function(){
topUpFactory.createwordsDoku().then(function(data){
console.log(data.data);
var req = data.data;
$scope.invoice = req.invoice;
$scope.words = req.words;
$scope.currency = req.currency;
$scope.amount = req.amount;
console.log(invoice);
$("#doku-modal").modal('show');
});
}
i try to put that scope to parametes like this
<script type="text/javascript">
console.log("form doku");
$(function() {
var data = new Object();
data.req_merchant_code = '3279';
data.req_chain_merchant = 'NA';
data.req_payment_channel = '15'; // ‘15’ = credit card
data.req_transaction_id = {{invoice}};
data.req_currency = {{currency}};
data.req_amount = {{amount}};
data.req_words = {{words}};
data.req_form_type = 'full';
getForm(data);
});
</script>
but doesn't work.. i try to set upperstroup ("") still doesn't work. anyone can help. . thanks
When using AngularJS, try avoiding using jQuery in that way.
$("#doku-modal").modal('show'); - not a good idea to do that in this framework.
This article may give some guidance: http://www.dwmkerr.com/the-only-angularjs-modal-service-youll-ever-need/
In $scope.dokuPayment you can potentially do the same thing what getForm(data) does as long as it does not manipulate the DOM directly.
As a result, you do not have to pass any data to the view as the entire JS logic should be in your Angular services or controllers.
There is simple hack, not sure if it is good practice or not! You can make use of $window scope.
All you need to do is, make angular variables to global variables using $window.{variable name} and access them from outside using window.{variable name}.
See here:
$scope.dokuPayment = function(){
topUpFactory.createwordsDoku().then(function(data){
console.log(data.data);
var req = data.data;
$window.invoice = req.invoice;
$window.words = req.words;
$window.currency = req.currency;
$window.amount = req.amount;
console.log(invoice);
$("#doku-modal").modal('show');
});
}
Outside AngularJS:
console.log("form doku");
$(function() {
var data = new Object();
data.req_merchant_code = '3279';
data.req_chain_merchant = 'NA';
data.req_payment_channel = '15'; // ‘15’ = credit card
data.req_transaction_id = window.invoice;
data.req_currency = window.currency;
data.req_amount = window.amount;
data.req_words = window.words;
data.req_form_type = 'full';
getForm(data);
});
This worked for me. Hope this helps :)

Categories