How call another php page after jQuery / Ajax success method? - php

I have following Ajax Success method :
success: function(data, el){
var parent = el.find(".jFiler-jProgressBar").parent();
el.find(".jFiler-jProgressBar").fadeOut("slow", function(){
$("<div class=\"jFiler-item-others text-success\"><i class=\"icon-jfi-check-circle\"></i> Success <b class=\"text-danger\"> Delete</b></div>").hide().appendTo(parent).fadeIn("slow");
});
console.log(data);
},
In this success method you see that I have a link which is :
Delete
and
console.log(data)
This console.log(data) is returning following String :
mpic_list_573ecaafae8220.41741946 |76|40
Now I want call a php page e.g : delete_upload_image.php after click on this link Delete with a string mpic_list_573ecaafae8220.41741946 and 76 and 40
I mean :
In delete_upload_image.php page I can get 3 string which is passed when I click on the delete link.
`

You must either bind the click to a function where you send the user to the desired page or directly make a link in the button.
First, if you want to send the differents params separately, you must split them.
var params = data.split('|');
And then use it as you want, for example bind the click method to the new link to create a new ajax call.
$('#delete_upload_image').on('click', function() {
var params = data.split('|');
var url = "delete_upload_image.php?param1=" + params[0] +"&param2=" + params[1] + "&param3=" + params[2];
// Make AJAX call as you want to url
$.get(url);
});

Catch your parameters in your data using split method :
var stringParam = data.split('|')[0];
var int1Param= data.split('|')[1];
var int2Param= data.split('|')[2];
then put your parameters inside your link :
$("<div class=\"jFiler-item-others text-success\"><i class=\"icon-jfi-check-circle\"></i> Success <b class=\"text-danger\"> Delete</b></div>").hide().appendTo(parent).fadeIn("slow");

you must put your data in your link tag:
<a href=\"#delete_upload_image\" data-params='" + data + "'>Delete</a>
then you can send delete requests to "delete_upload_image.php" by below codes:
$(function(){
$('body').on('click', '[href=#delete_upload_image]', function() {
var params = $(this).data('params').split('|');
var url = "delete_upload_image.php?param1=" + params[0] +"&param2=" + params[1] + "&param3=" + params[2];
// Make AJAX call as you want to url
$.get(url);
});
});

now I understand what is your problem;
You want to get the parameters from console.log.
but you can not get the console.log value directly.
What you can do is:
hook the console.log function so that you store when it logs by this code:
var store = '';
var oldf = console.log;
console.log = function(){
store = JSON.stringify(arguments);
oldf.apply(console, arguments);
}
use below function to get parameters from console_store variable and delete image:
function delete_image()
{
var params = store.split('|'),
queryString = $.param({param0:params[0], param1:params[1], param2:params[2]}),
url = "delete_upload_image.php?" + queryString;
$.get(url);
}
call the function on link click:
$('body').on('click', '[href=#delete_upload_image]', delete_image);

Related

Assign the jquery value of a div to a php variable

I am using a jquery calendar script that assigns the content of a div using ajax.
$('#details-event-id').html(id);
The div tag:
<div id="details-event-id"></div>
is in another file and displays the id correctly.
<div id="details-event-id">91</div>
Is it possible to get the id, 91, to be assigned to a PHP variable?
Using ajax you can send the value to the server and then assign to the php variable.
If you think you assign php variable in any javascript event in client side, its not possible without any asynchronous calling of the server script.
If I understand correctly you would like to send the variable id to a PHP file. You can achieve this by using AJAX. Bellow I'm showing two ways to get it done.
var id = $('#details-event-id').html(id);
AJAX with good old JS
ajax(myfile.php, {id:id}, function() {
// the following will be executed when the request has been completed
alert('Variable id has been sent successfully!');
});
function ajax(file, params, callback) {
var url = file + '?';
// loop through object and assemble the url
var notFirst = false;
for (var key in params) {
if (params.hasOwnProperty(key)) {
url += (notFirst ? '&' : '') + key + "=" + params[key];
}
notFirst = true;
}
// create a AJAX call with url as parameter
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
AJAX with JQuery
$.ajax({
url: 'ajax.php', //This is the current doc
type: "GET",
data: ({
id: id
}),
success: function(data) {
// the following will be executed when the request has been completed
alert('Variable id has been sent successfully!');
}
});
Offtopic: you can see why some prefer JQuery...
When either function (Jquery or plain JS) is launched it will send the variable id to the file myfile.php. In order to retrieve the variable from the call you won't use $_GET[...] but $_REQUEST[...].
myfile.php
<?php
if(!isset($_REQUEST['id'])) {
echo "no variable was sent";
}
$id = $_REQUEST['id'];
// process data, save in db, etc ....
You may return a value to the JS callback function by using echo() not return

jQuery DataTables - Send URL parameter with Ajax call

I am using jQuery DataTables with Ajax-sourced data and pagination. Each time when I click pagination link the same Ajax URL is called.
How can I send different offset to load records accordingly?
You can do that with ajax.data option.
For example, to send current page number as URL parameter use the code below:
var table = $('#example').DataTable({
"ajax": {
"url": "/getNextPageData",
"data": function(){
var api = $('#example').DataTable();
// Get paging information
var info = api.page.info();
// Update URL
// Send page number as a parameter
api.ajax.url(
"/getNextPageData/" + (info.page + 1)
);
}
}
});
Try this code for pagination:
function pagination(val)
{
var pageurl='yourPage.php';
event.preventDefault();
$.ajax({
type:'post',
url:pageurl+'?page='+val,
success: function(data){
$('.element').html(data);
}});
}
Define this function in your pagination in html like that
<a onclick='pagination("<?= $i ?>")' href='yourPage.php?page=".$i."'><?=$i?> </a>

calling on a complex function with onClick (ajax)

So I have this chunk of code here (below). It waits for a video to finish playing and then it looks up a cookie, sends that info to a php script through ajax, gets back a url from json, and reloads an iframe with a new url.
So I think you'll agree, it's sorta a lot going on.
Its purpose is to advance ONE forward in a playlist of videos. I am trying to create a button area where a user can click a >> sort of button and go forward. Which is exactly what this function does.
Rather than starting from scratch with a new function, is there a way to activate all of the above function functionality (ajax and all) when the user clicks that button?
<script>
function ready(player_id)
{
$f('play').addEvent('ready', function()
{
$f('play').addEvent('finish', onFinish);
});
function onFinish(play)
{
var now_video_var = $.cookie('now_video');
console.log ('player ' + now_video_var + ' has left the building');
var intermediate_integer = parseInt(now_video_var);
var request2 = $.ajax({
url : "geturl.php",
data : {intermediate_integer : intermediate_integer},
type : 'post'
}).done(function(data) {
var gotfrom = jQuery.parseJSON(data);
var NEWURL = gotfrom[1] ;
console.log(gotfrom);
console.log(data);
console.log(gotfrom[1]);
var theiframeforrealyo = document.getElementById('play');
$(theiframeforrealyo).attr("src", "http://player.vimeo.com/video/" + gotfrom[1] +"?api=1&player_id=play&title=0&byline=0&portrait=0&autoplay=1");
var new_video_var = intermediate_integer +1;
$.cookie('now_video', new_video_var);
console.log ( 'cookie function ok: the cookie is....');
console.log ($.cookie('now_video'));
});
}
}
window.addEventListener('load', function() {
//Attach the ready event to the iframe
$f(document.getElementById('play')).addEvent('ready', ready);
});
</script>

Processing PHP variable in javascript and returning back to PHP

I am working on an application where I fetch data from database and process it using javascript/jquery like this:
$sqlEdit = "select revisionContent from tbl_revision where revisionId='".$_SESSION['contentId']."'"; //Query to fetch the result
$rsEdit = $dbObj->tep_db_query($sqlEdit);
$resEdit = $dbObj->getRecord($rsEdit);
$IdLessContent = $resEdit['revisionContent'];
<script language="javascript">
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
I get the required data in viewContent.I want to display it on the page in this section
<div id="mainWrap" onClick="fnDestroyEditable();">
<?php echo $resEdit['revisionContent']; ?> //THis is the unprocessed data displayed directly from database.I want to display the processed data here
</div>
I know we cannot get javascript variables to PHP as both are different (one server side and other client). But then how can I achieve this in my scenario?
EDIT I would like to add that the returned data is HTML stored in the database.So,I get the html->process it(add id attribute)->want to return back after processing
you can put the viewContent inside #mainWrap using javascript.
just make sure the DOM is loaded wrapping your js code with $(document).ready()
and add:
$('#mainWrap').html(viewContent);
at the end of your function.
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
});
if you need to send back info to the server you have to do it with ajax.
I added a javascript function addId() that will be invoked on click on one of the elements.
the new code is:
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
$('#mainWrap .addId').children().click(function({
addId(this);
}));
}
addId = function(elem){
// elem is the child element you clicked on
// $(elem).attr('id') should be "com-[randomString]"
$.ajax({
type: "POST",
url: "path/to/php/script", // update id PHP script
data: data, // whatever you need in json format
dataType: "json",
error: function() {
// error function you want to implement
errorFunction();
},
success: function(resp) {
// do whatever you need with the response from you PHP action
}
});
};
if you need to to call server with out human interaction just substitute
$('#mainWrap .addId').children().click(function({
addId(this);
}));
with:
$('#mainWrap .addId').children().each(function({
addId(this);
}));
if I undesrstand you, you shold only add in the end of your js code this line:
$('#mainWrap').html(viewContent);
If you want to send JS data to PHP, you should use ajax request.

submit a value from span field

i have a from with a submit button
after using jquery the page will have :
for(var i=0 ; i <10 ; i++){
'<span class="ioAddConcept">'+ currentConcept[i] +'</span>\n\
with\n\
<span class="ioAddRelation">'+ currentRelation[i] +'</span>\n\'
}
(that piece of code is just an example)
the variables currentConcept[] and currentRelation[] i got its values from database using Ajax
**i am using PHP**
and my question how to submit the page with these two variables ?
i mean in the server i hope something to be like this
$concepts = $_POST['currentConcept[]']
Get these values in jQuery like this:
var ioAddConcept = $(".ioAddConcept").html();
var ioAddRelation = $(".ioAddRelation").html();
Now you can set these values into form text boxes:
$('input.ioAddConcept').text( ioAddConcept );
$('input.ioAddRelation').text( ioAddRelation );
OR if you are submit form via AJAX request:
$.ajax({
url : '/path/to/action.php',
type : 'POST',
data : 'value1=' + ioAddConcept '&value2=' + ioAddRelation,
success : function( data ) {
alert(data);
}
});
Get these values on server side:
print_r( $_POST );
Add an ID to your span element
<span id="ElementID"> your variable text here</span>
Then use jquery to get the text out
var spanText = $('#ElementID').html();
Something like that
var currentConcept = $('currentConcept').html();
And then you can send this var as a param in you request to server
Update
$("form").submit(function() {
var currentConcept = $('.currentConcept').html(); // it's an Array
var currentRelation = $('.currentRelation').html(); // it's an Array
$.ajax({
url : // your URL,
data : 'currentConcept=' + currentConcept '&currentRelation=' + currentRelation,
success : function( html ) {
// write your code here
}
});
}
// server side (php)
$currentConcept = $_GET('currentConcept');
$currentRelation = $_GET('currentRelation');

Categories