Passing values from jQuery to PHP in same page instantly - javascript

I have written a PHP program to confirm deletion of data through jQuery confirm message (Refer: http://rathur.fr/jQuery/MsgBox/) and record the result back to the same page itself instantly. If the page refreshes, it'll return back its state to previous.
The part of line is below:
print "
<script type='text/javascript'>
$(document).ready(function(){
$.msgbox('<br/>Are you sure you want to delete the selected record from the database?', {
type : 'confirm'
}, function(result){
$('#output').text(result);
var output = result;
});
});
</script>";
I want to get the result of the action button to PHP variable instantly, like below (just a trial):
$x = $_SESSION['output']; OR
$x = $_POST['output']; OR
$x = print "<div id=\"output\"></div>"; OR
$x = some_function(output);
Please help me, or suggest if there is other better options.

Here is a simple Ajax call to a Php File by an event : Click on a button.
Javascript client side :
$("body").on("click", "#mybutton", function() {
var mydata = $("#form").serialize();
$.ajax({
type: "POST",
url: "/api/api.php",
data: {data : mydata},
timeout: 6e3,
error: function(a, b) {
if ("timeout" == b) $("#err-timedout").slideDown("slow"); else {
$("#err-state").slideDown("slow");
$("#err-state").html("An error occurred: " + b);
}
},
success: function(a) {
var e = $.parseJSON(a);
if (true == e["success"]) {
$("#action").html(e['message']);
// here is what you want, callback Php response content in Html DOM
}
}
});
return false;
});
Next in your Php code simply do after any success function :
if ($result) {
echo json_encode(array(
'success' => true,
'msg' => "Nice CallBack by Php sent to client Side by Ajax Call"
));
}

You should use jQuery to POST the data to a PHP script using AJAX if you want to use the second pass.
http://api.jquery.com/category/ajax/ has many functions and tutorials on writing AJAX functions and handling return data. In particular, look at the post() function.

Related

How can we apply both JavaScript and PHP to a button?

When I click a button:
I need the JavaScript to perform some function.
Also run PHP code as well.
How can we achieve this?
PHP is only run by the server and responds to requests like clicking on a link/button (GET) or submitting a form (POST).
HTML & JavaScript is only run in someone's browser.
<html>
<?php
function PhpFunction() {
echo 'A php function';
}
if (isset($_GET['JsFunction'])) {
PhpFunction();
}
?>
Hello there!
<a href='index.php?JsFunction=true'>Run PHP Function On Click Of This Link</a>
</html>
Alternatively ,
You can create a ajax request to run a php code in your server..
Ajax can help you to send an asynchronous request to the server that php (or other) can catch, in this way you can implement and play with some callback functions
$.ajax({
url : "yourScript.php", // the resource where youre request will go throw
type : "POST", // HTTP verb
data : { action: 'myActionToGetHits', param2 : myVar2 },
dataType: "json",
success : function (response) {
//in your case, you should return from the php method some fomated data that you //need throw the data var object in param
data = toJson(response) // optional
//heres your code
},
error : //some code,
complete : //...
});
in your php script, you'll receive the request posted throw the superglobal vars like POST (for this example)
<?php
$action = (string)$_POST['action']; //this is unsecure, its just for the example
if("myActionToGetHits" == $action) {
//here you have to call your php function and so on..
$data = hitsMonth();
echo $data;
exit;
}
here is html
<a href="#" onclick="javascript:functionName(arg1, arg2);">
This is a basic example to do it, there are lots of ways to do.
Have javascript do the submit:
function button1() {
// js code here
var formelt = document.getElementById("form1");
formelt.submit(); // this will submit the form to server
}
Example =>
<button class="btn-test">Btn Test</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
jQuery('.btn-test').click(function() {
js_do_something();
php_do_something();
});
function js_do_something() {
console.log('something done from js');
}
function php_do_something() {
console.log('something done from php');
jQuery.ajax({
type: "POST",
url: 'you_php_file.php',
data: {param: 'btn-test-click'},
success: function () {
console.log('success');
}
});
}
</script>
There you have how to execute a php function with on Onclick.
Execute PHP function with onClick
You can execute a Javascript function assuming you´re using jQuery like this:
jQuery('#id-button').on('click', function(){
// your function body
});

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.

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Ajax POST is not posting onclick to current page

Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>

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