How to pass results from jQuery function to PHP - javascript

I have a list of dropdown options for a survey, and am counting their choices using jquery. The counting code works fine and has been confirmed. The trouble comes with passing the variable to PHP (from what I've read, I'll need to use the POST function but am having trouble) in order to modify the user's meta data based on the survey responses.
Here's the jquery / counting code which works fine:
$('select').change(function() {
// get all selects
var eSelects = $('select.e');
// set values count by type
var eyes = 0;
// for each select increase count
$.each(eSelects, function(i, s) {
// increase count
if($(s).val() == '1') { eyes++; }
});
// update count values summary
$('.cnteyes').text(eyes);
});
And here's the PHP which is not working (don't understand how to use the POST function, so left that out):
<?php
$response = 'cnteyes';
if ( ! add_user_meta( get_current_user_id(), 'survey', $response, true )) {
update_user_meta ( get_current_user_id(), 'survey', $response );
}
echo get_user_meta( get_current_user_id(), 'survey', true );
?>
Any help would be greatly appreciated! I'm completely stuck and do not understand how to pass jquery to PHP. Thanks for your time.

You can pass data through POST using jQuery.ajax
**JS File**
$.ajax({
url: "path/to/php/file.php",
type: "POST",
data: {
'someData': 'someData' //you pass your results here
},
datatype: "json",
success: function (result) {
}
});
**PHP File**
<?php
$someDate = $_POST['someData']; // you access your results here
?>

// update count values summary
$('.cnteyes').text(eyes);
Above Code should be changed to
// update count values summary
$('.cnteyes').val(eyes);
text() function just fills the input with the text provided but not the value. But Val() function will set the value of the input object to the provided one.
Also on the php snippet the $response should be set to $_POST['cnteyes']
<?php
$response = $_POST['cnteyes'];
if ( ! add_user_meta( get_current_user_id(), 'survey', $response, true )) {
update_user_meta ( get_current_user_id(), 'survey', $response );
}
echo get_user_meta( get_current_user_id(), 'survey', true );
?>

What you want is AJAX, which is asynchronous JavaScript and XML. The answer by #marcus-ekwall here should point you in the right direction, but the short of it is that POST and GET are ancient pre-JavaScript methods that (among other things) result in page refreshes.
Tutorials Point introduces AJAX as follows:
Conventional web application transmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.
You may want to begin by looking at their PHP and AJAX Example.

You can try this.
js code
$('select').change(function() {
// get all selects
var eSelects = $('select.e');
// set values count by type
var eyes = 0;
// for each select increase count
$.each(eSelects, function(i, s) {
// increase count
if($(s).val() == '1') { eyes++; }
});
$.post(
"result.php",
{ eye: eyes },
function(data) {
$('.cnteyes').val(eyes);
}
);
});
result.php
<?php
if( $_REQUEST["eye"] ) {
$response = $_REQUEST['eye'];
//write your code here.
}

Related

problem passing variable from HTML to JS for AJAX request in Wordpress

I have a Wordpress website page where I want to enter two values- gender and manufacturer, then display a list which shows which items match the gender and manufacturer selected.
So that the whole page is not refreshed I want to do this with an AJAX request which has to follow a particular route in Wordpress which has got me completely lost. At the moment I am having trouble even passing my two variables from the HTML page through to the JS and PHP.
For some reason the code always thinks that the user has selected Men even where Women or Junior is chosen.
My HTML
<form>
<br>
<select id="gen" name="gen">
<option value="Men">Men</option>
<option value="Women">Women</option>
<option value="Junior">Junior</option>
</select>
</form>
<div><a class="chartsearch">Search</a></div>
<div id="results">
Results go here if it works
<br>
<br>
</div>
Then my JS and PHP which is currently all contained in the functions.php file in my public_html/wp-content/themes/inspiro folder.
//Load jQuery
wp_enqueue_script('jquery');
//Define AJAX URL
function myplugin_ajaxurl() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
add_action('wp_head', 'myplugin_ajaxurl');
//The Javascript
function add_this_script_footer(){ ?>
<script>
jQuery(document).ready(function($) {
// This is the variable we are passing via AJAX
let str = document.getElementById('gen').value;
// This does the ajax request (The Call).
$( ".chartsearch" ).click(function() {
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'example_ajax_request', // This is our PHP function below
'str' : str // This is the variable we are sending via AJAX
},
success:function(data) {
// This outputs the result of the ajax request (The Callback)
$("#results").text(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
});
});
</script>
<?php }
add_action('wp_footer', 'add_this_script_footer');
//The PHP
function example_ajax_request() {
// The $_REQUEST contains all the data sent via AJAX from the Javascript call
if ( isset($_REQUEST) ) {
$str = $_REQUEST['str'];
// This bit is going to process the gender variable and display results
if ( $str = 'Men' ) {
$results = 'Mens results';
} else {
$results = 'Other results';
}
// Now let's return the result to the Javascript function (The Callback)
echo $str;
echo $results;
}
// Always die in functions echoing AJAX content
die();
}
// This bit is a special action hook that works with the WordPress AJAX functionality.
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
If you select Men and click Search it displays Men Mens Results but the same happens if you select Women. This tells me that it is getting the initial value for $str as Men but not ever changing it. So there is no point going any further with my code until it does. Once it does I can get the AJAX request to search my SQL database and show real Mens Results, Women Results, Junior Results rather than just the text.
Can anyone see what I have done wrong? I know I am a clown and a complete novice but any help would be appreciated.
It's because you st your variable at the documentReady event callback. So the var has the default value (the value at the documentReady moment).
move it in the submit event:
// This does the ajax request (The Call).
$( ".chartsearch" ).click(function() {
let str = document.getElementById('gen').value;
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'example_ajax_request', // This is our PHP function below
'str' : str // This is the variable we are sending via AJAX
},
success:function(data) {
// This outputs the result of the ajax request (The Callback)
$("#results").text(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
});
$str = 'Men' is always true, because assigning the value Men to $str won't fail.
To compare them, you should write: $str == 'Men'

ajax request is successful, but php is not running

I have a very simple jquery function that sends an Ajax call to a php file that should echo out an alert, but for the life of me, cannot get it to run. For now, I'm just trying to trigger the php to run. Here is the javascript:
function getObdDescription(){
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if($length == 5){
window.confirm($length);
$.ajax({ url: '/new.php',
data: {action: 'test'},
type: 'post',
success:function(result)//we got the response
{
alert('Successfully called');
},
error:function(exception){alert('Exception:'+exception);}
});
}
return false;
}
Here is new.php
<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
?>
I'm testing in Chrome, and have the network tab up, and can see that the call is successful, as well, I get the 'Successfully called' message that pops up, so the jquery is running, and the Ajax call is successful. I also know that the url: '/new.php is correct, because when I delete new.php from my server, I get a status "404 (Not Found)" from the console and network tab. I've even test without the conditional if($length ==... and still no luck. Of course, I know that's not the problem though, because I get the 'Successfully called' response. Any ideas?
This isnt the way it works if you need to alert the text, you should do it at the front-end in your ajax success function, follow KISS (Keep It Simple Stupid) and in the php just echo the text . that is the right way to do it.
You should do this:
function getObdDescription() {
var $code = document.getElementById("vehicle_obd_code").value;
var $length = $code.length;
if ($length == 5) {
window.confirm($length);
$.ajax({
url: '/new.php',
data: {
action: 'test'
},
type: 'post',
success: function (result) //we got the response
{
alert(result);
},
error: function (exception) {
alert('Exception:' + exception);
}
});
}
return false;
}
In your php
<?php
echo 'message successfully sent';
?>
You are exactly right Muhammad. It was not going to work the way I was expecting it. I wasn't really trying to do an Ajax call, but just to get an alert box to pop up; I just wanted confirmation that the call was working, and the PHP was running. Changing the alert('Successfully called'); to alert(result); and reading the text from the php definitely confirmed that the php was running all along.
I want to stay on topic, so will post another topic if that's what's needed, but have a follow-up question. To elaborate a bit more on what I'm trying to do, I am trying to run a function in my php file, that will in turn, update a template variable. As an example, here is one such function:
function get_vehicle_makes()
{
$sql = 'SELECT DISTINCT make FROM phpbb_vehicles
WHERE year = ' . $select_vehicle_year;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
$template->assign_block_vars('vehicle_makes', array(
'MAKE' => $row['make'],
));
}
$db->sql_freeresult($result);
}
Now, I know that this function works. I can then access this function in my Javascript with:
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
This is a block loop, and will loop through the block variable set in the php function. This work upon loading the page because the page that loads, is the new.php that I'm trying to do an Ajax call to, and all of the php runs in that file upon loading. However, I need the function to run again, to update that block variable, since it will change based on a selection change in the html. I don't know if this type of block loop is common. I'm learning about them since they are used with a forum I've installed on my site, phpBB. (I've looked in their support forums for help on this.). I think another possible solution would be to return an array, but I would like to stick to the block variable if possible for the sake of consistency.
I'm using this conditional and switch to call the function:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
//Get vehicle vars - $select_vehicle_model is used right now, but what the heck.
$select_vehicle_year = utf8_normalize_nfc(request_var('vehicle_year', '', true));
$select_vehicle_make = utf8_normalize_nfc(request_var('vehicle_make', '', true));
$select_vehicle_model = utf8_normalize_nfc(request_var('vehicle_model', '', true));
switch($action) {
case 'get_vehicle_makes' :
get_vehicle_makes();
break;
case 'get_vehicle_models' :
get_vehicle_models();
break;
// ...etc...
}
}
And this is the javascript to run the Ajax:
function updateMakes(pageLoaded) {
var yearSelect = document.getElementById("vehicle_year");
var makeSelect = document.getElementById("vehicle_make");
var modelSelect = document.getElementById("vehicle_model");
$('#vehicle_make').html('');
$.ajax({ url: '/posting.php',
data: {action: 'get_vehicle_makes'},
type: 'post',
success:function(result)//we got the response
{
alert(result);
},
error:function(exception){alert('Exception:'+exception);}
});
<!-- BEGIN vehicle_makes -->
var option = document.createElement("option");
option.text = ('{vehicle_makes.MAKE}');
makeSelect.add(option);
<!-- END vehicle_makes -->
if(pageLoaded){
makeSelect.value='{VEHICLE_MAKE}{DRAFT_VEHICLE_MAKE}';
updateModels(true);
}else{
makeSelect.selectedIndex = -1;
updateModels(false);
}
}
The javascript will run, and the ajax will be successful. It appears that the block variable is not being set.

how to fetch data from sql server database in php without refreshing the page

I am trying to get some data from the database. I create a function that is located in functions.php file that return a value. On another page, I create a variable and just get that value. I was trying to use the onkey to check the database but then I realize that i need to know the amount of tickets even if they don't type anything.
Here is the function:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$amount_of_tickets = $row['number_of_tickets'];
}
return $amount_of_tickets;
}
And, I am trying to check the database (without refreshing the page) and get the value on this page:
application.php
$amount_of_tickets = is_ticket_able($conn);
Then, I just check that $amount_of_tickets is not 0 or 1. Because if is one then some stuff have to change.
I am doing this (inside application.php):
if($amount_of_tickets !=0){
//show the form and let them apply for tickets.
//also
if($amount_of_tickets == 1){
//just let them apply for one ticket.
}
}
EDIT: I saw that AJAX would be the right one to use, but I am so confuse using it.
UPDATE:
function.php
function is_ticket_able($conn){
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
return $ticket;
}
application.php
$amount_of_tickets = is_ticket_able($conn);
<script type="text/javascript">
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
alert(global_isTicketAble);
if( global_isTicketAble == 0 ){
window.location.replace("http://www.google.com");
}
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
});
}
</script>
So, now the problem is that when I alert(global_isTicketAble); it doesn't alert the value from the database but it does alert everything that is inside application.php...Help plzzz
Server side
Assuming you need to check $amount_of_tickets periodically and this can be computed into application.php, inside that file you'll have
<?php
// $conn is defined and set somewhere
$amount_of_tickets = is_ticket_able($conn);
echo $amount_of_tickets;
exit(0);
?>
This way when the script is invoked with a simple GET request the value is returned in the response as simple text.
Client Side
ajax is the way to go if you want to update information on page without reloading it.
Below is just a simple example (using jQuery) that may be extended to fit your needs.
The code below is a JavaScript snippet. A global is used to store the value (globals should be avoided but it's just for the purpose of the example)
Then a function is invoked and the updated value is fetched from function.php script.
The function -prior termination- schedules itself (with setTimeout) to be re-invoked after a given amount of milliseconds (to repeat the fetch value process).
var global_isTicketAble = 0;
checkTicket();
function checkTicket()
{
$.ajax(
{
url: "application.php",
method: 'GET',
dataType: 'text',
async: true,
success: function( text )
{
global_isTicketAble = text;
// eventually do something here
// with the value just fetched
// (ex. update the data displayed)
setTimeout( checkTicket, 5000 ); // check every 5 sec
}
}
}
Note that $.ajax() sends the request but does not wait for the response (as async is set to true). When the request is received the function specified as success is executed.
Complete jQuery ajax function documentation can be found here
http://api.jquery.com/jquery.ajax/
I assume that you have a page (application.php) that displays a table somewhere.
And that you wish to fill that table with the data found in you database.
I'm not sure about WHEN you want these data to be refreshed.
On button click or periodically (like ervery 5 seconds)... But it doesn't matter for what I explain below.
In application.php:
Assemble all your page as you already know how.
But inside it, somewere, just insert an empty div where your table should show:
<div id="dynamicContent"></div>
Also add this script at the bottom of the page:
<script>
function getData(){
PostData="";
$.ajax({
type: "POST",
url: "function.php",
data: PostData,
cache: true,
success: function(html){
$(Destination).html(html);
}
});
}
getData(); // Trigger it on first page load !
</script>
There is 2 variables here... I named it "PostData" and "Destination".
About PostData:
You can pass data collected on the client side to your PHP function if needed.
Suppose you'd need to pass your user's first and last name, You'd define PostData like this:
Fname=$("#Fname").val(); // user inputs
Lname=$("#Lname").val();
PostData="Fname="+Fname+"&Lname="+Lname;
In your function.php, you will retreive it like this (like any normal POST data):
$Fname=$_POST['Fname'];
$Lname=$_POST['Lname'];
If you do not need to pass data from your client side script to you server side PHP... Just define it empty.
PostData="";
Then, about Destination:
This is the place for the empty "dynamic div" id ( I named it "dynamicContent" above).
Don't forget about the hashtag (#) for an id or the dot for a class.
This is a jQuery selector.
So here, PostData would be defined like this:
Destination="#dynamicContent";
The result of the ajax request will land into that "dynamic div".
This WILL be the result of what's defined in function.php..
So, if you follow me, you have to build your table in function.php...
I mean the part where you do your database query and your while fetch.
echo "<table>";
echo "<tr><th>column title 1</th><th>column title 2</th></tr>"
while ($row = sqlsrv_fetch_array($stmt)){
echo "<tr><td>" . $row['data1'] . "</td><td>" . $row['data2'] . "</td></tr>";
}
echo "</table>";
So if you have no data, the table will be empty.
You'll only get the table and table headers... But no row.
There is then no need for a function that checks if there is data or not.
Finally... About the trigger to refresh:
In application.php, you may place a button that fires getData()... Or you may define a setInterval.
It's up to you.
This is how I use ajax to refresh part of a page without reloading it completly.
Since ajax is new to you, I hope this answer will help.
;)
------------------------
EDIT based on Ariel's comment (2016-05-01)
Okay, I understand! Try this:
In application.php:
<div id="dynamicDiv"></div>
<script type="text/javascript">
// timer to trigger the function every seconds
var checkInterval = setInterval(function(){
checkTicket();
},1000);
function checkTicket(){
$.ajax({
type: "POST",
url: "function.php",
data: "",
cache: true,
success: function(html){
$("#dynamicDiv").html(html);
}
});
}
function noMoreTikets(){
clearInterval(checkInterval);
window.location.replace("http://www.google.com");
}
</script>
In function.php:
// Remove the "function is_ticket_able($conn){" function wrapper.
// Define $conn... Or include the file where it is defined.
// I assume that your query lookup works.
$query = "select number_of_tickets from [dbo].[TICKETS_LKUP] " ;
$stmt = sqlsrv_query($conn, $query);
while ($row = sqlsrv_fetch_array($stmt)) {
$ticket = $row['number_of_tickets'];
}
// Add this instead of a return.
if($ticket>0){
echo "There is still some tickets!"; // Text that will show in "dynamicDiv"
}else{
?>
<script>
$(document).ready(function(){
noMoreTikets();
});
</script>
<?php
}
Remember that your PHP scripts are executed server-side.
That is why your "return $ticket;" wasn't doing anything.
In this ajax way to call function.php, its script is executed alone, like a single page, without any relation with application.php, which was executed long ago.
It produces text (or javascript) to be served to the client.
If you want to pass a PHP variable to the client-side javascript, you have to echo it as javascript.
So here, if the PHP variable $ticket is more than zero, some text saying that there is still tickets available will show in "dynamicDiv" and the application page will not be refreshed. I suppose it shows a button or something that allows students to get a ticket.
Else, it will be the javascript trigger to "noMoreTikets()" that will land in the "dynamicDiv".

checking instantly php arrays using jquery / ajax

I want to be able to check whether values exist in the php array without having to click the submit button to do those checks using jquery/ajax.
when users enter an abbreviation in the text field want to be able to show that the brand exists (either vw or tyta) or not (as they type in the input box) and show the results in the carnamestatus div.
I was following a tutorial from youtube, however it queried against a mysql database.
I was wondering if this is possible using php arrays instead of mysql? I would be grateful if you could pick any faults in the code.
the code is as follows:
<?php
$car = array()
$car["vw"] = array( "name" => "volkswagen");
$car["tyta"] = array( "name => "toyota");
?>
the html code is as follows:
<label for="carname">Car Code:</label> <input type="text" onblur="checkcar()" value="" id="carname" />
<div id="carnamestatus"></div>
the checkcar()
function checkcar(){
var u = _("carname").value;
if(u != ""){
_("carname").innerHTML = 'checking ...';
var B = new XMLHttpRequest();
B.open("POST","check.php",true); /
B.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
B.onreadystatechange = function() {
if(B.readyState==4 && B.status== 200) {
_("carnamestatus").innerHTML = B.responseText;
}
}
var v = "carnamecheck="+u;
B.send(v);
}
}
</script>
Use Javascript keyboard event and then, send the value of the input into your php function.
For example:
$("#youInput").keyup(
function() {
$.ajax(
{
type: "post",
url: "your_url.php",
data: {params: $(this).val()},
success: function(data) {
console.log(data)
}
}
);
}
);
And in you php code, just retrieve the params value, $_POST['params']
Explain
When you press the keybord, your retrieve the value of the input ( here, it is $(this).val() where this represents #yourInput ), then you send the value via ajax (Here we use post type) with your url and the different params that you will send to the server side. If you post the value with $_POST['params'] you will get the value entered in the input. And if it's success, the callback function will retrieve the data returned by your server side.
Here, we just use, jQuery.ajax but you can find more about ajax here or here. Using library make it easy to work with.
Hope it helps you!

Ajax driven content using CodeIgniter

I'm making an web that is a single-page website interacting with the server through Ajax in CodeIgniter. The general coding is of the following type:
controller (user.php):
public function get_user_content() {
$id = $this->input->post('id');
$hits = $this->user_model->user_data($id);
$s = '';
foreach ($hits as $hit) {
$s .= $hit->name;
$s .= $hit->age;
}
echo $s;
}
model(user_model.php):
function user_data($id) {
//do sql operation
return $query->result();
}
view:
...
...
Click here for user details
...
...
javascript:
('.user-data').click(get_user_data);
....
....
function get_user_data(response) {
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/get_user_content",
data: { id: this.id },
success: function(response) {
$("#somediv").append(response);
$(".someclass").click(another_function);
},
error: function(error) {
alert("Error");
}
});
}
So, looking at the above javascript, there are separate functions for all actions that send some data to the server and the particular html content is updated via Ajax.
I had the following questions (I'm just new to this stuff):
1. Is there any better way of doing ajax in javascript than my implementation.
2. I'm not using the concept of views in CodeIgniter. I just `echo` results through my controller functions that gets embedded in javascript. This is because I want dynamic update in my app. It is a single page and there is no concept of new-page/new-tab. Is there any better way?
I'm not aware of any open-source projects that might make it easier/more optimized.
For making code more simplified, readable & with great coding standard answer will be yes for both to improve your javascript code & way you are getting a response from the Ajax call.
Improve Javascript :
You might have one common js included in you header portion, if not create & include one. This common jar contains only common functions throughout the application. Create one function with the name may be like sendAjaxRequest() in that common.js. This function will have some parameters like divId (refresh div id), url(post url), options(array of options) & function will look like this:
function sendAjaxRequest(strDivId, strRequestUrl, options) {
options = options || {};
var defaultOptions = {url: strRequestUrl, type: 'POST', beforeSend: function(request,options){showLoadingImage(strDivId);}, success: function(html){$('#'+strDivId).html(html); removeLoadingImage(strDivId); }};
options = $.extend({},defaultOptions,options);
$.ajax(options);
}
Call this function from where ever required on application.
like
('.user-data').click( function() { sendAjaxRequest('somediv', url,{data: { id: this.id }}) });
Benefit : This method is very useful in the future when you want to keep google analytics on ajax call also or want to track your ajax calls. It is always good to have common functions.
Resposnse from ajax call: You can load views in Controller->function in case of ajax call also, nothing need to change or configure for this. Use of this way is always good practice to maintain standardness & readablity in the code.
Note : Here in this case you might worry about using a second action on load of your first Ajax call, for this standard way is to write second action on load of view of that particular Ajax call view (Write second click code in that particular view only) like
('.someclass').click( function() { sendAjaxRequest('someOtherDiv', otherUrl,{data: { id: this.id }}) });
In short at the end user divide & conquer rule (Divide an html page into blocks & create the huge page) to create good applications. Its really fantastic way, as I am using this way in my codings overall.
1- There is other ways to do ajax calls , being better or not is based on your needs, This post clears this point
2- your way is good, still you could use some enhancements to your functions to be a complete web-services same as handling errors - in case - and to return the output data as json allowing you to control it from your JavaScript function for a better handling & representation.
3- from what i understood you're getting data for single user each time ,in this case using $query->row() would be make your life easier extracting the data than using $query->result() , but in case you are getting multiple records you could loop it withing your JavaScript function.
here's another approach to your example with little enhancements that might be helpful :
controller (user.php):
public function get_user_content($id) {
$output -> hit = $this -> user_model -> user_data($id);
if (!$output -> hit) {
$output -> msg = "NORECORDS";
} else {
$output -> msg = "SUCCESS";
}
echo json_encode($output);
}
model(user_model.php):
function user_data($id) {
//do sql operation
return $query -> row();
}
JavaScript :
function get_user_data(response) {
$.get("<?php echo base_url();?>index.php/user/get_user_content/" + this.id, function(data) {
if (data.msg != 'SUCCESS') {
alert(data.msg);
return;
}
var hit = data.hit;
$("#somediv").append("Name: " + hit.name + "Age: " + hit.age);
$(".someclass").click(another_function);
}, "json");
}
First Answer:
The ajax request seems fine, you can add dataType option also to expect particular type of response,
As you are using post you can use jquery.post as an alternative
Example
$.post( "<?php echo base_url();?>index.php/user/get_user_content", function(data) {
alert( "success" );
}, 'html') // here specify the datatype
.fail(function() {
alert( "error" );
})
You can also use done callback instead of success
Second answer:
Controller
public function get_user_content() {
$id = $this->input->post('id');
$hits = $this->user_model->user_data($id);
$user_array = array();
foreach ($hits as $hit) {
$temp_array = array();
$temp_array = array('name' => $hit->name);
$temp_array = array('age' => $hit->age);
$user_array = array($temp_array);
}
$this->load->view('user', $user_array);
}
Modal
Remains the same
View (user.php)
example say user.php
<?php
echo "<div class='somediv'>";
if (sizeof($user_array)) {
for ($row = 0; $row < sizeof($user_array); $row++ ) {
echo "User Details: Name - " . $user_array[$row]['name'] . ", Age - " . $user_array[$row]['age'];
echo "<br/>";
}
} else {
Click here for user details
}
echo "</div>";
?>
Javascript
$('.user-data').on('click' function () { // better to use event delegation as content is loaded dynamically
get_user_data();
});
function get_user_data() {
$.post( "<?php echo base_url();?>index.php/user/get_user_content", function(data) {
alert( "success" );
$("#somediv").append(data);
$(".someclass").click(another_function);
}, 'html') // here specify the datatype
.fail(function() {
alert( "error" );
});
}
Reference
stackoverflow.com/questions/18471627/codeigniter-load-a-view-using-post-and-ajax

Categories

Resources