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.
Related
I'm having some problems changing the view page in the code. Note: i'm using ajax.
This is part of the controller function called "insert_inventario" after the information is saved in array_db it compares with the inventario_model and the result "true" or "false" is saved in obj_inv.
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
if($obj_inv){
$edit_view = $this->load->view(base_url()."inventario/edit",$array_db,TRUE);
$response = array('mensaje' => $edit_view,
);
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;
}
This is part of the view page called create, this is the submit button that executes the Javascript code that execute the controller function
<input type="submit" class="btn btn-danger" id="btn_enviar" value="Guardar">
The javascript Function
$("#btn_enviar").click(function(){
var r = confirm("Make sure the information you fill is correct");
if (r == true){
var url = base_url + "/inventario/insert_inventario";
$.ajax({
type: "POST",
url: url,
data: $("#form_inventario").serialize(),
success: function(data)
{
$("#contenido").html(data.mensaje);
}
});
}
return false;
});
The problem is, when i fill the form and press submit, the message box appears and when I click accept, it does nothing. I'm burning my brain so much to understand what I'm doing wrong, please help me.
The main problem is a error called jquery-2.1.4.min.js:4 POST http://161.196.112.19:8080/Inventario_Remedy/inventario/insert_inventario 500 (Internal Server Error) it happens when the code try to insert the array
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
So, in order to fix this, you have to check your database values and keep trying.
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. :)
I've tried several ways to redirect the URL back to the page where the user came from after submitting a form or just refresh the form page to allow the user to make a new entry if the user came directly to it. So far, I've been unsuccessful. The following method is the closest I've got but I'm not sure what's going wrong -
The user clicks this link which takes them to the page where the form is -
<a target="_blank" class="sampleredirect" href="<?php echo base_url();?>sample/controller/add">Add User</a>
Upon clicking, the following jQuery script links the click to a function -
<script>
$('#sampleredirect').click(function(){
$.ajax({
type: "POST",
url: "sample/controller/redfunc",
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
</script>
The function gets the URL where the click was initiated -
public function redfunc(){
$referred_from = $this->session->set_userdata('referred_from',current_url());
return $referred_from;
}
Inside sample/controller/add where the form logic is located, after the submission, I'm calling the function to redirect the user back to the previous URL -
public function adduser(){
//sample code
$this->redfunc();
redirect($referred_from, 'refresh');
}
This isn't working and I keep getting redirected to the default page that shows up if a URL can't be found. When I do vardump($referred_from) after calling the function $this->redfunc();, I'm getting NULL.
I'm kinda lost here and would love some help with this. Thanks!
$referred_from will return nothing. It is just setting a session. It will not return session value. Try below code
<script>
$('#sampleredirect').click(function(){
$.ajax({
type: "POST",
url: "sample/controller/redfunc",
data: {current_url:<?=current_url()?>}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
public function redfunc(){
$this->session->set_userdata('referred_from',$this->input->post('current_url');
}
public function adduser(){
//sample code
$referred_from = $this->session->referred_from;
redirect($referred_from, 'refresh');
}
You need to assign the $referred_from in your adduser function.
$this->redfunc();
You need assign a variable there. Because you want to receive result from redfunc() right?
so, Try it.
public function adduser(){
//sample code
$referred_from = $this->redfunc();
redirect($referred_from, 'refresh');
}
or you can do this
public function adduser(){
//sample code
redirect($this->redfunc(), 'refresh');
}
sorry. bad english
$referred_from = $this->session->userdata('referred_from');
use session->userdata to get current_url which you have stored in the session
set url in session
$this->session->set_userdata('referred_from',current_url());
Retrieve from session
$this->session->userdata('referred_from');
I am trying to get some data from the database. I create a function that is located in functions.php file that return a value. On another page, I create a variable and just get that value. I was trying to use the onkey to check the database but then I realize that i need to know the amount of tickets even if they don't type anything.
Here is the function:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$amount_of_tickets = $row['number_of_tickets'];
}
return $amount_of_tickets;
}
And, I am trying to check the database (without refreshing the page) and get the value on this page:
application.php
$amount_of_tickets = is_ticket_able($conn);
Then, I just check that $amount_of_tickets is not 0 or 1. Because if is one then some stuff have to change.
I am doing this (inside application.php):
if($amount_of_tickets !=0){
//show the form and let them apply for tickets.
//also
if($amount_of_tickets == 1){
//just let them apply for one ticket.
}
}
EDIT: I saw that AJAX would be the right one to use, but I am so confuse using it.
UPDATE:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
return $ticket;
}
application.php
$amount_of_tickets = is_ticket_able($conn);
<script type="text/javascript">
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
alert(global_isTicketAble);
if( global_isTicketAble == 0 ){
window.location.replace("http://www.google.com");
}
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
});
}
</script>
So, now the problem is that when I alert(global_isTicketAble); it doesn't alert the value from the database but it does alert everything that is inside application.php...Help plzzz
Server side
Assuming you need to check $amount_of_tickets periodically and this can be computed into application.php, inside that file you'll have
<?php
// $conn is defined and set somewhere
$amount_of_tickets = is_ticket_able($conn);
echo $amount_of_tickets;
exit(0);
?>
This way when the script is invoked with a simple GET request the value is returned in the response as simple text.
Client Side
ajax is the way to go if you want to update information on page without reloading it.
Below is just a simple example (using jQuery) that may be extended to fit your needs.
The code below is a JavaScript snippet. A global is used to store the value (globals should be avoided but it's just for the purpose of the example)
Then a function is invoked and the updated value is fetched from function.php script.
The function -prior termination- schedules itself (with setTimeout) to be re-invoked after a given amount of milliseconds (to repeat the fetch value process).
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
// eventually do something here
// with the value just fetched
// (ex. update the data displayed)
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
}
}
Note that $.ajax() sends the request but does not wait for the response (as async is set to true). When the request is received the function specified as success is executed.
Complete jQuery ajax function documentation can be found here
http://api.jquery.com/jquery.ajax/
I assume that you have a page (application.php) that displays a table somewhere.
And that you wish to fill that table with the data found in you database.
I'm not sure about WHEN you want these data to be refreshed.
On button click or periodically (like ervery 5 seconds)... But it doesn't matter for what I explain below.
In application.php:
Assemble all your page as you already know how.
But inside it, somewere, just insert an empty div where your table should show:
<div id="dynamicContent"></div>
Also add this script at the bottom of the page:
<script>
function getData(){
PostData="";
$.ajax({
type: "POST",
url: "function.php",
data: PostData,
cache: true,
success: function(html){
$(Destination).html(html);
}
});
}
getData(); // Trigger it on first page load !
</script>
There is 2 variables here... I named it "PostData" and "Destination".
About PostData:
You can pass data collected on the client side to your PHP function if needed.
Suppose you'd need to pass your user's first and last name, You'd define PostData like this:
Fname=$("#Fname").val(); // user inputs
Lname=$("#Lname").val();
PostData="Fname="+Fname+"&Lname="+Lname;
In your function.php, you will retreive it like this (like any normal POST data):
$Fname=$_POST['Fname'];
$Lname=$_POST['Lname'];
If you do not need to pass data from your client side script to you server side PHP... Just define it empty.
PostData="";
Then, about Destination:
This is the place for the empty "dynamic div" id ( I named it "dynamicContent" above).
Don't forget about the hashtag (#) for an id or the dot for a class.
This is a jQuery selector.
So here, PostData would be defined like this:
Destination="#dynamicContent";
The result of the ajax request will land into that "dynamic div".
This WILL be the result of what's defined in function.php..
So, if you follow me, you have to build your table in function.php...
I mean the part where you do your database query and your while fetch.
echo "<table>";
echo "<tr><th>column title 1</th><th>column title 2</th></tr>"
while ($row = sqlsrv_fetch_array($stmt)){
echo "<tr><td>" . $row['data1'] . "</td><td>" . $row['data2'] . "</td></tr>";
}
echo "</table>";
So if you have no data, the table will be empty.
You'll only get the table and table headers... But no row.
There is then no need for a function that checks if there is data or not.
Finally... About the trigger to refresh:
In application.php, you may place a button that fires getData()... Or you may define a setInterval.
It's up to you.
This is how I use ajax to refresh part of a page without reloading it completly.
Since ajax is new to you, I hope this answer will help.
;)
------------------------
EDIT based on Ariel's comment (2016-05-01)
Okay, I understand! Try this:
In application.php:
<div id="dynamicDiv"></div>
<script type="text/javascript">
// timer to trigger the function every seconds
var checkInterval = setInterval(function(){
checkTicket();
},1000);
function checkTicket(){
$.ajax({
type: "POST",
url: "function.php",
data: "",
cache: true,
success: function(html){
$("#dynamicDiv").html(html);
}
});
}
function noMoreTikets(){
clearInterval(checkInterval);
window.location.replace("http://www.google.com");
}
</script>
In function.php:
// Remove the "function is_ticket_able($conn){" function wrapper.
// Define $conn... Or include the file where it is defined.
// I assume that your query lookup works.
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
// Add this instead of a return.
if($ticket>0){
echo "There is still some tickets!"; // Text that will show in "dynamicDiv"
}else{
?>
<script>
$(document).ready(function(){
noMoreTikets();
});
</script>
<?php
}
Remember that your PHP scripts are executed server-side.
That is why your "return $ticket;" wasn't doing anything.
In this ajax way to call function.php, its script is executed alone, like a single page, without any relation with application.php, which was executed long ago.
It produces text (or javascript) to be served to the client.
If you want to pass a PHP variable to the client-side javascript, you have to echo it as javascript.
So here, if the PHP variable $ticket is more than zero, some text saying that there is still tickets available will show in "dynamicDiv" and the application page will not be refreshed. I suppose it shows a button or something that allows students to get a ticket.
Else, it will be the javascript trigger to "noMoreTikets()" that will land in the "dynamicDiv".
When the user press button the data will be save into database.After success I want to retrieve data from database and place it in the proper td ( in the same row of the clicked td) i am success to retrieve data but not assign the retrieved data to the different td
ajax
$(document).ready(function(){
$('.edit2').on('click', function(){
arr = $(this).attr('class').split( " " );
var clientid=document.getElementById("client").value;
$.ajax({ type: "POST",
url:"clientnetworkpricelist/updateprice.php",
data: "value="+$('.ajax input').val()+"&rowid="+arr[2]+"&field="+arr[1]+"&clientid="+clientid,
success: function(data){
$('#CPH_GridView1_clientprice'+arr[2]).empty();
$('#CPH_GridView1_clientprice'+arr[2]).append(data);
$('.ajax').html($(this).val());
$('.ajax').removeClass('ajax');
}});
}
);
});
HTML
<td id="CPH_GridView1_clientprice'.$rows['net_id'].'" class="edit clientprice '.$rows["net_id"].'">'.$rows["clientprice"].'</td>
<td id="CPH_GridView1_Status'.$rows['net_id'].'" class="edit2 status '.$rows["net_id"].' "><img src="image/'.$rows["status"].'f.png" /></td>
in my updateprice.php i connect to database and retrieve value from the database any just print the retrieve value like this
print $newclientprice;
print $status;
my result
both the value are showing now in the same td but i want it in separate td 0/01 in clientprice and increase in status
Client Price status
0.01increase |
|
|
any one help me thanks.
updateprice.php
let's change this:
<?php
print $newclientprice;
print $status;
I'm not sure what you're trying to do. Because you are using jQuery, let's make use of JSON for our benefit. Important: the following code depends on no output being sent before it executes, and it will finish the php execution immediately
<?php
// set type so client can understand what was sent
header('Content-Type: application/json');
// transform our 2 values into a JSON array,
// this will be transparently transformed into an array for your ajax handler
echo json_encode(array($newclientprice, $status));
// end the script, this is what the client ajax request wanted
exit;
javascript.js
I took the liberty to rewrite your code so that it would seem clearer, and at least with a few comments too
$(document).ready(function(){
var onClick, ajaxSuccessHandleMaker;
onClick = function() {
var
url = 'clientnetworkpricelist/updateprice.php',
clientid = $('#client')[0].value,
classesArray = $(this).attr('class').split(" "),
// send data as object, jQuery will transparently transform for the server
data = {
value : $('.ajax input').val,
rowid : classesArray[2],
field : classesArray[1],
clientid : clientid
};
// send POST request and expect JSON
$.post(url,data,ajaxSuccessHandleMaker(classesArray),'json');
};
// success returns the ajax handler with a closure on classesArray
ajaxSuccessHandleMaker = function (arr) {
// the handler EXPECTS an array, which is why we have to protect output in updateprice.php
return function (arrayOf2vals) {
$('#CPH_GridView1_clientprice'+arr[2]).html(arrayOf2vals[0]);
$('#CPH_GridView1_Status'+arr[2]).html(arrayOf2vals[1]);
// I am not sure what you want with the following 2 lines of code
$('.ajax').html($(this).val());// what is this?
$('.ajax').removeClass('ajax');// what is this?
};
};
// set the onClick handler
$('.edit2').click(onClick);
});
Finally
any questions are welcome
please test if it works, if it doesn't then comment back and I'll try to help out