I am using codeigniter. When I update database values using website UI, it gets updated in database but on user interface it shows old values only. After refreshing page it shows updated values.
Please suggest solution on the same.
Thanks.
You need to use AJAX. Something like this:
data = {"slug" : slug};
$.ajax({
url: '', //url of controller where you would update the code using model
method: 'POST', //method
data: data, //data to be updated
dataType: 'json',
contentType: 'json'
})
.done(function(res){ //Upadte html; Note the data in 'res' variable is the data which your above 'url' would echo
})
.fail(function(res){//handle here if error occured
});
Hope this is a good starting point for you to learn AJAX. I would have helped you more if you provide us with some code.
Related
I'm not the best to explain problems but i'll try my best.
So i'm developping a website with php and javascript and bootstrap.
I got a list of equipment that i want to be able to edit with a modal form.
What i'm doing is that i write the id of the equipment (from mysql) into the id of the picture that i'm supposed to click to edit the equipment.
Like this
When i'm clicking on it it goes to a JS page that execute an ajax request to get all the infos from the database.
Now the main problem: when i transfer the id with the ajax request (with $_POST) and i var_dump it to see if i really have it it shows like that: Array ( [1] => )
The number is actually the ID but i have no idea how to use it as a string to get my infos.
If I get you right, your question is "How can I fix the ajax request to process it in PHP?"
Without seeing the specific code-part that you need help with, it's difficult to tell what exactly needs to be changed.
From your description, I assume that your Ajax request in JS looks like this
// your code is either this:
jQuery.post( 'https://example.org?' + id );
// or this:
jQuery.post( 'https://example.org', id );
This will give you the URL https://example.org?1, which is equal to the URL https://example.org?1= (i.e., param "1" is an empty string)
You need to give the ID a param name. Like this:
// This will work (add the string before the parameter value "id=")
jQuery.post( 'https://example.org?item=' + id );
// This is even better - set the post data as object:
jQuery.post( 'https://example.org', { 'item': id } );
In PHP you can then access the product id via $_POST['item'].
Of course, you can use any other param instead of "item" and even pass multiple values inside the post object.
Update based on new comment
The problem is, that you only pass the ID to the post-request, without assigning a name to it: data: id
Change this to data: {item: id} and you have $_POST['item'] in PHP. Here's the full code:
$.ajax({
url: "getInfos.php",
type: "POST",
data: {item: id}, // <-- change this line!
success:function(response){
$('#bodyEdit').html(response);
$('#myModalEdit').modal('show');
},
error:function (resultat, statut, erreur){
console.log(resultat, statut, erreur );
}
})
EDIT: the answer above works better, it seems i've got more than one problem for this issue and the answer above helped me correct it for good
thanks to everyone that answers my question,
i found out about the problem.
First i was the ajax function built in jquery:
$.ajax({
url: "getInfos.php",
type: "POST",
data: {item: id}, // <-- change this line! credit to Philipp
success:function(response){
$('#bodyEdit').html(response);
$('#myModalEdit').modal('show');
},
error:function (resultat, statut, erreur){
console.log(resultat, statut, erreur );
}
});
I was sending the id with data: but the value was missing .serialize after it, wich adapt the value to the url query if i understood correctly.
working code:
$.ajax({
url: "getInfos.php",
type: "POST",
data: id.serialize(),
success:function(response){
$('#bodyEdit').html(response);
$('#myModalEdit').modal('show');
},
error:function (resultat, statut, erreur){
console.log(resultat, statut, erreur );
}
});
I have an Opencart website, I am currently trying to use ajax at the frontend to pass data to php controller in the backend, but I am unable to get the value from the request in backend
here is the frontend ajax code:
$.ajax({ url: 'index.php?route=checkout/cart/addAll',
type: 'post',
data: 'product_list= test' ,
dataType: 'json',
success: function(json) {});
at the backend controller, I am trying to retrieve variable "product_list" but it is not working
$products = $this->request->post['product_list'];
$logger->write("products to add to cart is"+ strval($products));
the last statement keeps printing 0 to the log file
any help with this ? what is wrong here?
I also tried
$products = json_decode($this->request->post['product_list'], true);
with same results
Ok, fixed, Ajax was not the issue, it was accessing the variable from server side, so I used $_POST
instead of $this->request->post and it is working fine
So I just did this
in file catalog/view/theme/defaulttemplate/common/home.twig I add this code at the end of the file
$(document).ready(function() {
$.ajax({url:'index.php?route=checkout/cart/addAll',
type: 'post',
data: 'product_list= test' ,
dataType: 'json',
success: function(json) {}
});
});
and in file catalog/controller/checkout/cart.php on line 479 I add this
public function addAll(){
print_r($this->request->post);
}
And I see this in my console http://joxi.ru/krDlvPdfKGejar
All I did was correct your js code. hope this helps.
I saw a form to load data from database, i decode all form ajax code but when i see a new thing inside the form. i don't know what it's mean. Please My Image for more details.
The code something look like that.
$.ajax({
dataType: "json",
type: "POST",
url: "/user/setting/template-action",
data: {
_act: "load",
_tname: tempname,
_json : $.now() //Here i don't know what is the use of $.now() and how post and verify same value into my php code HOW...!
}
});
$.now() how to verify same value into php code
Image is here
as per Jquery's documentation $.now is a integer containing the unix timestamp.
http://api.jquery.com/jquery.now/
in php this value is represent with time();
When I send serialised data to a PHP file using ajax, it is sometimes URL Encoded depending on how i do it.
Originally i had the following code which worked fine:
$.ajax({
type: 'POST',
url: 'ajax-process.php',
data: $("#sitestructure-form").serialize(),
success: function(d){$("#structureupdate").html(d);}
});
The data was sent to my PHP file and i could echo it and it looked like this.
[{"id":20,"children":[{"id":21}]},{"id":19},{"id":18,"children":[{"id":14}]},{"id":16},{"id":13,"children":[{"id":11}]},{"id":17},{"id":15},{"id":12}]
I wanted to send more than one piece of data, I called the serialized data 'order' and added 'process' to it so i updated my code to the following:
$.ajax({
type: 'POST',
url: 'ajax-process.php',
data: {
order: $("#sitestructure-form").serialize(),
process: "sitemap-reordernavigation"
},
success: function(d){$("#structureupdate").html(d);}
});
However when I retrieve the serialised data sent in 'order' the output looks like this:
data=%5B%7B%22id%22%3A20%2C%22children%22%3A%5B%7B%22id%22%3A21%7D%5D%7D%2C%7B%22id%22%3A19%7D%2C%7B%22id%22%3A18%2C%22children%22%3A%5B%7B%22id%22%3A14%7D%5D%7D%2C%7B%22id%22%3A16%7D%2C%7B%22id%22%3A13%2C%22children%22%3A%5B%7B%22id%22%3A11%7D%5D%7D%2C%7B%22id%22%3A17%7D%2C%7B%22id%22%3A15%7D%2C%7B%22id%22%3A12%7D%5D
The only way i can think of to fix this problem is to use php to urldecode it and then use str_replace to remove the 'data=' bit at the front, like so.
$data = str_replace("data=","",urldecode($_POST['order']));
How can I get this to work with AJAX though so i dont have to urldecode it?
Ive tried using a variable and setting the processData to false however that didn't seem to work.
var order = $("#sitestructure-form").serialize();
$.ajax({
type: 'POST',
url: 'ajax-process.php',
processData: false,
data: {
order: order,
process: "sitemap-reordernavigation"
},
success: function(d){$("#structureupdate").html(d);}
});
My knowledge of AJAX/Jquery is rather limited so any help would be greatly appreciated.
That's because you are feeding a serialized text string to the data attribute the first time around and jQuery does not convert it to a serialized string. The second you are assigning an object to the data attribute with the "order" attribute having the serialized text string, so jQuery basically double encodes it. For it to act as you'd like you would have to convert the form to an object and assign your "order" attribute to that object. See this post: Convert form data to JavaScript object with jQuery
// taking the example from the above link, you do this instead
order = $("#sitestructure-form"). serializeObject();
Fixed by doing the following:
$.ajax({
type: 'POST',
url: 'ajax-process.php?',
data: $("#sitestructure-form").serialize() + "&action=sitemap-reordernavigation",
success: function(d){$("#structureupdate").html(d);}
});
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.