So I have a page index.php?packageID=153. That page has a form which when submitted is sent to PHP via Ajax call
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('submit', '#form_name', function()
{
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'phpfile.php',
data : data,
success : function(data) {
$('.result-modal').html(data);
},
error: function (request, status, error) {
alert(error.responseText);
//or console.log(request.responseText), or status or error;
}
});
return false;
});
});
</script>
I want to get that ID from the URL. I usually just do $_GET['PackageID'] (in my PHP file) to get the ID from the URL when I'm not using Ajax, but it doesn't work with ajax (from what I'm experiencing). How do I get That ID in my PHP file?
Two possibilites:
You insert the PackageID as a GET parameter into the url:
url : 'phpfile.php?PackageId=<?php echo $_GET['PackageID']; ?>',
You insert the parameter into the JavaScript data object like:
var data = $(this).serialize();
data.PackageId = <?php echo $_GET['PackageId']; ?>;
$.ajax({
[...]
However you do it, at some point you have to output text from PHP inside your JavaScript code.
It's a PHP file so you can still use PHP. Add something like this at the top of the file.
<?php
echo '<script>';
echo "var id = $_GET['packageID']";
echo '</script>';
?>
Related
So here's the problem:
Trying to make an ajax call using .ajax. However, there's something going wrong somewhere because my controller isn't redirecting to the good view file and nothing is displaying on my page.
Here is where the ajax call happens
$('#validate').on('click',function(){
var data = []; // data container
// collect all the checked checkboxes and their associated attributes
$("table#subsection_table input[type='checkbox']:checked").each(function(){
data.push({
subsectionid : $(this).val(),
sectionid : $(this).data('sectionid'),
year : $(this).data('year')
})
});
// JSON it so that it can be passed via Ajax call to a php page
var data = JSON.stringify(data);
$.ajax({
url : "<?php echo Yii::app()->createAbsoluteUrl("scheduler/AjaxExample"); ?>",
type: "POST",
data : "myData=" + data,
success : function()
{
alert("in success");
$("#ajax-results").html(data);
$("#ajax-results").dialog({ width: 500, height: 500})
},
error: function()
{
alert("there was an error")
}
})
console.log(JSON.stringify(data));
$('#dialog').html(data).dialog({ width: 500, heigh: 500});
});
Now here's my controller code:
public function actionAjaxExample()
{
$post_data = $_POST['myData'];
$this->renderPartial('_ajax', array(
'data'=> $post_data,
)
);
}
trying to redirect to _ajax view file:
<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
echo "HI FROM BACKEND! here's what you gave to PHP: <br>";
print_r($data);
?>
So I'm obviously doing something wrong but... I can't seem to find where because the ajax call DOES happen ( at least in my #validate on click event). However, the last view file isn't displaying it's alert box OR the "hello from back end".
Try :
remove var data = JSON.stringify(data);
change
data:{myData:data},
I think the issue is with the quotes of the url.
Please check if you are getting some JavaScript error in console.
If you are getting some error, Please change this
$.ajax({
url : "<?php echo Yii::app()->createAbsoluteUrl("scheduler/AjaxExample"); ?>",
type: "POST",
to
$.ajax({
url : '<?php echo Yii::app()->createAbsoluteUrl("scheduler/AjaxExample"); ?>',
type: "POST",
If not getting any error, Please check the xHr tab in console, whats the url, your ajax is hitting. Please let me know in case of any issue
$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'<?php echo site_url($this->config->item('admin_folder').'/catalog/get_all_option');?>',
type:'POST',
data:{category_id:1},
dataType: 'json',
success:function(data){
$('#attribute_form').html('<?php add_attribute_form("'+data+'");?>');
}
});
}
});
on callback function success return the data and pass it to add_attribute_form(data) php function but nothing response.
what is the correct way to pass js object to php function
What you will need to do here is, use Ajax to send data to a separate php page passing it some information, then, based on that information, the php page should return data to the Ajax callback function which will add the returned data to the original page.
Here's a simple example (and a working demo here):
In index.html do this:
<script>
$(document).ready(function(){
$('.select_category').change(function(){
if($(this).is(':checked')){
var ID = $(this).val();
$.ajax({
url:'somepage.php',
type:'POST',
data:{category_id:1},
dataType: 'json', // this setting means you expect the server to return json formatted data
// this is important because if the data you get back is not valid json,
// the success callback below will not be called,
// the error callback will be called instead
success:function(response){
$('#attribute_form').html(response.html);
// if not using json, this would just be $('#attribute_form').html(response);
},
error:function(xhr, status, error){
// handel error
}
});
}
});
});
</script>
<input type="checkbox" class="select_category"> Check this box
<div id="attribute_form"></div>
Then in somepage.php do the following:
<?php
$category_id = isset($_POST['category_id']) ? $_POST['category_id'] : null;
if($category_id == '1'){
echo json_encode(array('html'=>'<h1>This text came from the php page</h1>'));
exit;
// if you are not using dataType:json in your ajax, you can just do:
// echo '<h1>This text came from the php page</h1>';
// exit;
}
?>
I'm trying to show a specific div depending on the result of a SQL query.
My issue is that I can't get the divs to switch asynchronously.
Right now the page needs to be refreshed for the div to get updated.
<?php
//SQL query
if (foo) {
?>
<div id="add<?php echo $uid ?>">
<h2>Add to list!</h2>
</div>
<?php
} else {
?>
<div id="remove<?php echo $uid ?>">
<h2>Delete!</h2>
</div>
<?php
}
<?
<script type="text/javascript">
//add to list
$(function() {
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
success: function(data){
$('#add'+I).hide();
$('#remove'+I).show();
}
});
return false;
});
});
</script>
<script type="text/javascript">
//remove
$(function() {
$(".minus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_remove.php",
data: info,
success: function(data){
$('#remove'+I).hide();
$('#add'+I).show();
}
});
return false;
});
});
</script>
ajax_add.php and ajax_remove.php only contain some SQL queries.
What is missing for the div #follow and #remove to switch without having to refresh the page?
"I'm trying to show a specific div depending on the result of a SQL query"
Your code doesn't seem to do anything with the results of the SQL query. Which div you hide or show in your Ajax success callbacks depends only on which link was clicked, not on the results of the query.
Anyway, your click handler is trying to retrieve the id attribute from an element that doesn't have one. You have:
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
...where .plus is the anchor element which doesn't have an id. It is the anchor's containing div that has an id defined. You could use element.closest("div").attr("id") to get the id from the div, but I think you intended to define an id on the anchor, because you currently have an incomplete bit of PHP in your html:
<a href="#" class="plus" ?>">
^-- was this supposed to be the id?
Try this:
<a href="#" class="plus" data-id="<?php echo $uid ?>">
And then:
var I = element.attr("data-id");
Note also that you don't need two separate script elements and two document ready handlers, you can bind both click handlers from within the same document ready. And in your case since your two click functions do almost the same thing you can combine them into a single handler:
<script type="text/javascript">
$(function() {
$(".plus,.minus").click(function(){
var element = $(this);
var I = element.attr("data-id");
var isPlus = element.hasClass("plus");
$.ajax({
type: "POST",
url: isPlus ? "ajax_add.php" : "ajax_remove.php",
data: 'id=' + I,
success: function(data){
$('#add'+I).toggle(!isPlus);
$('#remove'+I).toggle(isPlus);
}
});
return false;
});
});
</script>
The way i like to do Ajax Reloading is by using 2 files.
The first: the main file where you have all your data posted.
The second: the ajax file where the tasks with the db are made.
Than it works like this:
in the Main file the user lets say clicks on a button.
and the button is activating a jQuery ajax function.
than the ajax file gets the request and post out (with "echo" or equivalent).
at this point the Main file gets a success and than a response that contains the results.
and than i use the response to change the entire HTML content of the certain div.
for example:
The jQuery ajax function:
$.ajax({
type: 'POST', // Type of request (can be POST or GET).
url: 'ajax.php', // The link to the Ajax file.
data: {
'action':'eliran_update_demo', // action name, used when one ajax file handles many functions of ajax.
'userId':uId, // Simple variable "uId" is a JS var.
'postId':pId // Simple variable "pId" is a JS var.
},
success:function(data) {
$("#div_name").html(data); // Update the contents of the div
},
error: function(errorThrown){
console.log(errorThrown); // If there was an error it can be seen through the console log.
}
});
The PHP ajax function:
if (isset($_POST['action']) ) {
$userId = $_POST['userId']; // Simple php variable
$postId = $_POST['postId']; // Simple php variable
$action = $_POST['action']; // Simple php variable
switch ($action) // switch: in case you have more than one function to handle with ajax.
{
case "eliran_update_demo":
if($userId == 2){
echo 'yes';
}
else{
echo 'no';
}
break;
}
}
in that php function you can do whatever you just might want to !
Just NEVER forget that you can do anything on this base.
Hope this helped you :)
if you have any questions just ask ! :)
UPDATE: Wow that was the fastest response ever and so many answers in minutes of each other. Amazing. Ok here is what I am trying to do. http://edvizenor.com/invoice33/
I want to edit this invoice on the fly but when I hit the BLUE BOX at the top I want to preview or see this content on the next page contained php var echoed out.
This blue box will change later to be a button at the bottom but for testing I am using it.
As you see it calls the ajax script but I need the edited content of the div to be sent a php var to I can echo it on the preview page. If I can put it in a php var I do what I will with it on the next page. Does that make sense? Thanks guys for your quick responses.
OLD POST
Is it possible to get the contents of a div using jQuery and then place them in a PHP var to send via GET OR POST?
I can get the contents of the div with jQuery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#MyButton").click(function()
{
var htmlStr = $("#MyDiv").html();
});
});
</script>
But how do I put the jQuery var in a php var. I need to do this by a BUTTON press too. This is not included in the code above. I need because the div file is changeable and when I hit UPDATE and send via PHP it needs to have the latest content.
According to your situation,
You are trying to send JavaScript variable to PHP.
The only common way to do this is to exchange in JSON format,
for example, suppose we have basic text editor
Jquery:
$($document).ready(function(){
$("#submit-button").click(function(){
$.post('yourphpscript.php', {
//this will be PHP var: //this is JavaScript variable:
'text' : $("#some_text_area").text()
}, function(response){
//To avoid JS Fatal Error:
try {
var result = JSON.parse(response);
//get back from PHP
if ( result.success){ alert('successfully changed') }
} catch(e){
//response isn't JSON
}
});
});
});
PHP code
<?php
/**
*
* So we are processing that variable from JavaScript
*/
if ( isset($_POST['text']) ){
//do smth, like save to database
}
/**
* Well if you want to show "Success message"
* that div or textarea successfully changed
* you can send the result BACK to JavaScript via JSON
*/
$some_array = array();
$some_aray['success'] = true;
die( json_encode($some_array) );
You'll need to use ajax to send the value to your server.
var html = $('#myDiv').html();
$.ajax({
type: 'POST',
url: '/SomeUrl/MyResource.php',
data: JSON.stringify({ text: html }),
success: function(response)
{
alert('Ajax call successful!');
}
});
The thing you need is AJAX (see http://en.wikipedia.org/wiki/Ajax_(programming))
The basic idea is to send a http request with javascript by e.g. calling a php script and wait for the response.
With plain Javascript AJAX requests are a bit unhandy, but since you are already using jQuery you can make use of this library. See http://api.jquery.com/jQuery.ajax/ for a complete overview.
The code on client side would be something like this:
$.ajax({
url:'http://example.com/script.php',
data:'var=' + $('#myDiv').html(),
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
In your script.php you could do something like this:
$var = $_GET['var'];
// Do some processing...
echo 'response';
and in your javascript console the string response would occur.
In modern ajax based applications the best practise way to send and receive data is through JSON.
So to handle bigger datasets in your requests and responses you do something like this:
$.ajax({
url:'http://example.com/script.php',
data:{
var:$('#myDiv').html()
},
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
And in your PHP code you can use the $someArray = json_decode($_GET['var']) to decode JSONs for PHP (it will return an associative array) and $jsonString = json_encode($someArray) to encode an array to a JSON string which you can return and handle as a regular JSON in your javascript.
I hope that helps you out.
You can use hidden form fields and use jQuery to set the value of the hidden field to that, so when the button is clicked and form submitted, your PHP can pick it up as if it were any other form element (using $_POST). Alternatively, you can use AJAX to make an asynchronous request to your PHP page. This is probably simpler. Here's an example:
$("#myButton").click(function() {
var htmlStr = $('#myDiv').html();
$.post("mypage.php", { inputHTML : htmlStr },
function(data) {
alert("Data returned from mypage.php: " + data);
});
}
Yes, Its possible
<script type="text/javascript">
$(document).ready(function(){
$('#MyButton').click(function(){
$.post('sendinfo.php',
{
data: $('#data').html()
},
function(response){
alert('Successfully');
});
});
});
</script>
<div id="data">Here is some data</div>
Use ajax for sending value to php (server).. here's a good tutorial for ajax with jquery http://www.w3schools.com/jquery/jquery_ajax.asp
you should just use Ajax to send your variable.
$.ajax({
url:'whateverUrl.php',
type:'GET',
data:{
html : htmlStr
}
});
Using AJAX:
$("#MyButton").click(function() {
var htmlStr = $("#MyDiv").html();
$.ajax({
url: "script.php",
type: "POST",
data: {htmlStr : htmlStr},
success: function(returnedData) {
//do something
}
});
});
Something like below should work.
Read more: http://api.jquery.com/jQuery.post/
$("#YourButton").click(function(e){
e.preventDefault();
var htmlStr = $("#YourDiv").html();
$.post(
url: 'YourPHP.php',
data: '{"htmlStr" : "'+htmlStr+'"}',
success: function(){
alert("Success!");
}
);
});
Send the data via XmlHttpRequest ("ajax") to your php page either via POST or GET.
This is the code that I'm using to send a variable (via GET) to another php file:
(basically, I click on a button, and then js gets the id and sends the id via ajax to the php file.
$(document).ready(function() {
$(".doClick").click(function() {
var category=$(this).attr('id');
$.ajax({
url:'aFile.php',
type:'GET',
data: $category,
success: function(data){
alert("It worked?"); // this is the response
}
});
alert($(this).attr("id"));
});
});
This is the code in my aFile.php:
The php file gets the info via $_GET[] and then assigns it to a variable and uses that variable in a function call.
<head>
<script type="text/javascript">
$(document).ready(function() {
function JS() {
//code
});
</script>
</head>
<body onload="JS()">
<?php
$category = $_GET['category'];
if (function_exists('inventory_insert')) {
echo inventory_insert('{category_name = '.$category.'}');
} else echo('warning');
?>
It's supposed to give me a response back on my main page, but nothing seems to be happening. I don't even get the alert I posted after the ajax script.
your variable is category but you're sending data: $category
You must send key/value pair to server
to receive $_GET['category'] your data sent in ajax needs to be either:
data: 'category='+category
Or
data: {category: category}
You have assigned id into category in jquery. so correct in data params.
data: {category : category},
Send it in this way to server or php file.
$(document).ready(function() {
$(".doClick").click(function() {
var category=$(this).attr('id');
$.ajax({
url:'aFile.php',
type:'GET',
data: {category : category},
success: function(data){
alert("It worked?"); // this is the response
}
});
alert($(this).attr("id"));
});
});