Create and Fetch Dynamic url using Jquery - javascript

I have a page single-colur.html and it can take a variety of set query strings as can be seen below:
single-colur.html?id=1
single-colur.html?id=2
single-colur.html?id=3
single-colur.html?id=4
The id above is referenced to a colour table which has the following columns:
id
name
content
When people come to single-colur.html and they request a specific ID, I'd like to get the respective ID from the URL and send an AJAX request to a PHP page which will get the corresponding row from my table based on the ID that is provided, this is currently implemented.
My question is: Is it possible that if someone goes to single-colur.html?id=1 then all the data is fetched and displayed in a new URL based on the name field which is referenced by the ID e.g. single-colur.html?id=1 points you to a dynamically created file called red.html and it shows the data from the colour table for this ID?
My restriction is that I must create the new file dynamically and it cannot be done statically.
EDIT
Currently i have two pages .
1)archive-colour.html
2)single-colour.html
in archive-colour.html
<div>
Red
Green
Blue
</div>
in single-colur.html?id=anynumber
<div class="result">
</div>
In single-colur.html i am doing ajax and fetch details from database using requested id and display in class result .
This is the current process . But what i need is
in single-colur.html?id=anynumber
i have to replace the current page url with colour-name.html
and show the details . [BUT the thing is there is no colour-name.html page in server . ie there is no red.html, green.html,blue.html in server . It have to be virtually created by jquery . ]

Use Ajax :
$.ajax({
url: "my-colours.html",
type: "get", //send it through get method
data: {
id: //<Your id here >
},
success: function(response) {
window.location.href = '/' + response.color + '.html' ;
},
error: function() {
//Do Something to handle error
}
});
I suppose this is what you're looking for. Here a dynamic link will be created by ajax and you can give a dynamic value to Id each time.

So you use
window.location = window.location.hostname + "here put the returned from ajax" + ".html";
Explain
window.location.hostname
returns the website url

This example is as complete as it can be in this environment.
Load on click via ajax
Set content
Set virtual url
$( 'a.virtual' ).click( function( e ) {
var link = $(this);
console.log( "Loading: " + link.attr('href') );
$.ajax({
url: link.attr('href'),
type: "get",
success: function(response) {
// parse json or howerver data get transferred
var result = parseJSON(response);
var content = result['content'];
var virtual_url = result['url'];
// set content
$('#content').html( content );
// set virtual url
window.history.pushState([], 'Title', virtual_url);
}
});
// do not follow the link!
e.preventDefault();
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a class="virtual" href="my-colours.html?id=1">Link A</a></li>
<li><a class="virtual" href="my-colours.html?id=2">Link B</a></li>
<li><a class="virtual" href="my-colours.html?id=3">Link C</a></li>
<li><a class="virtual" href="my-colours.html?id=4">Link D</a></li>
<ul>
<br/>
Content delivered via ajax:<br/>
<div id='content'>
</div>

Related

display ajax result on new page

I would like to display the results of an ajax request on a new page rather than the page the ajax call was made from. Essentially I have a membership directory page. When the user clicks on the member ID cell on that page, an ajax call sends the ID to the server and completes an HTML table to display that member profile. If I add a <div> element below the membership directory page, I can make the profile information table display below the membership directory table. But I want the profile table to display on different page.
JavaScript:
$jq.ajax({
url : ajax_mmmp.ajax_url,
type : 'post',
data : {
action: 'mmmp_profile_member_id_callback',
mem_id : member_id
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
// Return response to client side
alert("Submit Success");
$jq('#display_profile').html( data );
return false;
},
error: function(errorThrown){
console.log(errorThrown);
}
}); // End of AJAX function
But when I create a new page with the same <div> element and try to open that page prior to the ajax call, the result does not display.
var mem_profile = "http://localhost:81/wordpress/view-member-profile"
window.open (mem_profile,'_self',false)
$jq.ajax({
url : ajax_mmmp.ajax_url,
type : 'post',
data : {
action: 'mmmp_profile_member_id_callback',
mem_id : member_id
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
// Return response to client side
alert("Submit Success");
$jq('#display_profile').html( data );
return false;
},
error: function(errorThrown){
console.log(errorThrown);
}
}); // End of AJAX function
Putting aside the question of whether it is a good idea to take that approach, the answer to your question is yes. You can open a new window and write the resulting HTML to it:
// open a new window with no url and a title. check the docs for other args to open()
let win = window.open('','My New Window');
// write some HTML to that window
win.document.write('<table><tr><th>test</th></tr></table>');
After some further research, I'm almost there. I do not presently have a "form" to submit. The user simply clicks on a table cell which contains a member ID number. I want to 'submit' that value as input on another page which displays the membership profile. I have been successful in temporarily adding a HTML form that works as desired if I type the member ID in an input field. So I decided what was needed was to create a hidden form in JS that used the ID value that was clicked on. It appears that I can not insert revised code into a comment, so I opted to 'Answer' my original question with updated code.
Working HTML Form included on Membership Directory Page:
$site_url = site_url();
$location = $site_url . "/view-member-profile";
?>
<form action="<?php echo $location;?>" method="post">
<input type="text" class="input_member_id" id="input_member_id" name="Member_ID">
<input type="submit" id="submit_member_id" name="submit_member_id" value="Submit">
</form>
My attempt to create a similar hidden form in JS:
var $jq = jQuery.noConflict();
$jq(document).ready(function(){
// Add listener for Member ID click in member directory
$jq("#mem_dir").delegate(".member_id", "click", function() {
var mem_id = $jq(this).text();
var mem_id = mem_id.trim();
alert ("ID is: " + mem_id);
var site_url = document.location.origin + '/wordpress';
var form_location = site_url + '/view-member-profile';
alert ("Submit to location is: " + form_location);
var form = $jq('<form method="post" class="js:hidden">').attr('action', form_location);
//var input = $jq('<input type="hidden"'>).attr('value', mem_id );
//form.append(input);
//$jq('body').append(form);
form.submit();
}); // End of Click Member ID Listener
}); // End of Main Document Ready Function
The problem I am having with the JS file is with inserting the mem_id value into the input form. The JS file correctly opens the new View Member Profile page. (Note the 3 // lines just prior to the form.submit). When uncommented, the Profile page opens, but table values are empty (i.e. mem_id value was not passed to the page).
Thanks for any advice. If I was supposed to list this as a new question, please let me know.

Laravel 5 attach with Ajax?

I have this laravel code in my controller detach function.
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
return view('products.tagsdelete', [
'products' => $product,
]);
This works fine, it deletes the tag realation from my pivot table. The only thing that bugs me it that I don't want to reload the page everytime I press the delete button on my view.
( Of course I could make a selection of all tags the user want to delete, but I want to to this live with Ajax )
My problem is, I couldn't find anything that helps me with detachment from laravel + Ajax. I'm quite okay with Javascript and Jquery but Ajax is still a new thing for me..
So can anybody help me there? I'm really stuck.
Thanks for taking your time :)
#Wiriya Rungruang
current controller code:
public function detach()
{
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
}
my button:
<button type="submit" class="delete-tag-btn" data-product_id="{{ $product->id }}" data-tag_id="{{ $tag->id }}"><i class="glyphicon glyphicon-trash"></i></button>
at the bottom of the code the JS:
<script>
$(".delete-tag-btn").on('click', function(){
var url = "{{ route('detach') }}"; // Url to deleteTag function
url += "product_id=" + $(this).data('product_id');
url += "&tag_id=" + $(this).data('tag_id');
// Now url should look like this 'http://localhost/deletetag?product_id=2&tag_id=5
// Send get request with url to your server
$.get(url, function(response){
alert("success");
});
});
</script>
First : You should create function detach tag from product in your controller and return status success or failure(or nothing)
In your controller
function detachTag(){
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
return "Some state for checking it a success or not";
}
Second : Create javascript function for checking when you click on delete button send request with parameter to function that we created in the first step and rerender or remove that tag from your HTML page
**Parameter is mean product_id and tag_id that your want to detach it
In your js
$(".delete-tag-btn").on('click', function(){
var url = "localhost/deletetag?"; // Url to deleteTag function
url += "product_id=" + $(this).data('product_id');
url += "&tag_id=" + $(this).data('tag_id');
// Now url should look like this 'http://localhost/deletetag?product_id=2&tag_id=5
// Send get request with url to your server
$.get(url, function(response){
// Do what you want
});
});
So when you click on .delete-tag-btn It will send request for detach it
While you can right a simple ajax call, send data and return html and replace it with the old html
lets begin :)
first step is to write ajax, and send it when form is submit or any button is clicked (as per your code)
this one is sample ajax, just fill in your data in it.
var BASEURL = window.location.origin + "/your_domain_name/";
$.ajax({
url: BASEURL + "your_route",
type: "POST/GET", //any_one
data: {
// Your data comes here (object)
},
beforeSend: function () {
},
success: function (response) {
console.log(response); // your html in return
},
complete: function (response) {
}
});
now a call will be send with your data to controller respective to specified route you mentioned, processing will be normal.
It will return only html. You can do whatever you want with this html.
One important problem you might face if considering these instructions is, right now the view you are returning is probably of whole page (because the page is been refresh every time), but if you are thinking to replace it with new html, your will only have to return that part of the page may be a single row or something like that. So break your view in many sub views. Php #include(//path) (blade) might come handy. Thats how I use to work. :)

Get active tab ID from Bootstrap and pass it to PHP

I have two pages with 3 tabs each. One page for viewing and another for editing.
When I click the tab 2 from view page and press Edit button, I want to be redirected to tab 2 in Edit page. Similarly, for other tabs as well. Tab 1 from view takes me to tab 1 in Edit, and tab 3 from view takes me to tab 3 in Edit.
So what I want to do is, get the active tab from the 3 tabs, fetch the href value, store the href value such that I can use it as php variable (or any other way) in the same page and pass it on to the button link to redirect correctly.
I am using Bootstrap and Codeigniter.
To fetch the href from the active tab; I found this:
$('.nav-tabs .active > a').attr('href')
This will give me the concerned href name like tab1, tab2, tab3:
<li class="active">Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
I have a line in my PHP code like:
Edit
How do I achieve this?
You'll have to change your link a little bit, like this:
<a id="EditLink" href="<?= site_url('backend/edit/'. $uid) ?>">Edit</a>
And add this when you click on the tab, where :
var tabValue = $(".nav-tabs .active > a").attr("href");
var url = $("#EditLink").attr("href");
$("#EditLink").attr("href", AppendToUrl(url, "tab", tabValue));
With the function AppendToUrl:
function AppendToUrl(url, key, value) {
var regex = /\?/i;
if (regex.test(url)) {
return url + "&" + key + "=" + value;
} else {
return url + "?" + key + "=" + value;
}
}
You cannot. Active tab is client side, PHP is server side. You can eventually use javascript to send AJAX query:
$.ajax({
method: "POST",
url: "some.php",
data: { active_tab_id: jquery_function_returning_id() }
})
.done(function( url ) {
$("#id_of_element_u_want_inject_href").attr("href", url)
});
Some.php:
<?php
$data = $_POST['data'];
echo site_url('backend/edit/'. $uid . $data['active_tab_id']);
session_start();
$_SESSION['variable']=$data['active_tab_id'];
?>
You should be able to access data in session.
Best would be full javascript solution :)
Handle this in JS by passing the uid down instead of the selected tab up.
Something like this.
var uid = <?PHP echo $uid; ?>;
function getHref() {
var selTab = $('.nav-tabs .active > a').attr('href');
var retHref = 'backend/edit/' + uid + selTab;
return retHref
}
May need a PHP script to shiv this into site_url() whatever that does, but thats easy enough.
You should achieve this wit javasvript...
When click on a tab get its id and then set required href for any element ...

Use one ajax call for different page and div?

I use this code to make ajax call to change the content of div in main page without reloading the page :
function ajaxcall()
{
$.ajax({
type: "POST",
url: "/create.php",
success: function( returnedData ) {
$( '#container' ).html( returnedData );
}
});
}
and I call it like that :
<p><a onclick="ajaxcall()" >Create</a></p>
The issue is very complicated because I have to call 4 pages in the same div :
create.hmtl ; update.html; delete.html ; read.html
Also I have 2 different forms in the same page that required the same thing, I mean I should do the same thing for the second form with another div "container-1",then I have 2 div for exmaple in create.html :
create.html :
<div id="container">
....
</div>
<div id="container-1">
....
</div>
So I call create.html everytime but different div for different form, the question is to use a minimum clean code to do all what I explained above?
Edit
To explain more my problem, I have 4 options (create/update/delete/read) with 4 pages, and in every page they are 2 div and 2 contents for 2 forms, I should change div content of every option(CRUD) for every form in webpage!
form -> ajax call content -> create.html -> div:container
form-1 -> ajax call content -> create.html -> div:container-1
form-1 -> ajax call content -> update.html -> div:container-1
You can add those as parameters to the function and make it like below
function ajaxcall(url, data, targetDivId)
{
$.ajax({
type: "POST",
url: url,
data : data,
success: function( returnedData ) {
$("#"+targetDivId).html( returnedData );
}
});
}
For your scenario:
I assume that even the AJAX url may change as currently it's pointing to create.php. In case it's same then you can avoid tht parameter.
<p><a onclick="ajaxcall('/create.php', {} , 'container-1')" >Create</a></p>
<p><a onclick="ajaxcall('/update.php', object2 , 'container-2')" >update</a></p>
<p><a onclick="ajaxcall('/delete.php', object3, 'container-3')" >Delete</a></p>
Following mohamedrias' answer, if you also needed to process each alternate path in the CRUD use case differently, you can use global event handlers.
Don't handle when making the request:
$.ajax({
type: "POST",
url: url,
data : data,
success: function( returnedData ) {
}
});
Do handle seperatley for each alternate path in CRUD
$(document).ajaxSuccess(function(event, xhr, settings) {
var query = settings.data;
var url = settings.url;
if (url.match(/create.php/) && query.match(/container1/)){
$("#container1").find(".form-1").html( xhr.responseText );
}
});
You should also notice that the selector in my example implies that "form-1" is a Class and not an ID.
IDs must be unique but Classes can occur many times.
Following this rule, if you wanted to reuse the same form for each alternate path you can do so by addressing discrete elements in the form using unique class names for each element. The container Div must have a unique ID (as you have already done). But you must give that element context by chaining the selectors to first select the div using ID and then select the element using class.
If I understood it correcyly you want to provide an argument to the ajax calling function to apply the return content from "/create.php" to a different div.
function ajaxcall(id, path)
{
$.ajax({
type: "POST",
url: path,
success: function( returnedData ) {
$("#"+id).html( returnedData );
}
});
}
And in html you can set the id like
<p><a onclick="ajaxcall(this.id, "/create.php")" >Create</a></p>
var xhr = new XMLHttpRequest();
xhr.onload = function(){
var document = xhr.response;
var container = document.getElementById('container');
var container-1 = document.getElementById('container-1');
console.log(container, container-1);
// or
// var containers = document.querySelectorAll("#container, #container-1" );
//console.log(containers);
}
xhr.open('POST','/create.php');
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
xhr.responseType = 'document';
xhr.send();

Ajax POST is not posting onclick to current page

Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>

Categories

Resources