Using JQuery.Ajax to change content in other file - php

I am using an iFrame in my application that lets user to upload a CSV file which has information about the new countries to be added into database. What I want is as soon as the CSV file is processed into the database the existing select box that shows current countries from the database should get updated with newly added entries of CSV file.
I am the making ajax call like
$(document).ready(function(){
jQuery.ajax({
type: "POST",
url: "get_all_countries.php",
data: '',
cache: false,
success: function(response)
{
$("#all_countries_select_box").html("<select name='all_countries' id='all_countries' MULTIPLE size='8' style='min-width:250px;'>"+response+"</select>");
}
});
});
My only problem is the id 'all_countries_select_box' is in another PHP file called 'manage_countries.php'. Is there a way to change content of that file from the file that is in iFrame (upload.php). If not, what could be the best possible solution

If you want to access the parent window from inside an iframe you should use window.parent
success: function(response)
{
var parentJQuery = window.parent.jQuery;
parentJQuery("#all_countries_select_box").html("<select name='all_countries' id='all_countries' MULTIPLE size='8' style='min-width:250px;'>"+response+"</select>");
}
if the file you wantr to modify instead is inside an iframe you should do
success: function(response)
{
$('#idoftheiframe').contains().find("#all_countries_select_box").html("<select name='all_countries' id='all_countries' MULTIPLE size='8' style='min-width:250px;'>"+response+"</select>");
}

Related

jQuery AJAX Onchange Redirect Issue

I have my bit of jQuery AJAX code, to send a file to a PHP script, update/insert to db and continue to edit by ID as redirect. Works fine.
Problem is.. every other page except homepage (no rewrites, base url) the script will break the onchange event listener, and skip upload then continue to editing a broken upload.
Every other page, this code works perfect and does as intended. But homepage, it does not listen. I can not figure it out. Only recently we got the last insert ID working for redirect to edit entry.
$(document).ready(function(a) {
$("#form-fileUpload").on("change", function(a) {
var file_data = $('#uploadFile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: '/ajax_file_upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
if (data.redirect == true) {
window.location.href = '/file-edit.php?id=<?php echo mysql_insert_id(); ?>';
}
//alert(php_script_response);
}
});
});
});
How can I prevent this from ignoring the onchange submit action for our form? Is this a root domain thing? Didn't think the PHP code was relevant, it works fine as intended.
So user browses for file, and form automatically uploads and redirect happens sending them to edit and add more details in a form. Perfect on all pages but homepage. Is the JS at fault? Is there handling for this in this situation away from sub pages?
The PHP code that plays this role (AJAX script):
$id = $conn->lastInsertId();
// Redirect & complete details
header("Location: https://www.website.com/editfile?id=".$id.");
You should use full url to direct in jQuery like below
window.location.href = 'https://www.website.com/file-edit.php?id=<?php echo mysql_insert_id(); ?>';

Ajax call not working with other Ajax Calls

I have an Index.php file that makes an ajax call and loads a php page
Within that php page that is loaded using ajax I have a html form.
I am trying to do another ajax call from Index.php that if a select box is changed a new ajax call is made.
Everything works fine but the ajax on change for the select box.
I think it has something to do with the fact that the form is loaded in with ajax and the on change is using ajax.
Is this possible to do?
$(document).ready(function() {
$("#message-loading").show();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "details.php",
data: dataString,
success: function(html)
{
document.getElementById('message-box-body').innerHTML = html;
$("#message-loading").hide();
}
});
This is the select change code
$(".selectbox").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "another-page.php",
data: dataString,
cache: false,
success: function(html)
{
$(".another-selectbox").html(html);
}
});
});
The select box is located inside the php page of the first ajax call. The ajax change should load new values for another select box within the first php page.
I have this working if I don't load the php page using ajax.
jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM, for example - via AJAX, are unrecognized by jQuery.
To combat that either re-bind your jQuery function or use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.
You can access newly created element on the pages using $(document).on.
$(document).ready is only aware of elements that existed when the page was loaded.
So, for an element that existed when you you loaded the page you would use:
$(document).ready(function(){
$("#element").click(function() {
alert("You clicked an element that existed when you loaded this page.");
});
});
For an element that did not exist when you loaded the page, you would use the following:
$(document).on({
click: function () {
alert("You clicked an element that DID NOT exist when you loaded this page.");
},
}, '#element');

Get the Ace editor content using PHP

Hey guys I was wondering if it's possible to get the content within the tags I have using PHP. I'm using the Ace editor and I have a save button. I'm trying to save the content to a file using PHP, can someone tell me how I can get the content using PHP please?
May you can save it via AJAX,
send the editor content and desired filename (and path also) using POST method
example
function saveCode () {
$.ajax({
url: 'handler.php',
type: 'POST',
dataType: 'html',
data: {code: editor.getValue(), filename: './test.php'},
})
.done(function(result) {
console.log("success");
});
}
then on the handler.php
<?php
if(isset($_POST['code']))
{
file_put_contents($_POST['filename'], $_POST['code']);
echo 'success';
}
?>

Ajax load duplicates entire page

I am trying to refresh a div with jquery load(); but the load displays the correct information but duplicates entire parts of the page that arent in the div
$.ajax({
type: 'POST',
url: $(this).attr('action'),
cache: false,
data: $("#uses_form").serializeArray(),
success: function(data)
{
$('#uses_form_div').load('#uses_form_div');
}
});
return false; });
i think you are having a misunderstanding..
if you want to load an external url into the div block
$('#uses_form_div').load("./a.file");
will do it. see the api docs.
Or if you are trying to load the ajax response of the $.ajax call into the div, it should be
$.ajax({
type: 'POST',
url: $(this).attr('action'),
cache: false,
data: $("#uses_form").serializeArray(),
success: function(data)
{
$('#uses_form_div').html(data); // see here
}
});
UPDATED according to comments below:
if the case of an included page to be refreshed. I have two ways to recommend.
make the included file as a separate url and load it initially. so instead of include you will be loading it via jquery as the page loads by a jquery load call. and when you want to refresh it you can do $('#uses_form_div').load("./a.file");
you can put it as include it self and when you need to update, make an ajx request get the data back. Here you have 2 choice. You can build the dom at server and give html as ajax response and simply $("#uses_form_div").html(data) or get the response as json
and build your dom at client side and load it via same $("#uses_form_div").html(data).
I also had the same problem but finally found the answer
<script type="text/javascript">
function recp() {
setInterval(function()
{
$("#result").load(location.href+ ' #my');
});
}
</script>
<div id="result">
<div id="my"><?php echo date('a:i:s'); ?></div>
</div>

Download pdf file from a string using Jquery

All,
I have a PHP5 application written with Zend Framework and MVC. On my home page, I want to incorporate the functionality to download a dynamically generated pdf file. The way this is done is:
User clicks "download file" link.
On Click, an AJAX call occurs to a PHP controller, which takes the form data, generates the pdf and returns it as a string.
My javascript function now has the pdf string.
How can I display the user an "Open/Save" dialog to download the pdf file from javascript?
I have the following code:
<script type="text/Javascript">
$('#dlcontent').click(function(e) {
$.ajax({
type: 'POST',
url: "/downloads/dlpolicies",
data: $("#frmMyContent").serialize(),
cache: false,
dataType: "html",
success: function(html_input){
alert(html_input); // This has the pdf file in a string.
//ToDo: Open/Save pdf file dialog using this string..
}
});
});
</script>
Thanks
I would try to keep this simple. Just sumbit the form with a target="_blank" and then have PHP force the file download.
HTML CODE
<script type="text/Javascript">
$('#dlcontent').click(function(e) {
e.preventDefault();
$("#frmMyContent").submit();
});
</script>
<form id="formMyContent" action="/downloads/dlpolicies" target="_blank" ... >
...
</form>
Then on your server side, you need to tell PHP to send the response as a "download".
PHP Code
$this->getResponse()
->setHeader('Content-Disposition', 'attachment; filename=result.pdf')
->setHeader('Content-type', 'application/pdf');
Got this from here:
Zend Framework how to set headers
The simplest way of doing it is open a new window with URL to pdf string.
Add an element to your page where you want the link to go. It can be a span or a div or a cell in a table or whatever you want. Give it a unique ID. Then use jQuery to set the html of that element. I refer to it as somepageelement here.
$('#dlcontent').click(function(e) {
$.ajax({
type: 'POST',
url: "/downloads/dlpolicies",
data: $("#frmMyContent").serialize(),
cache: false,
dataType: "html",
success: function(html_input){
$('#somepageelement').html('Click here to download the pdf');
}
});
});

Categories