Request new page with ajax and open it in new page - php

I'm having problem trying to request new page(s) from CodeIgniter using JQuery Ajax and open them in a new blank page
The following is the example scenario of current code which is working,
1.) User select the customer's receipt by checkbox
<input type='checkbox' class='customer_id' value='<?php echo $entry->customer_id;?>'>
2.) Javascript read the customer(s) id then send those data to CodeIgniter. Once return data is received, fire callback function to display them target div
var data;
var counter = 1;
$(.customer_id:checked).each(function(){
data['customer_' + counter] = $(this).val();
})
$.post('finance/getReceipt', data, function(){
$('#some_target_div').html(data);
}
3.) CodeIgniter retrieve customer data from db and generate page
function getReceipt(){
$counter = 1;
while ($this->input->post('customer_' + $counter)){
$where['customer_id'] = $this->input->post('customer_' + $counter);
$data += $this->getCustomerReciept($where);
}
$this->load->page('finance/receipt', $data);
}
But now I need to convert this code to make it open a new blank page with a print button
The purpose of this is because I want to generate a formatted receipt and display in a new blank page with a print button. I know that there are several plugin that I can print a div but this is the request from my client. So, that's isn't a solution for me.
Any suggestion or comment will be great. Thank in advance.

I think the easiest way would be to create an auxiliar form to post your data to a new page instead of using $.post So, this would be the code:
var data;
var counter = 1;
$(.customer_id:checked).each(function(){
data['customer_' + counter] = $(this).val();
});
$('<form action="finance/getReceipt" method="POST" target="_blank" style="display:none">' +
'<input type="hidden" name="data1" value="value-data1" />'
).appendTo("body").submit().remove();
Just change your data1 param to the one you want, or add more if you want.
And that's it. The magic is in using a _blank target for the form.
Hope this helps. Cheers
PS: The other way would be creating a new window with window.open and assign its content with javascript.

Related

Ajax visit link without actually visiting link

I've got a basic like button concept on my site that visits url.tld?action=love and adds +1 to the link's database column.
It's a hassle redirecting to another page all the time though. Is it possible to click the button, and send a request to the URL without actually redirecting to a new URL? Also maybe refresh the button afterwards only so that the count updates?
For a general idea of what my download button is this is in the header:
<?php require_once('phpcount.php'); ?>
<p class="hidden"><?php
$time = time();
for($i = 0; $i < 1; $i++)
{
PHPCount::AddHit("$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]", "127.0.0.1");
}
echo (time() - $time);
/*echo "PAGE1 NON: " . PHPCount::GetHits("page1") . "\nPAGE1 UNIQUE: " . PHPCount::GetHits("page1", true);
echo "\n\n" . PHPCount::GetHits("page2");
$ntot = PHPCount::GetTotalHits();
$utot = PHPcount::GetTotalHits(true);
echo "###$ntot!!!!$utot";*/?></p>
And this is an example of my "love" button.
Love <span class="count">'. PHPCount::GetHits("$package_get?action=love", true).'</span>
The reason I used this method is because people create pages, and I wanted the like button to work out of the box. When their page is first visited it adds their url to the database, and begins tallying unique hits.
This is basically adding a new link column called downloadlink?action=love, and tallying unique clicks.
use the following code. assgin id="btn_my_love" to that button and add this code to you page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
//assign url to a variable
var my_url = <?php echo "https://alt.epicmc.us/download.php?link='.strip_tags($package_get).'?action=love"; ?>;
$(function(){
$("#btn_my_love").click(function(){
$.ajax({
url:my_url,
type:'GET',
success:function(data){
//comment the following result after testing
alert("Page visited");
},
error: function (request, status, error) {
alert(request.responseText);
}
});
//prevent button default action that is redirecting
return false;
});
});
</script>
Yes, it is possible. I am assuming you know what ajax is and how to use it, if not I am not going to give you the code because some simple reading on ajax as suggested by #Black0ut will show you how. But the basic steps are as follows:
Send ajax request to a PHP script that will update +1 vote to the database
In the PHP script, add +1 to the database and return some data to the ajax, maybe the new number of votes
Parse the return data in your JavaScript and update the button accordingly

Updating AJAX request variable with ID of PHP generated table row on click

Im probably overlooking something very obvious but at this point i surrender and need help.
Here is my situation. When my page loads, in a while loops, PHP generates a table with data from my server. Each table row has a name column, phone, etc. One of the columns is an icon that when clicked allows the user to view a popup with notes on this particular lead. Easy stuff.
The icons in each row have the same class name and their ID's are unique.
I have an AJAX request that should be pulling the notes data from the server and displaying it in the popup when the user clicks on the relative icon. I am trying to use $('.class').click(this).attr('id'); to set a variable in my AJAX request with the id that needs to be submitted to my PHP script.
PROBLEM: The AJAX request and return seems to be working fine but no matter which row icon I click on it only displays the data that belongs to the first row, or the first instance with the class name 'homelead' Example: I click on row 1 icon and i get a popup with row 1's notes, GREAT!. I click on any other row and it only shows the 1st rows data, :(. I have confirmed that the ID's associated with each row icon are correct by doing a simple click.(this).(id) and alerting the id belonging to the row icon. All is correct, just can't seem to get the JS variable to update with the correct ID.
Im confused why this is. Any help would be appreciated. Here is my current code.
HTML:
<td>
<img class="homelead" id="<?php echo $leadsfetch['unit_id'];?>"
onclick="ajax_unitnotes();" src="images/list-view.png">
</td>
<?php echo "</tr>"; } ?>
AJAX request:
function ajax_unitnotes(){
var hr = new XMLHttpRequest();
var url = "PHP/getnotes.php";
// this variable should update with clicked rows id before submitting to PHP script
var unitidnotes = $('.homelead').click(this).attr('id');
var vars = "unitidnotes="+unitidnotes;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("unitnotes").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("unitnotes").innerHTML = "processing...";
}
As you are using an onclick trigger in the tag itself - which is usually un common when using jQuery. You can do this:
<img class="homelead" id="<?php echo $leadsfetch['unit_id'];?>"
onclick="ajax_unitnotes($(this));" src="images/list-view.png">
And the in your function
function ajax_unitnotes(e){
var unitidnotes = e.attr('id');
}
Your current code
var unitidnotes = $('.homelead').click(this).attr('id');
Actually does not know what it the this object you are trying to access.
Better yet you can use a jQuery event, remove the onclick from the img tag and have an event like this:
$('.homelead').click(function(){
id = $(this).attr('id');
});
You could pass the clicked object this to the function trigged by "onclick":
onclick="ajax_unitnotes(this);"
That will make the DOM object you clicked on available inside the JS function.
You need to change the function signature accordingly:
function ajax_unitnotes(clickedElement){
and then you can alter this
var unitidnotes = $('.homelead').click(this).attr('id');
to
var unitidnotes = clickedElement.id;
This will give you the value of $leadsfetch['unit_id'] = img id.

How to use reload/refresh when click cross then jquery modal will be close

I have used same form for adding and edtting data. Adding and Editting is done successfully and I am refreshing after editing and adding. But I need some solution which is below
My jquery code is below
$(".update_vehicle_info").click(function(){
var hdn_id = $(this).attr('data-hdn_id');
$("#vehicle_form_div").find("#hdn_id").val(hdn_id);
var post_url = "<?php echo base_url();?>index.php/spc_con/get_vehicle_info_data/" + hdn_id;
$('#hdn_id').empty();
$.getJSON(post_url, function(response){
document.getElementById('financial_year_id').value = response.financial_year_id;
document.getElementById('vehicle_id').value = response.vehicle_id;
document.getElementById('brand_id').value = response.brand_id;
document.getElementById('country_id').value = response.country_id;
document.getElementById('reg_no').value = response.reg_no;
document.getElementById('capacity').value = response.capacity;
document.getElementById('running').value = response.running;
document.getElementById('serviceable').value = response.serviceable;
document.getElementById('condemned').value = response.condemned;
});
$("#vehicle_form_div").dialog("open");
});
I have screen shoot which is below
If i click edit button, if i don't edit now and if click Add Vehicle Info then edit field value has stayed but
I need when i click edit and click cross without editing. Then Page will be refresh/reload which if i click Add Vehicle Info then every field Data won't stay it.
How to solve it, Please help me.
UPD:
give to each of your tr some unique id, for example <tr id="tr_pk_23">...</tr> where 23 is a primary key of the row in you databse.
<button onClick="showModalForm(this,23);">EDIT</button>
function showModalForm(button,id){
var $tr = $(button).closest('tr');
/*
* Send ajax request to your php script /myScript.php?id=23
* Find data in database by id, and generate modal form with php, send it back to browser append to body and show it to user.
*/
}
Update button in modal form must be an ajaxButton. So onClick should be assigned as function
<button onClick="saveDataAndUpdateRow(this,23);">UPDATE</button>
JavaScript:
function saveDataAndUpdateRow(button,id){
var $form = $(button).closest('form');
var data = $form.serialize();
/*
* Send data to another script, save your data in DB and generate a new <tr> with updated values
*/
var $new_tr = #ajaxresponse;
var $old_tr = $('#tr_pk_'+id);
$old_tr.after($new_tr);
$old_tr.remove();
}
Feel free to ask me any questions about this concept.

Attaching textbox value to a link in the form of a variable without using submit button

I was wondering how it would be possible to attach an HTML form's text box value to a link. For instance, I have 3 links and each link goes to a different PHP file, however, I need to pass a variable. Because of the design of my page, I cannot use buttons. So, I created a form with a text field. How do I send that Text Fields value with the links?
EG:
<form>
<input type="text" name="test1" id="test1"></input></form>
Link 1
Link 2
Link 3
I hope this makes sense as to what I am trying to do.
EDIT:
I tried to do this dynamically, but:
OK, I made a function like this:
<script>
function awardcode()
{ var awamount = document.getElementById("awardamount");
document.write('<?php $awardvar = ' + awamount.value + '; ?>');
};
</script>
Then, I made the link via PHP that looks like this:
echo '<a id=awlink3 name=awlink3 href="index.php?siteid=gmaward&type=xp&post=' . $posts_row['posts_id'] . '&handle=' . $posts_row['handle'] . '&varamount=' . $awardvar . '">Award XP</a>';
However, that didn't work. This is my input box code:
<form><input type=text name='awardamount' id='awardamount' onchange='awardcode()' style:'width:10px;'></form>
When I put the number and then tab, it loads an empty page.
How can I adjust that?
You'll need to dynamically change the link using JavaScript. Here's one approach:
$('a').on('click',function(e) {
e.preventDefault();
var url = $(this).attr('href').split('$')[0];
window.location = url + $('#test1').val();
});
But it might be better to add an onchange event to the textbox itself, so that the HREF changes instantly and the user can see the intended destination on mouseover:
$('#test1').on('change', function () {
var val = $(this).val();
$('a[href*=\\?id\\=]').each(function (i, el) {
$(el).attr('href', function (j, str) {
return str.split('?')[0] + "?id=" + val;
});
});
});

update json data into db

Alright... this seems complicated for me..
I don't know if it is.
filename: add_types.js
I have some data, which i create into mysql db (is for a back-end system).
through jquery/ json. It work fine.
var last_id = data.last_id;
var fck_editor = data.fck_editor;
var new_data = '<div id="input_highlight'+last_id+'"><strong style="font-size:14px;">Overskrift:</strong> <br />';
new_data += '<input type="text" name="overskrift[]" /><br />';
new_data += '<input type="hidden" name="tekst_id[]" value="'+data.last_id+'" />';
new_data += fck_editor;
new_data += '<img src="/gfx/admin/icons/delete.png" alt="" />Slet';
new_data += '</div><div id="loader'+last_id+'"></div><br />';
$(div_id).append(new_data);
Now I just need to update it (in the same file where it gets outputed)
rejser.php
my data goes out here in a div
<div id="add_here" class="add_here_bg"></div>
I want the ouput from add_types.js to be updated in db when i submit another form in the rejser.php file.
pls inform me, if my question is understandable.
You could use a regular jQuery AJAX-request, which submits the contents of your div to a server-side script:
var content = $('#add_here').html();
$.get(url_of_script, content);
And then have the script add it to the DB. Are you familiar with using PHP/MySQL to do this?
If you want to update this stuff when a form is submitted, try attaching an event listener to the onSubmit event of the form.
Edit:
So, first add the onSubmit attribute to your form:
<form onSubmit="return formSubmit(event);">
Now, you'll have to define this function somewhere - really doesn't matter where you do it, though the <head> section of your page is recommended. External file is, of course, also possible.
function formSubmit(event) {
var content = $('#add_here').html();
// this callback will make sure the form is submitted after having completed the other request
var callback = function() { event.target.submit() };
$.get(url_of_script, content, callback);
// Now, cancel the default event, the callback will take care of the submit afterwards
event.stopPropagation();
}
Haven't tested it, but something like this is supposed to work. Let me know if you need some more help.

Categories