Call html and Php pages with Ajax - javascript

I made an ajax function that call my html pages inside an ajax-container div in my index.php, so now how can i do if i also want to call php pages in ajax?
There is my code:
htaccess rewrite
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^([a-zA-Z0-9\-]*).html$ index.php?p=$1 [L]
index.php
<div class="link" href="page2.html">go html</div>
<div class="link" href="page3.php">go php</div>
<div id="ajax-container">
<?php
$d = "pages/";
if (isset($_GET['p']))
{
$p = strtolower($_GET['p']);
if (preg_match("/^[a-z0-9\-]+$/", $p) && file_exists($d . $p . ".html"))
{
include $d . $p . ".html";
}
else
{
include $d . "404.html";
}
}
else
{
include $d . "home.html";
} ?>
</div>
And this is my ajax function calling html pages from folder pages/
var afficher = function(data, page) {
$('#ajax-container').fadeOut(100, function() {
$('#ajax-container').empty();
$('#ajax-container').append(data);
$('#ajax-container').fadeIn(100, function() {});
});
};
var lastRequest = null;
if (lastRequest !== null) {
lastRequest.abort();
}
var loadPage = function(page, storeHistory) {
if (typeof storeHistory === 'undefined') {
storeHistory = true;
}
lastRequest = $.ajax({
url: 'pages/' + page,
cache: false,
success: function(html) {
afficher(html, page);
if (storeHistory === true) {
history.pushState({
'key': 'value',
'url': page
}, '', page);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
afficher('erreur lors du chagement de la page');
}
});
return false;
};
window.addEventListener('load', function() {
setTimeout(function() {
window.addEventListener('popstate', function(e) {
if (e.state === null) {
loadPage('home.html');
} else {
loadPage(e['state']['url'], false);
}
});
}, 0);
});
$(document).ready(function() {
$('.link').bind('click', function(e) {
e.preventDefault();
var page = $(this).attr('href');
loadPage(page);
return false;
});
});

If you want to execute php and display what it returns on a div you can use jQuery and ajax:
$(function(){
$(".myDivClass").load('yourPHPFile.php');
}());

Related

dropzone.js edit (add/delete) pre-exisitng image files in Magento

below is my code for deleting images when clicked on "remove file" CTA on the dropzonejs box. However, when the "remove file" is clicked, only the thumbnail image is deleted, and not the actual file.
By calling the delete function in Magento through Ajax when the "removedfile" is called, it should delete the thumbnail as well as the file, but it does not seem to work as the server still keeps the pre-loaded image file.
this.on("removedfile", function(file) {
alert("here");
jQuery.ajax({
url: "<?php echo Mage::getUrl("*/*/deleteimage"); ?>",
type: "POST",
dataType: "json",
data: {'pid': "<?php echo $loadpro->getId(); ?>",'file':file.name},
success: function (data) {
Success = true;//doesnt goes here
},
error: function (textStatus, errorThrown) {
jQuery("#vals").text('');
var det = checkfile('<?php echo $loadpro->getId(); ?>');
if(det != null)
{
maxcount = 1;
}
else {
maxcount = null;
}
}
});
Below is the code for the Magento controller that is called in the function above that listens for the "removedfile."
public function deleteimageAction()
{
$id= $this->getRequest()->getParam('pid');
$imagename= $this->getRequest()->getParam('file');
$product = Mage::getModel('catalog/product')->load($id);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$mediaGallery = $product->getMediaGalleryImages();
foreach($mediaGallery as $mediagg){
$file = $mediagg->getUrl();
$fileName = basename($file);
if($fileName == $imagename){
$filepath = $mediagg->getFile();
}
}
try{
$storeId=Mage::app()->getStore()->getStoreId();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$newimage = '';
$data= $this->getRequest()->getParams();
//error_log(print_r($data, TRUE));
$_product = Mage::getModel('catalog/product')->load($data['pid'])->getMediaGalleryImages();
$main = explode('/',$filepath);
foreach($_product as $_image) {
$arr = explode('/',$_image['path']);
if(array_pop($arr) != array_pop($main)){
$newimage = $_image['file'];
$id = $_image['value_id'];
break;
}
}
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$mediaApi->remove($data['pid'],$filepath);
if($newimage){
$objprod=Mage::getModel('catalog/product')->load($data['pid']);
$objprod->setSmallImage($newimage);
$objprod->setImage($newimage);
$objprod->setThumbnail($newimage);
$objprod->save();
}
Mage::app()->setCurrentStore($storeId);
} catch (Exception $e) {
$this->getResponse()->setHeader('Content-type', 'text/html');
$this->getResponse()->setBody('');
}
}
I have tried most of the methods that are in google, as well as stackoverflow, but could not find an answer that works in this case.
If you know a solution to this problem, please let me know.

Second ajax request doesn't work

I made an ajax website calling pages from /pages folder inside an ajax-container div in my index.php.
Now i want to make a second ajax request after the first ajax request success but the second request will be only on certains page,
for example: i call the page work.php and inside this page i want to call a page work-slider from the same folder and replace the work.php page by work-slider.php in my ajax-container div when i click on images link-in
but i can't find a solution for make it,
This is my actual code:
index.php:
<div id="ajax-container">
<?php
$d = "pages/";
if (isset($_GET['p'])) {
$p = strtolower($_GET['p']);
if (preg_match("/^[a-z0-9\-]+$/", $p) && file_exists($d . $p . ".php")) {
include $d . $p . ".php";
} else {
include $d . "404.php";
}
} else {
include $d . "home.php";
}
?>
</div>
Ajax function:
var afficher = function(data) {
$('#ajax-container').fadeOut(250, function() {
$('#ajax-container').empty();
$('#ajax-container').append(data);
$('#ajax-container').fadeIn(100, function() {});
});
};
var lastRequest = null;
if (lastRequest !== null) {
lastRequest.abort();
}
var loadPage = function(page, storeHistory) {
if (typeof storeHistory === 'undefined') {
storeHistory = true;
}
lastRequest = $.ajax({
url: "pages/" + page,
cache: false,
success: f$.ajax({
url: "pages/" + page,
cache: false,
success: function(resultFirst) {
afficher(resultFirst);
if (storeHistory === true) {
history.pushState({
'key': 'value',
'url': page
}, '', page);
}
$.ajax({
// How can i define pageIn variable ??
url: "pages/" + pageIn,
cache: false,
success: function(resultSecond) {
afficher(resultSecond);
}
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
afficher('erreur lors du chagement de la page');
}
});
return false;
};
window.addEventListener('load', function() {
setTimeout(function() {
window.addEventListener('popstate', function(e) {
if (e.state === null) {
loadPage('home.php');
} else {
loadPage(e['state']['url'], false);
}
});
}, 0);
});
// link inside index.php
$('.link').bind('click', function(e) {
e.preventDefault();
var page = $(this).attr('href');
loadPage(page);
return false;
});
// second link inside called page
$('.link-in').bind('click', function(e) {
e.preventDefault();
var pageIn = $(this).attr('href');
loadPage(pageIn);
return false;
});
If that .link-in tag if dinamically inserted into the DOM after the page loads, the bind() method will fail: bind() attach listeners to elements it find when called. If you add a new elemenent after the bind call, it will not receive the listener binding.
In order to prevent that when dinamically inserting html code in a page, you should use the on() method:
$('body').on('click' , '.link-in', function(e) {
e.preventDefault();
var pageIn = $(this).attr('href');
loadPage(pageIn);
return false;
});
And now, every .link-in tag you push dinamically inside body will respond to the click listener. A discussion on using on() by default instead of bind() is in fact found in the bind() documentation.

Getting a post variable inside a function

I have a case where I want to pass a variable inside a function.
The code gives more clarity:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
function loadData(page){
$.ajax({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page }),
success: function(msg) {
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings) {
$(\"#subscritor #container\").html(msg);
});
},
error: function(){
alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function() {
var page = $(this).attr('p');
loadData(page);
});
$('#subscritor #go_bt').live('click',function() {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>";
?>
As shown in the code,
I would like to know how could I pass $id inside the loadData(page) function .
I get this variable from a post request made with ajax, and need to use it inside the function to pass it has variable to loadSubscritor.php
Any idea on how to do it?
EDIT 1: I guees I wasnt very clear on what I wanted, i want to do this :
function loadData(page){
$.ajax({
data: ({ page:page id:$id }),
Thanks in advance.
Well, if I understood what you are trying to achieve you could replace this :
$id=$_POST['id'];
By this :
$id = isset($_POST['id']) ? $_POST['id'] : 1;
And this :
loadData(1); // For first time page load default results
By this :
loadData($id);
For explanation, if it's first time page load, $id will be set to "1".
Else, this will come from $_POST['id'].
Inside your jquery code you can call a php variable in following way
var current_page = "<?php echo $id; ?>" ;
You can make a local variable and easily use as below:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
var id = \"".$id."\";
$(document).ready(function(){
function loadData(page){
$.ajax
({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page
}),
success: function(msg)
{
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings)
{
$(\"#subscritor #container\").html(msg);
});
},
error:
function()
{ alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(id);
});
$('#subscritor #go_bt').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(id);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>
";
?>

jQuery AJAX with PHP to upload contents to MYSQL DB

I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>

Javascript open in new tab by using json

Javascript Code:
<script type="text/javascript">
function MusteriBilgileriKaydet2() {
var veri = {
AnaOzelDurumId: AnaOzelDurumId.GetValue(),
AnaİlgiliPersonelId: AnaİlgiliPersonelId.GetValue(),
};
if (veri.MusteriAdiTextBox1.trim() == "" || veri.MusteriAdiTextBox1 == undefined || veri.MusteriAdiTextBox1 == null) {
$("#showwarning222").html('<img src="/Image/warning.png" title="Müşteri Adı Giriniz!">').show();
}
else {
LoadingPanel.Show();
$.ajax({
url: "/Home/GenelMusterilerGridView2",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(veri),
success: function (mydata) {
if (mydata.error6 == true) { // Error
LoadingPanel.Hide();
alert("Müşteri Adı Mevcut");
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
else { // Success
$("#MusterilerGetir").html(mydata);
LoadingPanel.Hide();
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
},
error: function () {
LoadingPanel.Hide();
$("#showwarning222").html('<img src="/Image/warning.png">').hide();
}
});
return false;
}
}
</script>
My Controller:
public ActionResult GenelMusterilerGridView2(MyModel model)
{
var stringView = RenderRazorViewToString("MerkezPartial", ModelleriGetir());
return Json(stringView, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { error6 = true, JsonRequestBehavior.AllowGet });
}
}
return null;
}
My all codes works well .
I only want to open in new tab page .
So
How can i open in new tab in browser after i post data to my controller ?
Any help will be greatly appreciated.
Thanks.
you can add to your html <a href tag a target that looks like this.
Link name or text
OR you can in your javascript code add
function OpenNewTab(url){
var something = window.open(url, '_blank');
something.focus();
}
Now this should be working fine but just because some clients prevent pop-ups then you could add this to your html tag too.
<div onClick="OpenNewTab();">your link name</div>
Hope this will work for you
Cheers!

Categories

Resources