I have a few external links on my site and when one of them is clicked I am also using jQuery ajax to set a variable into session, so that when a user is back from the other site the variable is available. Sometimes, though, it seems that the redirect happens too fast and the session is not set. Is there to delay sending user to another site, perhaps by popping a modal?
Here's how I currently do it:
$(".myLink").click(function() {
var soc = $(this).attr("id");
$.ajax({
type: "POST",
url: "/myAjax.php",
data: {
"action" : "sent",
"social" : soc
},
dataType : "json"
});
});
I think that you would need to disable the default for the link, send the data to a php script to save the session var, and once it is completed, forward the user on. Something like this (not tested):
$('a.blank').click(function(e){
e.prevendDefault();
$.post( "session.php", {
url: $(this).attr('href'),
id: $(this).attr('id')
})
.done(function( data ) {
window.open(this.href);
});
});
Note, you will need to check for failure and add a default behavior, so that if the php script fails for some reason, the user is still directed to the given url.
Related
I'm trying to create a simple "Register your interest" action. I have the front end working but I'm not sure how to link the AJAX to the PHP file. Where do I put the PHP file?
My current code for the AJAX is:
$.ajax({
url: "register-interest.php",
type: "GET",
dataType: "json",
data: {
type : "registerInterest",
email : userEmailLog,
user : userNameLog,
product : productTitle,
sku : productSku
},
success: function (response) {
JSON.stringify(response);
},
error: function (err) {
JSON.stringify(err);
},
complete : function() {
//$('.user-accept').addClass('unhide');
loading();
}
});
First you check url variable is correct or not and then provide response any data like
success: function (response) {
JSON.stringify(response);
},
Your url value is:
"register-interest.php"
This implies that the php file that processes the AJAX request needs to be available at the same directory level as the page that includes the javascript file that is performing the AJAX request.
Example:
If your page is at http://example.com/my/ajax/page.html
Then the javascript will perform the AJAX request to the URL http://example.com/my/ajax/register-interest.php
Alternatively if you change the JS url value to read "/register-interest.php", then the AJAX request will be made to: http://example.com/register-interest.php
Where you need to put it on your server depends on how your web server's webroot's folder structure is organised, but you should be able to work back from the URL the javascript will be requesting to work this out.
I am using Laravel as a PHP framework and I have Jquery set up so it prompts the user if they want to confirm redirecting away from the page or not.
The problem is that if the user confirms the redirect away from the page, I need to somehow perform some database operations to set various statues to closed on my tables.
How is this possible?
My Jquery code prompting the user
<script type="text/javascript">
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
Just make an Ajax request to inform the server that the user will be redirectd.
$(window).bind('beforeunload', function(e){
if ( confirm("Are you sure you want to leave?") ) {
e.preventDefault();
// make ajax request to inform the server
$.ajax({
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
// handle things
}
});
// Redirect.
window.location.href = someURL;
}
});
I have a website that uses bootstrap tabs so I'm trying to make everything work with minimal refreshing with Ajax, however I'm having trouble with getting an ajax post to work with a mysql query until the page is refreshed.
Once a button is pressed the value is grabbed from the ID of that element by Ajax and a bootstrap tab is opened. This is where I want the data to be passed so the results are relevant to the option that the user has selected.
Modules.php
(Ajax request)
$(".completed").click(function() {
var element = $(this);
var ID = $(this).attr("id");
var dataString = 'id='+ ID;
$.ajax({
cache: false,
url: "includes/scripts/ajax/module_parts.php",
type: "POST",
datatype: "text",
data: dataString,
success: function (html) {
$('#moduleNum').html(ID);
console.log(ID);
},
error: function(data, errorThrown)
{
alert('request failed :'+errorThrown);
}
});
return false;
});
module_parts.php
$module_id = mysqli_real_escape_string($connection, $_POST['id']);
echo $module_id;
$query = mysqli_query ($connection, "SELECT number FROM Modules WHERE number = '".$module_id."'");
I know that the post is working correctly because I tried turning the post into a session then when refreshing the page the data was displayed.
Also the data is displaying correctly when appending the ID to an html element.
Many thanks,
Zack.
Just as a side note, I prefer to do this with ajax shenanigans. It may help you ...
Altered the anchor element:
Click me
Javascript:
ID = $(this).attr("id")
$('body').on('click', '[rel="completed"]', function() {
$.post('includes/scripts/ajax/module_parts.php', { id : ID }, function(data) {
$('#moduleNum').html(data); // data or ID ?
}).fail(function() {
alert('request failed');
});
});
The $('body').on part helps to keep scripts alive should you insert new links or buttons. It means anything within the body tag but you can and maybe should narrow it down further such as the surrounding div.
I, personally, find this way to be easier to deal with, especially if there is just simple data passing to and fro.
1) Check if id is passed by post and get by module_parts.
2) I'd rather use object when passing post data via ajax:
data: { id : ID }
3) Good option to check ajax requests is to use Firebug (on Console), you can check requests details without echoing.
At least two things in your script need resolution.
datatype should be changed to dataType (text is not one of jQuery's "intelligent guess" types (xml, json, script, or html), so dataType must be correctly spelled.
You should prevent the default behavior of the anchor click event.
(".completed").click(function(e) {
e.preventDefault
...
There may be some additional problems, but these two jumped out at me.
I want to pass the ID to the urlstring via jQuery without refreshing jQuery and # tag so that I could get the ID via php $_get['ID'] function.
But the problem is that
If I use #, page did not get refreshed, however PHP did pick the ID from url.
If I don't use #, then php do picks the ID but Page get refreshed.
I want to pass an id to php without refreshing the page.
//javascript
function com(id) {
location.href = '#?ID=id'; //by this way way,page doesn't refresh, ID appears in the url string but ID is not picked by PHP as # is there
// location.href = '?ID=id'; this way way, ID appears in the url string , ID is also picked by PHP as # is there.But page get refreshed.
$.ajax({
type: "Post",
url: "getdata.php",
async: true,
cache: false,
success: function(data) {},
});
}
//php for getdata.php
<?php echo $_GET['ID']; ?>
You need to educate yourself about server-side vs. client-side operations. Javascript is client side. The server (running PHP in your case) knows nothing about what javascript is doing unless you send some information back. This can be accomplished via a page refresh or via ajax (put simplistically).
What you want is ajax which is an asynchronous request that goes back to the server. The server can then handle it and choose to pass information back to the page. Look into jQuery's ajax.
Update based on your updated comment:
function com(id) {
//forget about appending the id. This isn't doing anything.
//You can use it for informational purposes or so that if someone cuts and pastes
//the link you can handle it server side appropriately.
location.href = '#?ID=id';
//instead focus on this call. append your query string to the url
$.ajax({
type: "POST",
url: "getdata.php?ID=12345",
async: true,
cache: false,
success: function(data) {
alert(data); //should alert the id processed by php
},
});
}
I have a table that outputs all my contacts via a while loop from my database.
my syntax is like this:
SELECT * FROM contacts WHERE id = $_SESSION['user_id'] ORDER BY name ASC LIMIT 5
that pulls out all my data and only gives me 5 results.
Now my goal is to have a little button that opens up a model box with jquery (this I can manage on my own) with a form asking the user to input a number then that number will be sent via post or get to $PHP_SELF and update a local variable with the number the user inputed, then that variable will be used to update the database to increase or decrease the LIMIT value.
I have looked all over the web (with google) to look for submitting a form using AJAX but all the examples i've found don't work for me.
When the user submits the number and the sql query is executed and updated for the outputed table to dynamically update according to the new LIMIT value all without ever refreshing the page to the user.
my jquery code is:
(document).ready(function(){
$("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({
type: "post",
url: "process.php",
data: "val="+ val,
cache: false,
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
});
return false;
});
});
$(document).ready(function(){ $("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({ type: "post", url: "process.php", data: "val="+ val, cache: false, success:
function(){
$('form#form').hide(function(){$('.success').fadeIn();});
} }); return false; }); });
then my php code is:
$new_val = $_POST['new_val'];
$_val = "UPDATE `settings` SET `display_limit` = {$new_val} WHERE `user_id` = {$_SESSION['user_id']}";
mysql_query($_val) or die(mysql_error());
and my form is simple:
any suggestions? I haven't come to how to have my outputed table dynamically update yet so if anyone can point me in the right direction or provide some help that would be awesome.
thanks
EDIT:
Here is an updated jquery script I was working on, I'm able to submit the form successfully! but my only problem is that I can't see the changes until the page is refreshed with defeats the purpose of the AJAX usage... sigh
how can I now have my #results div updated and refreshed with the form submission content?
$(document).ready(function() {
var options = {
url: 'process.php',
type: 'post',
//dataType: 'json',
target: '#last_five_sellers',
success: success
};
// bind to the form's submit event
$('#form').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
function success(responseText, $form) {
$("form#form").hide();
$(".success").fadeIn();
}
});
In your php code where you do the update, You could echo your contacts in html-format. That would then return to your success function in jquery.
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
The function have a parameter data, which is the html-format you echoed in php.
Example
success: function(data){
$('form#form').hide(function(){$('.success').fadeIn();});
$(data).appendTo('#result');
}
You need to understand the flow of a request. Once the php script runs, that is it, it is done. If you plan on submitting back to that same page, it'll be a new request and a new execution of that script. Now, you could add a special case to that script to return the necessary data to your jQuery code, but that's messy IMO. I would rather have a separate script to handle that functionality. This can be looked at as a web service.
So, when a you go to that page in a browser, it will intially display 5 contacts (or w/e the default you have in the LIMIT clause). When you click the icon to display more contacts, you employ jQuery to submit a GET request to that 'web service' page (it really should be GET, since you're retrieving data, not submitting new data). This would then be a list of contacts that you use to update the display on the page, using jQuery/JavaScript.
As noted by Codler, the output from that 'web service' can be HTML which you simply use to replace the existing HTML which displays the contacts. (This would be the preferred way. You almost always want do as much on the server as you reasonably can.)
It looks like your jQuery code is duplicated — there's no need to bind the form's submit event twice. Additionally, the first jQuery block is missing the opening dollar-sign ("$"). And as far as I know, .hide() does not support passing a callback through the first parameter. In the jQuery API documentation, it's written as .hide( duration, [ callback ] ).
I would write:
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(){
$("form#form").hide();
$('.success').fadeIn();
}
});
return false;
});
});
Now, if you want to update your results table dynamically, the simplest way is just to replace the entire thing with the updated HTML. So for instance, if you modified your PHP script (process.php) so that, after updating display_limit, it outputted the new results table, you could then write something like (assuming your results table is table#results):
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(data){
$("form#form").hide();
$(".success").fadeIn();
$("#results").replaceWith(data);
}
});
return false;
});
});
You just have to make sure your script only outputs HTML.
Contrary to what George answers above, HTML will definitely work for this purpose, but I think the ideal method is to send purely the data alone (minus structure/presentation) in either JSON or XML format, and then use JavaScript to build the HTML; you can save a lot of bandwidth this way, and ultimately build a much more responsive application.
EDIT
Here's a mini JSON-based example.
JavaScript:
$(function(){
$("#form").submit(function(){
var val = $("input[name=new_value]").val();
$.getJSON("process.php?val=" + val, function(data){
$("#results").empty();
$(data.rows).each(function(){
$("#results").append('<tr><td>' + this.column_a + '</td><td>' + this.columbn_b + '</td></tr>');
});
});
return false;
});
});
PHP (process.php):
[assuming you already have a result/rows called $result]
$json = array('rows' => array());
while ($row = mysql_fetch_assoc($result)) {
$json['rows'][] = $row;
}
echo json_encode($json);
Now, granted, I haven't tested this code at all, but it should give you the gist of it.