I am doing a program in PHP (MVC) in which I need to delete a row from the database when I click on a link on the View side. So, when I click on the link, the following ajax function it is called.
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
}
});
}
but I do not want to send any data so it is the reason why I put it as above.
Then, in the Controller side I have the following method:
public function deleteCar($id)
{
//Here I call the function to delete the Car that I send by id. It works fine.
header('Location: http://localhost/project/car');
}
If I call directly the method deleteCar on the link without Ajax the header works properly but in the same moment I use Ajax to call it, I have to refresh the page to see the content that I have modified, I mean, that the Car have been deleted.
The code works fine, just I do not want to refresh the page after AJAX function had finished.
Thanks in advance!
I am guessing the use case is to allow the app to work when the user does not have JS enabled - so they just click the links and get a non-AJAX experience. In this case you probably want to redirect ONLY if the page was requested via GET, not POST. something like
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
header('Location: http://localhost/project/car');
}
is likely what you are looking for.
You will then have to actually remove the element representing the car from the DOM in your success handler, with something like:
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
$('#car-row-' + id).remove();
}
});
}
(that won't be it exactly, it depends how the HTML of your page is setup how exactly you will do this).
I believe the key thing to understand here is - when your PHP function has completed it has removed the car from the database, but the browser still has the same HTML it got from the page originally. Just sending an AJAX request won't change that. If you want the HTML in the browser to change to reflect the new state of the database, you will NEED to do one of two things:
Refresh the page, so the entire thing is rebuilt by PHP based on the current database state
Use javascript to change the HTML in the browser, to reflect the changes you have made to the database state.
It is wrong on so many levels but it's difficult to put in words. It's subtle.
Long story short - think about jquery.ajax as of another virtual tab of you browser.
When you make ajax-request to the server - you create new virtual tab.
You php header could affect this virtual tab and redirect it where that header defined.
But it will redirect that virtual tab, not your current tab - if that makes sense.
What are your options? On success - make redirect with pure javascript.
success: function(response){
location.href = "http://localhost/project/car";
}
This would be the basic way to solve your problem.
i'm not sure whether Ajax is what I need as i'm rather stumped on where to start, but I'll describe what I would like to happen.
I have a PHP file (lets call it scan.php) that contains a For loop that iterates along an array, which holds details of local files stored in a directory on a PHP. For each item in the array (a path to a file), I would like it (presumably an ajax script?) to call another php file (lets call it info.php) and display whatever that PHP file outputs on screen, with info.php taking the filepath in that index of the array as an argument.
Within that info.php file are various (dynamically generated) divs which inserts a different value into the database depending on which div the user clicks on. When that user clicks on a div, it inserts a value into the database (via an ajax call that i've already got working) and then displays a message (i'm using a javascript window.alert). If that message is a success then the info.php function ends, an we return back to scan.php. Whatever echoed out by info.php is cleared and then the loop iterates round again.
Sorry it's a bit complex but I have no idea where to start. Could anybody give me any hints on how to get started? I've had a look at ajax but frankly I have no idea where to start and whether it's even possible to use ajax to delay the PHP for loop.
This was my script that I thought would display info.php, but it's not echoing anything into the "show" div - or anything at all:
function Search_file(path) {
$( "#show" ).empty();
var request = $.ajax({
url: "info.php?path="+path,
type: "GET",
dataType: "html"
});
$("#show").html(result);
request.done(function(data) {
alert("Next file");
});
}
AJAX is asynchronous, so you haven't received your result when you are setting your html. You need to move your 'show' code inside the done handler like so:
function Search_file(path) {
$("#show").empty();
var request = $.ajax({
url: "info.php?path="+path,
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("#show").append(result);
alert("Next file");
});
}
I have one quick question for experienced ones.
I have a page that does a jquery ajax post to another php page with javascript in it.
My question is, will the javascript get executed as well?
Another question.
lets say, that instead of javascript, I have another jquery ajax post request to a third php.
Will any of the 2 work?
Unless the javascript in that "another php page" is actually returned to the client and somehow inserted into the DOM, the JS cannot and will not execute. The resulting output of an AJAX operation is returned as a string to the code that performed the ajax call. It's not interpreted/parsed except in a few very specific cases.
If you're using jQuery's AJAX function to send POST variables to a PHP file, only the backend code will be executed. However, upon success of the AJAX call, you can execute some more JS code as follows
//Define whatever variables you want to pass along to the PHP file
var variable = "";
$.ajax({
url: "file.php",
type: "POST",
data: "variable="+ variable,
success: function(data)
{
//Upon success of the call, you can execute JS code here
}
});
Additional info here
I'm working on a PHP / AJAX application and it's quickly becoming unmanageable!
The application is designed to work much like a a desktop application so almost every user action results in an AJAX call.
For every one of these actions I have some jQuery that posts the data to my PHP script and runs a corresponding PHP function that handles the server side actions.
That means in my jQuery file i'll have something like this:
$('.delete-project').on('click', function(){
// Ajax request to http://myapp.co.uk/ajax/delete_project
});
$('.delete-user').on('click', function(){
// Ajax request to http://myapp.co.uk/ajax/delete_user
});
$('.delete-keyword').on('click', function(){
// Ajax request to http://myapp.co.uk/ajax/delete_keyword
});
I'm sure there is a better way of doing things, but how is it generally done to avoid lots of similar code? The above actions could possible rolled into one 'delete' ajax request which posts the item type and a database ID but a lot of my functions post different data and require different parameters so wouldn't fit so neatly under one jQuery handler.
I've tried finding some resources on how an AJAX application should be put together but all I can find is beginner tutorials on making AJAX requests etc, not how to write a scalable AJAX application.
Just to be clear I know how AJAX works, I'm just trying to find the best way of implementing it in terms of reducing the jQuery and PHP needed where possible.
Are there any good resources that deal with this sort of thing?
You can roll all those into one delete function by using attributes in HTML, for example:
$('.delete').on('click', function(){
var delete = $(this).attr('data-delete');
// Ajax request to http://myapp.co.uk/ajax/delete_{delete}
});
Then your HTML would be something like:
Delete
More information on data-attributes
Not sure if this would help but you could create some functions to reduce your code as it grows. For starters you could prevent duplicating of the ajax call by putting the jQuery .ajax function in a custom wrapper function of your own. For example:
function ajaxGet(myUrl, queryString, successCallback, errorCallback) {
if(queryString) myUrl+= "?" + queryString;
$.ajax({
url: myUrl,
type: "GET",
data: null,
success: function (res) {
if(!successCallback) return;
else successCallback(res);
},
failure: function (res) {
if(!errorCallback) return;
else errorCallback(res);
}
},
By creating a wrapper function, you can pass in the needed data without duplicating the $.ajax call code over and over in each of the click functions. You can also create a similar function for an ajax call using post. You could then dynamically build the click functions to further reduce your code:
function buildClicks() {
setupClick([url], [data], [success], [error], [$(elem)]);
setupClick([url], [data], [success], [error], [$(elem)]);
setupClick([url], [data], [success], [error], [$(elem)]);
}
//Setup clicks for each button or link
function setupClick(url, data, success, error, elem) {
elem.click(function () {
ajaxGet(url, data, success, error);
});
}
In this example I'm assuming your using a "GET" and adding a query string. You could easily adapt this to pass, a JSON formatted object for example, using a custom "POST" function. In that case [data] would be an object not a query string.
Sorry this code isn't the clearest. Let me explain it a little more. The buildClicks function would allow you to setup multiple click events on different elements by passing in the required data. I'm not sure if you are passing any data, but the above functions would allow for it. By dynamically creating the clicks you can avoid duplicating the .click code over and over. Just call the buildClicks function on document ready as such.
$(document).ready(function () { buildClicks(); });
NOTE: The success and error callbacks are functions that will be executed when your call either completes successfully or errors out. If you do not wish to use these they can be ommitted or null can be passed in. Make sure if you do pass in functions that you leave off the "()" on the end of the function name. Otherwise the functions will be executed prior to the success or failure of the ajax call. For example:
ajaxGet("http://testurl.com", null, ajaxSuccess, ajaxFailure);
ajaxSuccess() {
}
ajaxFailure() {
}
You could set an ID attributes to that buttons and a class like submit-button.
Then hang a handler on that $('.submit-button') while using an ID attribute value to define the URL to call, like that:
$('.submit-button').on('click', function(){
$action = $(this).attr('id'); //lets say the ID's value is 'delete_project'
$url = 'http://myapp.co.uk/ajax/' + $action;
// Ajax request to http://myapp.co.uk/ajax/delete_project is done
});
Anyway any web application that tends to be like a desktop one is only a bunch of JS and few HTML with some PHP behind... That is always badly maintanable...
I used [extJs][1] once for this, which led to using only jQuery and their modules while no (or just a minimum of) HTML was needed to write...
Not a copy-and-paste-solution, but maybe you find some more ideas how to build a scalable client-server application when looking for how REST APIs are built. I find REST a very good structure to keep a clear server-side API when building such apps, and i'm sure there are tutorials around how to do the corresponding client-part cleanly too.
In my application I do quite a lot of ajax calls too. I found that the easiest way to do things was to create myself a wrapper for all ajax calls such as:
var MySite = function()
{
AjaxWrapper : function(type,url,data,callback,noloading)
{
$.ajax({
type: type,
url: url,
data: data,
success:function(json)
{
if(json.status === true)
{
if(typeof callback === 'function')
{
callback(json);
} else {
// A generic success handler
}
} else {
// An error handler
}
}
});
};
}();
then you'd call it like:
MySite.AjaxWrapper("GET", "somehref", {}, function(json)
{
// json has the result of your json callback
// you could also make this a separate function
// or not have it
});
this let's you call your ajax on just about anything you want. You could then use something like data attributes, or just the standard href for anything that requires ajax and add an event to all links that pass through this function. Or, if you wanted some to do certain things just make the callback function different for those.
I'm finding this hard to explain, but this is what I've used for a couple of ajax-rich projects and it makes things so much easier!
For an example for your case you could then use something like:
$('a[class|="delete"]').on("click", function()
{
MySite.AjaxWrapper("POST", $(this).attr("href"), {param:number1}, DeleteHandler);
});
The way I would do this would be to have a single function for all actions:
$('.actions').on('click', function (e) {
e.preventDefault();
var action = $(this).data('action'),
id = $(this).data('id');
$.get('/local/handler.php', {
'action': action,
'id': id
}, function () {
// Callback stuff here
});
});
And HTML:
Delete Project
Delete User
Delete Keywork
And the PHP file should have if statements based on the action parameter that performs the requested action.
EDIT:
This way your not limited to just delete actions, so you can scale your app in the future.
Also, If the different actions become a large list (e.g. deletes of many kinds, updates, adding), I would create a separate PHP file for each action and include them in one master file. This will allow for easy scaling.
I have a php function that builds a list of items for me. Im not sure but i read that you cant call a php function explicitly though jQuery/js.
So i saw that you can still call php pages like this:
$("#name").click(function(){
$("#div").load("script.php");
});
If i can call a php page like that, is there also a way to send it a URL when that page is loaded like this?
$("#name").click(function(){
$("#div").load("script.php", 'http://gdata.youtube.com/feeds/');
});
also another problem comes up that how do i make the script accept that string through from jQuery?
normally when you call a function you pass parameter with the call like so:
<?php makeList( 'http://gdata.youtube.com/feeds/' ); ?>
//on the function-side
<?php
function makeList( $feedURL )
{
//...stuff that uses $feedURL...
}
?>
Since i will make the function a script that runs upon being called how would i pass it a parameter?
I have no idea if this is possible or not and i would understand if this creates tons of security issues which makes it not acceptable.
You have the $.get and $.post methods in jQuery.
$.post('script.php', { url: 'http://gdata.youtube.com/feeds/' }, function(data) {
//data will hold the output of your script.php
});
The url is posted to your PHP script and you can access it through $_POST['url'].
See jQuery.ajax(), the 'sending data to the server' example.