I have page which shows number of routes. User click one and it sends an ajax request and save the selected route in database.
On the same page in different tab, I am running query which gets related information of the selected route. So i have Where clause in my query.
The problem is how I can feed in the ID of selected route to Where clause in my query in different tab
Here is code.
JQuery - When user click/select the route
$(document).ready(function () {
// capture the ID of clicked route
$(".collection-routeselection").click( function(){
route_id = $(this).attr("value");
jQuery.ajax({
url: '../data/collecting.php?action=route-selection?routeid='+route_id,
type: 'POST',
dataType: 'text',
data: {'routeid':route_id},
success: function(data, textStatus, jqXHR) {
$("#tab1").removeClass("active");
$("#tab2").addClass("active");
},
error: function(jqXHR, textStatus, errorThrown){
//Display error message to user
alert("An error occured when saving the data");
}
});
});
So i send the selected route using ajax to update database table.
$insert_web1 = $mysqli_scs->prepare("INSERT INTO collectiontracking_ctr (idrou_ctr,tab_ctr,created_ctr,modified_ctr) VALUES (?,'tab1',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)");
//bind paramaters
$rouid = "";
if (isset($_POST['routeid'])) {
$rouid = $_POST['routeid'];
}
$insert_web1->bind_param("i",$rouid);
$insert_web1->execute();
All working perfect so far..now I have another query on the same page (in different tab) which should have a where clause of selected route.
My question is how can i bind the selected route id to the where clause on second query.
$select_stmt = mysqli_prepare($mysqli_scs, "SELECT id_rou,idjtp_job
FROM routes_rou
WHere id_rou =?");
I want to populate ? with selected route ID.
Thanks
Assuming the value you are interested in is route_id, you should be able to store that in a variable that is accessible to tab #2 if it isn't already. Since it's on the same page this should be trivial especially since you're using jquery.
I apologize if I'm misunderstanding the question. If so please elaborate.
Related
I have an html page with a search field that can have a name typed in which returns a table of Names and IDs (from Steam, specifically). The leftmost column, the names, are hyperlinks that I want to, when clicked, take the user to said player's profile (profile.php) and I want to send the "name" and "steamid" to that profile.php when the name link is clicked, so essentially sending two JS variables from one page to the PHP backend of another page.
I'm new to ajax and it seems that that is the only way to use it, so after researching for a while this is what I've come to:
$(document).ready(function() {
$('#playerList td').click(function(e) {
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function() {
console.log('success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});
Everything up to the ajax definition works as I want, and I want to send the "name" and "steamid" vars to profile.php, but I don't think I'm understanding how ajax works. My understanding is that ajax can "post" information (usually a json object from what I've seen) to a url, but can also return information from a page? That's where I'm a bit confused and am wondering if I'm just using it wrong.
As a quick note: playerList is my table's id.
When I click the hyperlink, it takes me to profile.php, which is what I want, but php's $_POST[] array seems to be empty/null as I get the "undefined array key" error when trying to access both 'playersSteamID' and 'playersName'. var_dump() returns NULL as well, so I'm wondering if there's a problem with the way the data{} field is being sent in the ajax. I'm still very new to this so any help would be much appreciated.
Update: How I'm accessing the variables in profile.php
<?php
echo var_dump($_POST['playersName']);
echo var_dump($_POST['playersSteamID']);
if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}
?>
The rest of profile.php is taking those variables and running several sql queries and building a table which work given proper variables, but since the $_POST[] is empty I can't continue past the above point as the first two lines return null and the conditionals are never true since isset() is false.
The ajax is used to, post or get parameters/info from/to URL without redirecting/refreshing/navigating to a particular page.
Please note down without redirecting/refreshing/navigating
In your case you want to send 2 parameters to profile.php and you also want to navigate to it, yes..? but for that you are using Ajax, which is not a right choice.
Solutions:-
-> Use normal form submission kinda thing, and post the parameters to profile.php, in this case you will get redirect to profile.php and can expect proper functionality.
You can use a normal form with a submit button {pretty normal}, or use a custom function to submit form with some further work if need to be done {form validation}.
you function would look like this...
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
//Do some other stuffs
document.forms['someform'].submit();//submitting the form here
}
});
});
The rest in profile.php remains same.
-> If you really wanna use ajax do following.
Ajax are meant for dynamic web designing, pretty useful to grab data from server without refreshing the page.
You should change the way your response is in profile.php file.
for eg:-
<?php
if(isset($_POST['playersSteamID'])){
$name = $_POST['playersName'];
$id = $_POST['playersSteamID'];
//Do your stuff here db query whatever
//Here echo out the needed html/json response.
echo "<h3>".$name."</h3>";
echo "<h4>".$playersSteamID."</h4>";
}
?>
The response {from: echo} will be available in data of function(data) in ajax success, you can use this data in whatever you want and however you want.
for eg:-
success: function(data){
console.log(data);//for debugging
$('#mydiv').html(data);//appending the response.
}
-> Use php sessions and store steamID in sesssion variable, very useful if you have some login functionality in your website.
$_SESSION['steamID'] = //the steamID here;
This variable can be used anywhere in site use by calling session_start() in the page, you want to use sessions.
for eg:-
click here to view your profile
profile.php
<?php
session_start();
$id = $_SESSION['steamID'];
//echo var_dump($_POST['playersName']);
//echo var_dump($_POST['playersSteamID']);
/*if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}*/
echo $id;
//Do your work here......
?>
For any queries comment down.
A hyperlink may be causing the page navigation, which you dont want.
Page navigation will make a get request but your endpoint is expecting a post request.
You can stop the navigation by setting the href to # or by removing the <a> altogether.
You could also try calling the preventDefault on the event object.
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function(data) {
console.log('success', data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});
I am having an issue with assigning large set of data to jQuery select2 dropdown. I have an Ajax controller call which returns customer data (id & name) and assign it to a select2 dropdown box inside success call of Ajax. The problem is I have around 77k customer records and because of that select2 is not handling it well and browser hangs after few seconds.
As a solution I came across pagination in select2 and tried quite a few examples but none of them are working in my scenario. I am loading all customer data at once because I don't want to make frequent queries to search for customer record.
I have a javascript function which gets the data from controller (Ruby) and assign it to select dropdown using select2.
function updateCustomerList(teamId, customerSelectInput) {
if(teamId !== undefined) {
$.ajax({
dataType: "json",
url: "/team/customers",
data: {team_id: teamId},
success: function(data) {
$(customerSelectInput).select2({
createSearchChoice: createSearchChoiceFunction,
placeholder: "Search for customer"],
data: data
});
},
error: function(jqXHR, textStatus, errorThrown) {
displayError(jqXHR.responseText)
}
});
}
var createSearchChoiceFunction = function(term, data) {
if ( $(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
}
}
FYI Team controller method "customers" is just making a query to customer collection and gets all customer by team id and return the result as json object.
Any kind of help/guidance would be appreciated!
I have around 77k customer records and because of that select2 is not handling it well and browser hangs after few seconds.
Well, that happened because all data is loading in memory, you will see that all your RAM go off. In the DOM, many <options> are created, and chrome it will be happy eating all your memory.
I think you can get better results with Algolia API and Autocomplete.js which is
a JavaScript library that adds a fast and fully-featured auto-completion menu to your search box displaying results "as you type".
https://github.com/algolia/autocomplete.js
I have the following code in shopping-cart.tpl:
$(document).ready(function(){
$.ajax({
url: document.location.origin+"/univers/themes/leostyl/shopping-cart.php",
type: 'get',
success: function(data){
var array = $.parseJSON(data);
ch='<select class="form-control" id="customer-id" onchange="myFunction()">';
for (var i=0;i<array['results'].length;i++) {
if(array['results'][i].id_default_group== 3)
ch=ch+'<option id='+array['results'][i].id_customer+'> '+array['results'][i].firstname+' '+array['results'][i].lastname+'</option>';
}
ch=ch+'</select>';
$( ".customer" ).append(ch);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
how can i modify the value of $order->id_customer in PaymentModule.php by creating a variable in shopping-cart.tpl?
$order->id_customer = (int)$this->context->cart->id_customer;
you can't change it from a simple assignement in a template. The customer id is retrieved from the context (Cookie / Session) in the validateOrder() function...
Assign an order to a different customer is quite dangerous, but if you really need this, I see 2 workarounds :
Override the PaymentModule::validateOrder() function to set the customer id you want instead of using the one of the context, assuming you stored it somewhere else before in your process: Cookie, db table
Use a hook (actionObjectOrderAddBefore, actionValidateOrder, ...) to set or modify all the order related data in database after validation (be careful to subprocesses like email confirmation that could be sent to the previous customer according to the hook you use), and also assuming you stored the good customer id somewhere before
Good luck
I have a search feature I built for an administrative account in Django on the front-end that queries matched users to the admin with an option to remove them from the database. Currently, they click the button, and they are redirected to the view that handles the backend logic for removing the associated object by the primary key from the database. I am wanting to have the user remove the object on button click and then update the div that the users display in after object has been removed without the page refreshing. How can I go about this?
Here a super generic example.
You can do something like:
in your views.py:
def delete_element(request, element_id):
element = get_object_or_404(ElementClass, id=element_id)
element.delete()
return HttpResponse("success")
in your urls.py:
url(r'^element_delete/(?P<element_id>\d+)/$', 'app.views.delete_element', name="name_element_delete"),
in your template:
<script>
$(".delete-button").click(function(){
var element = this;
var url = $(this).data('url');
$.ajax({
type: 'GET',
url: url,
success: function(){
// do what you want with 'element' var
},
error: function(){
alert("Error on delete, please try again");
},
});
});
</script>
I'm retrieving some data into a JSON array, then display it into an HTML table which contains some data enclosed within hyper links. i.e. a couple of the columns' data are clickable, once clicked it displays another JSP page (say page #2) with some more data which was kept on the JSON array itself.
Now this page 2 has a 'Back' button functionality - the expected behavior is when user clicks the 'Back' button it should go back to page 1 where the HTML table data was displayed and user should be able to see the data which they first fetched too. i.e. there should be some way to remember the data fetched from my initial AJAX request and retrieve the same data which user fetched in page 1 when they go back to that page from the child page#2.
Th AJAX call is triggered when user enters an account# and the type of account - I fetch data accordingly and get the result in the 'response' object and neatly display it on html table, but after user moves from that page and again hits the back button I see the page#1 without the table. Now again I cannot ask the user to re-enter the details to see the data that they retrieved earlier. It's pretty annoying.
Please give me a solution to this problem. Thanks All.
Appreciate for taking time to read this.
Here's a part of the code:
$(document).ready(function () {
var flag = "1";
$('#accountType').bind('change', function (event) {
var accountType = $('#accountTypeSelect').val();
var account = $('#accountText').val();
jQuery.ajax({
type: 'POST',
url: '${pageContext.request.contextPath}' + "/Page1.spr", //request page
cache: false,
dataType: "json",
data: {
"accountType": accountType,
"account": account,
"flag": flag
}, //data sent to request page
success: function (response) {
// code to display the data into the html table
},
error: (function (message) {
console.log("error message : " + message);
}),
statusCode: {
404: function () {
alert("page not found");
}
}
});
});
You can save the data in HTML5 sessionStorage or localStorage using the setItem method as follows:
success: function(response) {
sessionStorage.setItem("result", response)
// code to display the data into the html table
}
And access it later using the getItem() When you come back to the page like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// code to be executed when old dats is found
}
else{
}
Ideally you code in first pages load will be something like
var prevResponse = JSON.parse(sessionStorage.getItem("result"));
if(prevResponse)
{
// data exists : code to be executed when old dats is found
}
else{
jQuery.ajax({}) // send the AJAX request to fetch data
}
You can read more about session and local Storage here
Browser support for web storage API.
Update
If you don't have HTML5 support, you could use jQuery cookie plugin (There are plenty of others as well) for storing data at client side.
You can store data into a cookie as follows:
$.cookie("result", response);
Then to get it from the cookie like:
$.cookie("result");
You maybe can use cookie via jquery. But user have to enable the browser's cookie. It usually enabled by default setting.
To add:
$.cookie("key1", data1);
$.cookie("key2", data2);
To read:
$.cookie("key1");
To delete:
$.removeCookie("key1");
So, you can try to read cookie to load table data, if no data, call ajax:)
Another way is to save it in a hidden input:
success: function(response){
$("#hiddenInput").val(JSON.stringify(response));
}