I have the following class in a php file:
function calcTotal(){
var productID = <?php echo $product_info['products_id'];?>;
var sizeID = 0;
$(".mine_sizes").each(function() {
if ($(this).is(':checked')) sizeID = $(this).val();
});
//alert(sizeID);
var colorID = 0;
$(".mine_color").each(function() {
if ($(this).is(':checked')) colorID = $(this).val();
});
$.ajax({
type: "POST",
url: 'get_product_price.php',
data: "product_id="+ productID +"&color_id="+ colorID +"&size_id="+ sizeID,
success: function( response ) {
$("#price_container").html(response);
;
}
});
}
and the php file get_product_price.php:
if($_POST){
$product_info_query = tep_db_query("select products_price, products_tax_class_id from " . TABLE_PRODUCTS . " where products_id = '" . (int)$_POST['product_id']."'");
$pricePrice = tep_db_fetch_array($product_info_query);
$productPrice = $pricePrice['products_price'];
$sizesPrices = tep_db_query("select options_values_price from products_attributes where products_id='".$_POST['product_id']."' and options_values_id='".$_POST['size_id']."'");
// echo "select options_values_price from products_attributes where products_id='".$_POST['product_id']."' and options_values_id='".$_POST['size_id']."'";
// exit;
if(mysql_num_rows($sizesPrices)>0){
$priceRow = tep_db_fetch_array($sizesPrices);
$productPrice = $productPrice + $priceRow['options_values_price'];
}
$sizesPrices2 = tep_db_query("select price from product_attributes_color_relation where product_id='".$_POST['product_id']."' and color_id='".$_POST['color_id']."' and color_size_option_id='".$_POST['size_id']."'");
if(mysql_num_rows($sizesPrices2)>0){
$priceRow2 = tep_db_fetch_array($sizesPrices2);
$productPrice = $productPrice + $priceRow2['price'];
}
//echo $productPrice; exit;
echo $currencies->display_price($productPrice, tep_get_tax_rate($product_info['products_tax_class_id']));
//echo $productPrice;
}
The function is called on a radio button click and is currently working but I am trying to understand how it works for myself (and to possibly recreate a similar function)
What I am not really understanding is the data parameter from the ajax api. How is that data parameter used?
another question I have is the success parameter. Is the "response" parameter a standard or can in be called anything?
Thanks for any help explaining this to me. I don't think any other information is necessary, there is a div with a class id #price_container which is where the price is echo'd.
The data parameter passes the information the same way an HTML form will. At least that's the easiest way to think of it. So that "data" will come through as $_POST or $_GET arrays. I always setup my data as JSON format:
data: { "product_id": productID,"color_id": colorID, "size_id": sizeID },
With your type set as "POST" that would come through as:
$_POST['product_id']
$_POST['color_id']
$_POST['size_id']
You can specify any variable name for the response - but 'response' is nice and easy to remember and work with. :)
from the ajax documentation
data
[Object, String]
Data to be sent to the server. It is converted to a
query string, if not already a string. It's appended to the url for
GET-requests. See processData option to prevent this automatic
processing. Object must be Key/Value pairs. If value is an Array,
jQuery serializes multiple values with same key based on the value of
the traditional setting (described below).
Basically if you set the data variable to a query string, it sends it to the server as is, other wise it will generate a query string from the key value pairs that you set. Once the php server receives the query string it is parsed and you can access your values using
$_POST['key']
Related
I have an ajax call which pulls data from the table and then transforms into a JSON object
Because I am also doing a lot with PHP as well I need to have a 2nd AJAX call
immediately after the first that will update $_SESSION info
I have tried putting
$_SESSION['company_id'] = $_POST['companyid'];
in the same file that handles the 1st AJAX call but it then doesn't process the data from the first call, hence I need to do the 2nd call
Here is my jQuery Code for the 1st and 2nd AJAX query
$(".showcompinfo").click(function(){
$("#comptable").hide();
$("#showcomptable").show();
var id = $(this).attr('id');
$("#comp_info").toggle();
var companyid = id;
var dataString = "companyid="+companyid;
$.ajax({ /* THEN THE AJAX CALL */
type: "POST",
url: "../inc/dataforms/complist.php",
data: dataString,
success: function(result){
var jsonObject = JSON.parse(result);
// here you can do your magic
var approved = jsonObject.customer_approved;
$("#showcompname").text(jsonObject.name);
// Get Reg Address Details - Check if any field is empty
var regoffice_2 = '';
var regoffice_3 = '';
var regoffice_city = '';
console.log(jsonObject.regoffice_city);
if(jsonObject.regoffice_2)
{
regoffice_2 = ', ' + jsonObject.regoffice_2;
};
if(jsonObject.regoffice_3)
{
regoffice_3 = ', ' + jsonObject.regoffice_3;
};
if(jsonObject.regoffice_city)
{
var regoffice_city = ', ' + jsonObject.regoffice_city;
};
var addlne1 = jsonObject.regoffice_1;
var regaddress = jsonObject.regoffice_1 + regoffice_2 + regoffice_3 + regoffice_city;
$("#addline1").val(jsonObject.regoffice_1);
$("#addline2").val(jsonObject.regoffice_2);
$("#addline3").val(jsonObject.regoffice_3);
$("#addcity").val(jsonObject.regoffice_city);
$("#addcounty").val(jsonObject.regoffice_county);
$("#countryselected").val(jsonObject.regoffice_country);
$("#countryselected").text(jsonObject.regoffice_country);
$("#addpostcode").val(jsonObject.regoffice_postcode);
console.log(regaddress);
if(approved == '1')
{
$("#approvedcust").text('Yes');
} else {
$("#approvedcust").text('Customer but Not Approved');
};
}
});
// 2nd Ajax
var companyid2 = jsonObject.company_id;
var dataString2 = "companyid="+companyid2;
$.ajax({ /* THEN THE AJAX CALL */
type: "POST",
url: "../inc/updatesession.php",
data: dataString2,
success: function(){
}
});
//
Here is the PHP code for complist.php
if(!empty($_POST['companyid']))
{
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc,"SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if($result){
$newdata = json_encode($result);
}
}
print_r($newdata);
If anyone can help even consolidate this into 1 ajax query or help me get 2 calls
working correctly it would be much appreciated
** EDIT **
OK I now have it displaying the Company ID in the session variable however when the user clicks to view a different company info result the session company_id does not update
I have changed the complist.php to the following
if(!empty($_POST['companyid']))
{
unset($_SESSION['company_id']);
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc,"SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if($result){
$_SESSION['company_id'] = $_POST['companyid'];
$newdata = json_encode($result);
}
}
print_r($newdata);
My thinking behind the above was that once the ajax call is made it immediately unsets the session variable company info
then once a result is found for the selected company it resets the session var company_id with the new value, however its not updating the session variable
Screenshots showing what I mean
Your code updates your session variable successfully. However, since you're making an AJAX call, only the code in the PHP script directly called by the AJAX ("complist.php" in this case) is executed on the server. None of the PHP code which originally used to create your page is run again - this is why you have to use JavaScript to populate the rest of your newly selected company details.
To update the ID on screen following the AJAX call, all you need to do is follow the pattern you've used to update the rest of the fields
Change your HTML so the element which contains the company ID has an ID which lets JavaScript identify it:
<span id="showcompname"></span><span id="showcompid"><?php echo $_SESSION['company_id'];?></span>
and then in the "success" callback of your AJAX code, write
$("#showcompid").text(jsonObject.company_id);
This is exactly the same concept as the other JavaScript code you've got e.g. to update the "showcompname" element.
Meanwhile, the value stored in your PHP session will be used next time you run the PHP code which updates the whole page (e.g. by refreshing the page).
I created a simple searching function in php. Its working when im not using ajax to that script. But when i use ajax, my implode function disappear.
Here how my codes looks like.
$searchtag = filter_var($_GET['search'], FILTER_SANITIZE_STRING);
$searchtagrlce = str_replace("+", " ", $searchtag);
$searchTermsis = explode(' ', $searchtagrlce);
$searchTermBitsis = array();
foreach ($searchTermsis as $terms) {
$terms = trim($terms);
if (!empty($terms)) {
$searchTermBitsis[] = "tbale_row1 LIKE '%$terms%' OR tbale_row12 LIKE '%$terms%' OR tbale_row13 LIKE '%$terms%'";
}
}
$getdataquerystores = "SELECT `tbale_row1`, `tbale_row2`, `tbale_row3`, `tbale_row4`, `tbale_row5`, `tbale_row6` FROM `tablename` WHERE ".implode(' AND ', $searchTermBitsis). " ORDER BY tbale_row1 DESC LIMIT $limit, 10";
$getdataquerystoress = mysqli_query($connection, $getdataquerystores);
when i echo or print the above codes without ajax, im getting this
SELECT `tbale_row1`, `tbale_row2`, `tbale_row3`, `tbale_row4`, `tbale_row5`, `tbale_row5` FROM `tablename` WHERE tbale_row1 LIKE '%a%' OR tbale_row2 LIKE '%a%' OR tbale_row3 LIKE '%a%' ORDER BY tbale_row1 DESC LIMIT 0, 10
but when i use ajax and print the above same code, im getting this (AFTER WHERE FUNCTION DATA HAS BEEN DISAPPEAR)
SELECT `tbale_row1`, `tbale_row2`, `tbale_row3`, `Logo_croped_554`, `tbale_row5, `tbale_row6` FROM `tablename` WHERE ORDER BY tbale_row1 DESC LIMIT 10, 10
here it is my ajax code
$(window).scroll(function ()
{
if($(document).height() <= $(window).scrollTop() + $(window).height())
{
loadmore();
}
});
function loadmore()
{
var val = $("#row_no").val();
$.ajax({
type: 'post',
url: '/myproject/data/alldata.php',
data: {
getresult:val
},
beforeSend:function(){
$(".loading-data").fadeIn("slow");
},
uploadProgress:function(){
$(".loading-data").fadeIn("slow");
},
success: function (response) {
var content = document.getElementById("dsdplasdy_sdtres");
content.innerHTML = content.innerHTML+response;
document.getElementById("row_no").value = Number(val)+10;
},
complete:function() {
$(".loading-data").fadeOut("slow");
}
});
}
here it is the value im getting from tne hidden field
<input type="hidden" id="row_no" value="10" />
Please any ex[ert may help me. Any help much appreciated. Thanks.
To pass arrays over the internet, or any other data for that matter, the data needs to be properly serialized and encoded on the senders end and un-serialized and decoded on the receivers end. There are many ways to serilize the data but the defaults that are supported by PHP directly are application/x-www-form-urlencoded or multipart/form-data which will populate the $_POST superglobal variable if the POST request method is used. The data can also be passed as URL parameters where the query portion of the URL is "application/x-www-form-urlencoded" encoded and populates the $_GET superglobal variable in PHP.
Note: Use $_POST or $_GET superglobals to get data. If you have register globals on you should turn it off, it is no longer supported as of version 5.4 http://php.net/manual/en/security.globals.php
For your specific case you are not passing the search parameter from your AJAX request.
url: '/myproject/data/alldata.php',
should be
url: '/myproject/data/alldata.php?search='+encodeURI(searchTerms),
You will need to populate the searchTerms variable with your search terms or replace searchTerms with your actual search terms. If you don't know how to get the search terms see How to retrieve GET parameters from javascript?
Thank you everyone who answered above. I been trying to figure this. It wan't something with the ajax as i mentioned.I was about how php forget variables data when it is passing through ajax. There for i used hidden field to store the data and then i sent it to the sript later using ajax.
<input type = "hidden" value= "<?php search parameter ?>"
I'm fairly new to PHP and really new to JQuery.
So I writ some JQuery that does some calculations, I writ something below that is similar:
//on change of a selectbox with the class item
$('.item').change(function() {
// set variable id as the id name of this id
var id = this.id;
// price variable is equal to the value of the element id 'hiddenprice'
price = $("#hiddenprice").val();
// number of items is the value of the select box
numberofitems = $(this).val();
// number of days is equal to a php variable I set on the page
numofdays = "<?php echo $length->days; ?>";
//totalprice is equal to the 'price' multiplied by 'numofdays'
totalprice = Number(price) * Number(numofdays);
//calculates final total by multiplying the 'totalprice' by 'numofitems'
finaltotal = Number(totalprice ) * Number(numofitems);
//updates the HTML with the new price
$('#'+id).html("€" + finaltotal.toFixed(2));
});
I was trying this and although I got it to work, after reading up some I am aware that because this script is in my footer of the page that is getting updated, it is unsafe and easy to manipulate if a user wanted to be malicious.
So I want to do the calculations server side, by posting values to a PHP script and then returning the values.
// POST values to PHP Script
$id = (posted select id);
$price = (#hiddenprice variable value);
$numofitems = (posted value of the select);
$numofdays = $length->days;
$totalprice = (int)$price * (int)$numofdays;
$finaltotal = (int)$totalprice * (int)numofitems;
//Then push $finaltotal and $id back to the user viewed page
$('#'+<?php echo $id; ?>).html("€" + <?php echo $finaltotal; ?>.toFixed(2));
I'm just not sure how to push them to the page without refresh and then return them, also without refresh.
Again, sorry if this is simple, I have looked at JQuery form plugins, I just wondered if there is more apt solution for what I would like to do.
Thanks in advance.
You may want to check out ajax, it can post or get data without refreshing the page. Also the answer of this question may be helpful too.
You need to use AJAX. This sends data to the server and allows you to execute a callback once you receive a response.
If you are using jQuery, then read up about the $.ajax method.
To handle the response, the easiest data type to use is JSON.
So a quick example
Javascript
$.ajax({
url: calculation_url.php,
method: 'post',
dataType: 'JSON',
data: {price: price, days: numofdays },
success: function(response) {
// you should check a valid response was received
$("#result").html(response.html);
}
});
PHP - calculatin_url.php
$price = $_POST['price'];
$days = $_POST['days'];
// do calculations
// send data back as json
die(json_encode(array('html' => $finalTotal)));
To start this process you will need to attach events to the calculation button. Read about registering events with the on method and you may find it helpful to read about the event.preventDefault() method.
Disclaimer
I have searched for duplicates, but I can't seem to find them. I am surprised because this seems to be a big issue. I most likely am missing something big though.
Problem/Question
I am having the userid passed into through the url via php, myOtherScript.php?userid=1. How can I get that variable to be passed via ajax so that I may query the database with that userid, echo it out and return it to the page?
This is in global.js file
jQuery
$.ajax({
url: "myScript.php",
data: "userid=" - This is what I need: $_GET['userid'] - ,
success: function( data ) {
$('#myDiv').html( data );
}
});
Solution
WIth the help of bstakes and this answer, I was able to figure it out with this function: (top answer)
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Thanks for the answers guys!
$.ajax({
url: "myScript.php",
data: "userid=<?php echo intval($_GET['userid']); ?>",
success: function( data ) {
$('#myDiv').html( data );
}
});
You could also try using the search attribute of the window.location object.
If the url is http://www.mysite.com/display.php?userid=7 window.location.search will return "?userid=7". You will obviously need to remove the leading "?", but be aware that if there are additional GET paramaters, separated with ampersand '&', those will be included as well.
So, with a bit of additional Javascript, you can split on the '&', which gets you an array of "key=val", then you can spilt on the equal sign and create an object with {key : val}. Then you could use that object to access the query string params.
var qs = window.location.search.substring(1),
pieces = qs.split('&'),
i,
qsObj {},
tmp;
for ( var i in pieces ) {
tmp = pieces[i].split('=');
qsObj[tmp[0]] = tmp[1];
}
See https://developer.mozilla.org/En/Window.location for additional information on the window.location.
If you want to keep the JS seperate, put it in a function that accepts the user id...
function do_something(user_id) {
$.ajax({
url: "myScript.php",
data: "userid=" + user_id,
success: function( data ) {
$('#myDiv').html( data );
}
});
}
Then just call do_something($_GET['user_id']);
You might have to move the script inline on the PHP file then you echo out the $_GET['userid'] in the data area of your ajax call.
just found this: how to get GET and POST variables with JQuery?
If data is submitted via POST through the classic HTML form method is it possible to access those values using standard Javascript without libraries? How would this be done?
Edit for clarity: The variables have been posted. I am trying to access those values via javascript.
Thinking outside the box: (A hack that should never see the light of day)
For this example the posted variable is "a":
var val=document.URL;
var start;
start = val.search(/a=/);
var end;
end = val.search(/&/);
var thispos = val.substring(start+2,end);
document.URL returns the url of the current site.
val.search returns the position of the first occurrence of the regular expression in
the parameter field.
substring the two and...
thispos now contains the posted variable.
Brutal but functional. Is this too terrible to be an answer?
use:
var myField = document.getElementById('myFieldId');
then myField.value will contain the value.
If you have submitted the page, then you have to get the form data using PHP.
Here is a tutorial that should help: http://www.phpf1.com/tutorial/php-form.html
But if you decide to test jQuery, you can use this:
jQuery('#submit').live('click', function()
{
var form_data = jQuery("#data_form").serialize();
//Save data
jQuery.ajax({
url: siteURL +"/path/to/php/file/jquery.php",
data: {formData : form_data,
success: (function(data) {
//data is whatever you return from jquery.php
//I use json for return data
alert('Data has been saved');
}),
dataType: 'json'
});
After a post, the data is send to the server, javascript cant do anything with that since its client side. What you can do is pre-check with document.getElementById('formid') and use those values in the form. After validating or doing what you want to do, end with form.submit() to really send it to the server.
function getUrlInfo() {
var data = window.location.search.substring(1).split("&");
//returns an array of strings containing the params and their values
// data = [ "param=value","param=value","param=value"]
var params1Array = data[0].substring(0).split("=");
//Splits the first string element at the "=" symbol and
//returns an array with the param and value
//param1Array = ["param","value"]
var param1Value = param1Array[1].replace("+", " ");
//Gets the value from the second element in the param1Array
//Replaces the spaces, if any, in the second element,
//which is the value of the url param
var param2Array = data[1].substring(0).split("=");
//Repeat steps for the second param element,in the url params data array
var param2Value= param2Array[1].replace("+", " ");
return {
param1Value,
param2Value
}
};
The submitted data (either POST or GET) is proccesed on the server side. Javascript runs on the client-side so you can't access the variables from the page receiving the form request.
But you can access them before the post using the input field id (specially to check the input values before sending them).