I am new to php and am trying to update a hidden field value inside a php function and can't see to find a solution that works.
In template.php I have:
<input type="hidden" id="variable_ID" name="variable_name" value="variable_value">
This works fine.
However I need to update the value of the variable to the record ID of inserted record in a function in functions.php eg
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
// *** Set Hidden field value to $get_record_id here ***
}
I have tried a myriad of things but can't seem to find a solution.
Any pointers on how to solve this problem?
Here is the solution I used - thanks to #Steven and #El_Vanja for direction.
(I may need to change the question title now though because what I actually needed to do was return a variable to javascript from PHP using Ajax. I didn't need to use hidden fields).
PHP
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
echo json_encode($get_record_id);
exit;
}
JS
jQuery.ajax({
url: ajax_url,
type:'POST',
data: {
action: "myFunction",
anydata:"to be posted"},
success: process_record_ID
});
function process_record_ID(data_returned_from_myFunction){
recordID = data_returned_from_myFunction;
}
Hope this helps others!
Notes
I believe that we have to declare 'process_record_ID' as a separate function outside of AJAX because AJAX is asynchronous. If we define the function in the success handler, the function runs in AJAX before the value is actually returned from PHP.
In the AJAX success handler, we don't need to explicitly list the 'data_returned_from_myFunction' variable in the call to process_record_ID function. When the data is returned to the AJAX success handler from PHP, it still gets sent to the function.
Additional answer
You're correct AJAX is an asynchronous construct which means that certain tasks can be carried out before you might expect them to (from a synchronous perspective).
For example we can (as per the code in the original answer) use jQuery to update the value of a field directly in the success handler.
We can't update a JS variable directly, i.e:
some_variable = response.value;
If you attempt it the variable some_variable will likely be undefined.
The difference comes down to callbacks:
Callbacks allow the asynchronous function to call a function after it completes. Where as setting a variable happens on the spot.
There are two easy ways to solve this issue then:
Create a function outside of the AJAX request and allow it to callback that function once the AJAX request has completed -- as you've already discovered.
Use the complete option inside of your AJAX request.
Using a call back
Firstly we need to define out variable to be updated and the function which we will use to update it:
var inserted_id = "";
function update_id(data){
inserted_id = data.record_id;
}
Then we can make out AJAX call:
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : update_id
});
N.B.
Calling update_id in this fashion means we pass the entirety of the returned JSON object; not just the returned number.
Alternatively...
var inserted_id = "";
function update_id(data){
inserted_id = data;
}
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response){
update_id(response.record_id);
}
});
This method is effectively the same but we only pass the returned number to the update_id function.
Using complete
complete works the same way as success however activates once the AJAX request is... complete...
var inserted_id = "";
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
complete: function(data) {
inserted_id = data.responseJSON.record_id;
}
});
Original answer
Having not seen the rest of your code giving a complete answer is tricky. However, this should set you on the right track:
PHP
Firstly, in your PHP you need to make sure and output the data that you want returned to the webpage. In this case we want to return the insert id of the newly created record; to do this we're going to output a JSON object so that the AJAX call can interpret the value and update the page:
function myFunction() {
$mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
echo json_encode(["record_id" => $mydb->insert_id]);
exit;
}
N.B.
We don't want any output other than the JSON string. Hence exit has been used after the echo. You may want/need to adjust the echo and exit to fit with the rest of your code etc.
JS
Now that we have our PHP returning usable data to our ajax call (which should look something like the below) we can take the returned data aka response and update the value of the hidden field accordingly.
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response) {
$("#id_of_hidden_field").val(response.record_id);
}
});
Related
I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing
Hey guys I am building an application in which I send input value from a text box via AJAX to a controller function and then return what I send back to the user (I am developing an instant search, this is a first step).
The AJAX links to the method fine however I am having problems returning the information. I receive no error messages, the problem is that the return string is BLANK.
I receive [you wrote ] rather than [you wrote WHATEVER I IN PUTTED ]
Any help greatly appreciated.
view_index.php
function search(){
var term = document.getElementById("mainsearch").value;
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: term,
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
controller_site.php
function search(){
$gotcha = $this->input->post('term');
return $gotcha;
}
The data: parameter accept a key : value json to pass to the POST, as the json array key will be your $_POST key
Try with this:
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/site/search/')?>",
data: {'term': term }
cache: false,
success: function(html){
alert("you wrote " + html);
}
});
You didn't send your data correctly, so PHP has nothing to process, and you end up sending back nothing:
data: term,
POST/GET requests MUST be in key=value format, and you're sending only the value portion. Try
data: {foo: term},
and then
$gotcha = $this->input->post('foo');
You need to change return to echo as AJAX response works on whatever echo from called function.
So, you can code like :
function search(){
$gotcha = $this->input->post('term');
echo $gotcha;
}
or
function search(){
echo = $this->input->post('term');
}
The responseText property returns the response as a string, and you can use it accordingly
It is generally a bad idea to return HTML from your controllers. Instead try to just manage data server-side wise and do all the frontend on the client side.
Now, for the error:
The success callback takes 3 parameters
You need to pass key-value pair in the data argument of the .ajax call
Make sure you handle errors on your controller appropriately because if something goes wrong you'll get an html document as a response from CodeIgniter and you'll spend a lot of time debugging javascript to find out that the error was actually server-side
1 the callback:
Your success callback function should look like this:
function (data, status, response) {
}
Where:
data is whatever you are echoing from your controller's method. You'll probably want JSON.
status Will tell you if the HTTP response message (e.g. "Not Found" is the status for a 404 code, "success" for a 200 code)
response is the jquery wrapped XmlHttpRequest object that gives you a handful information of the transaction, for example response.responseText would give you whatever you outputed from PHP, response.responseJSON would give you a JSON object if you echoed a json encoded object, etc.
Why should you care? Because those extra parameters will let you decide if something went wrong on your backend so you can handle the situation client-side not leaving the user wondering if you app just don't work. Worse, giving the infamous red cross on the status bar of the browser.
If you set the dataType parameter of the jQuery.ajax function then you can explicitly tell jQuery what kind of data you are expecting to be retrieved from the server on data parameter from your callback.
2 the sent data
As said, you need to either pass value-pairs or a URL encoded string. If you intend to use GET then you can pass the URL encoded string, but that means you have to have arguments on your CI function like:
function search($term)
And then CI automatically routes the incoming parameters. But since you want to do POST then you'll want to effectively get the values with $this->input->post("name")
If you have your input inside a form, or several fields that you need to send, then its easier to just serialize the form:
$.ajax("url", {
type : 'POST',
data : $('#form').serialize(),
dataType : 'json',
success : function(data, status, response) {} error : function(response, status error) {}});
3 handle errors
If you are relying on AJAX then make sure that you return some sort of error or warning so you can catch it client side:
function search() {
$term = $this->input->post("term")
if($term == FALSE) {
//return a 404 so that you can catch .error on jquery
} else {
echo $term;
}
}
Do a research on RESTFul apps. It'll help you a lot understanding that. this is a good starting point and although your question was not exactly related to this, it is a good practice to have separate layers on your application so that you just consume data from your backend, handle situations and then just react accordingly on the frontend, that is, you just use javascript to either send, receive and list data. If you are using CI or any other MVC framework then you should not really be generating HTML on your controllers, thats what the views are for.
Basically I have two sliders on my page, whenever their value is adjusted they reference a script which returns a JSON array holding values about products which meet the new criteria.
In my success callback I want to call my PHP class which renders my view to the screen ( I am aware that I could probably achieve this effect in Javascript, but I already have a PHP class built which handles all of the required logic, so it would be simpler if there was a shortcut.
My AJAX method looks like this:
function update_results(values)
{
var json = JSON.stringify(values);
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?cache=" + (new Date().getTime()),
data: { query : json },
cache: false,
success: function(data) {
// Remove the old data from the document
$('tr').remove();
// Build the new table rows using the returned data array
$('table').append("<?php Table t = new Table(data); ?>");
}
});
}
Calling my Table constructor builds everything I need just by passing the JSON array I recieve back from my AJAX call, however nothing is being rendered to the screen at the moment - is there any way of doing this?
PHP runs on the server...JavaScript on the client... "<?php Table t = new Table(data); ?>"
does not magically work with the Ajax call. The server should be returning the table when you make the Ajax call.
I have a link, delete, that removes an item from an array, and then removes a row from a table on my html page.
It runs the ajax request first to amend the array, then removes the row. If for some reason the ajax request was to fail then the html table row would still be deleted I think.
Is there a way to make sure subsequent code afer the ajax request only runs if it is successful? I tried moving it into the success function but then it didn't run at all..
This is how I have it set up at the moment...
$(document).ready(function () { //delete
$(document).on("click", "a[class='del']", function () {
var ID = $(this).attr("id"); //<----- get the ID of the column
$.ajax({
//contentType: "text",
url: 'proDel.php', //the url you are sending datas to which will again send the result
type: 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data: 'val1=' + ID, //Data you are sending
success: function (data) {
// do nothing, array was amended in php file
}
})
//Code here that deletes the table row(runs whether the array was changed or not!!
})
})
The problem might be that you are not returning valid JSON.
You were correct in thinking that you should move the code that deletes the table row into the success callback. You say you tried that, but the success callback was not executed.
Since you specify dataType: 'json', jQuery will attempt to parse the response body into a JavaScript object (or array or null). If the response body cannot be parsed (because it is not valid JSON), jQuery will call the error callback, rather than the success callback.
An empty response body is not valid JSON. You must at least return "null". Or if you do not plan on returning any data, just change to dataType: 'text'.
Move the code that deletes row to success callback.
$.ajax({
//contentType: "text",
url : 'proDel.php', //the url you are sending datas to which will again send the result
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// Code here that deletes the table row
}
});
Try you ajax with success parameter as well as an error to see if there is a problem, hope this helps..
$(document).ready(function (){
$(document).on("click", "a[class='del']", function(){
var elem = $(this); //to make $(this) accessible in you success callback
var ID= elem.attr("id"); // get ID of the column
$.ajax({
url : 'proDel.php', //the url you are sending datas to
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// success, Code here that deletes the table row , do something with 'elem'
},
error: function(x,e) {
//log error if any
console.log("failed with: "+x.status+", e="+e+", response="+x.responseText);
}
});
});
});
Since jQuery 1.5 you may use chainable methods of object returning by jQuery.ajax(). In your case (ensure executing code on ajax request completion) you have to use deferred.always() method. Somehow like this:
$.ajax({
...
})
.always({
//Code here that deletes the table row
})
In earlier jQuery versions you have to use complete option (handler) in jQuery.ajax() for your purpose.
First thing is that when looking at the ajax request success does not mean that the request returned a correct/true value. That just means that there was a response from the other end.
That tripped me up during my first couple times working with and debugging ajax calls.
I don't know if that's part of what is not working for you here, but something to consider.
Secondly, and to answer your real question, you'll have to put a function call in the success branch, else it might never get called, or be called at a non-deterministic time (the whole nature of an asynchronous call).
var a = function(){
$.ajax({
success : function (){
// code here fires if there is a response to your ajax request
// you should put in an function callback here to check the response for
// your success conditions.
// if your conditions are met, make the changes that you need to
b();
}
failure: function() {
// code here fires if the ajax request receives no response
}
})
// any code here will fire immediately after the ajax call is fired.
// it will not wait for the ajax response.
}
var b = function(){
// stuff you want to do according to the ajax response parameters
}
Could someone point me in the right direction here?
Basically, I've got this jQuery code snippet:
$('.bggallery_images').click(function () {
var newBG = "url('" + $(this).attr('src');
var fullpath = $(this).attr('src');
var filename = fullpath.replace('img/Bakgrunner/', '');
$('#wrapper').css('background-image', newBG);
// Lagre til SQL
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: filename,
dataType: 'Text',
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
});
This is being run when I click a certain button. So it's actually within a click handler.
If I understand this correctly, this snippet takes the source if the image I just clicked and strips it so I end up with only the filename. If I do an alert(filename), I get the filename only. So this is working ok.
But then, it does an ajax call to a php file called "save_to_db.php" and sends data: filename. This is correct right? Then, it does a callback which does an alert + data.
Does this seem correct so far?
Cause my php file looks like this:
<?php
require("dbconnect2.php");
$uploadstring = $_POST['filename'];
$sessionid = $_SESSION['id'];
echo ($sessionid);
mysql_query("UPDATE brukere SET brukerBakgrunn = '$uploadstring' WHERE brukerID=" .$_SESSION['id']);
mysql_close();
?>
When I click the image, the jQuery snippet fires and I get the results of this php file as output for the alert box. I think that the variables somehow are empty.
Because notice the echo($sessionid); which is a variable I've created just to test what the session ID is. And it returns nothing. What could be the issue here?
Edit: I just tried to echo out the $uploadstring variable as well and it also returns nothing. It's like the jQuery snippet doesn't even pass the variable on to the php file?
You're trying to send just the filename, but you're retrieving a named form field in your PHP code. So you need to send a named form field:
Change your ajax call like this:
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: {filename: filename}, // <= Change #1 (give jQuery a simple object)
dataType: 'text', // <= Change #2 ('text', not 'Text')
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
Your PHP script will now receive a POST varible called filename whose value comes from your filename Javascript variable. (You can also use $.post to do this, but it's just a wrapper for ajax anyway...)
Passing a simple object into the ajax call is the easiest way to send fields to the server. jQuery will take the object and create the URL-encoded form data (doing all of the escaping for you) by using the object's keys and field names. So for instance, if you give it this object:
data: {a: 1, b: "testing one two three", c: 3}
...it sends this URL-encoded data:
a=1&b=testing+one+two+three&c=3
(Note how it encodes it for us.) More in the ajax docs (but beware, at present what the docs say about array handling is wrong; see this bug report for details).