I'm having trouble with my project. I am trying to post something to the database via jQuery, but there is something wrong in my code and I am unable to figure out what.
Basically, I have a form:
<form id="addCartForm" method="POST" action="callback/additemtocart.php">
</form>
Inside the file additemtocart.php I have the following code:
$item_id = $_POST['item_id'];
$brand_id = $_POST['brand_id'];
$category_id = $_POST['category_id'];
if(item_exists($item_id, $brand_id, $category_id, $_SESSION['user_id']))
{
$errors[] = 'this item is already in your cart';
}
else
{
//register the user
$item_data = array(
'user_id' => $_SESSION['user_id'],
'item_id' => $item_id,
'brand_id' => $brand_id,
'category_id' => $category_id
);
add_item_to_cart($item_data);
$cart[] = 'An item has been added to your cart!';
}
Once the user clicks on the item, I will execute the following code:
$(".cart_item").click(function(){
var name = $(this).attr("id");
var array = name.split("|");
var data = [];
data.push({"item_id": array[0]});
data.push({"brand_id": array[1]});
data.push({"category_id": array[2]});
$.post($("#addCartForm").attr("action"), data, function(info){
});
});
$("#addCartForm").submit(function(){
return false;
});
Is there something wrong with it?
Your code won't work the way you want it to.
Javascript/jQuery is executed client side, the PHP is executed server side. When the callback in jQuery is fired, there's no PHP server on the client to deal with this PHP you've got there.
What you want to do instead, is pass the array key and string as a parameter in the $.post, to the script on the server, which can then add the string to your errors array.
Like this:
data.push({"item_id", array[0]});
data.push({"brand_id", array[1]});
data.push({"category_id", array[2]});
data.push({"errors", "my error string"});
$.post($("#addCartForm").attr("action"), data, function(info){
//success message?
});
Then in the action script, you'll be able to check for the get parameter $_POST['errors'], and add it to your PHP errors array.
if(isset($_POST['errors']) && !empty($_POST['errors'])){
$errors = $_POST['errors'];
}
EDIT: That aside, given your edit, your error is that your array isn't defined, is it? You have arrays named array1 and array2 but you're then trying to access array[0], array[1] and array[2]. It should be array2[0], etc.
Related
I am developing a plugin in which I get data from API, and then the user has an option to add this data to the cart and purchase the product. Everything works perfectly, except once we reload the page, the user cart value gets lost. How can I solve this?
I think one solution is, If we add the cart object to the session, it will be easy to use that session value to get the cart object. For this, I added the below function
my_file.js
function savecartObj(cartObj) {
$.post(
'cartObj.php',
{
cartobj : cartObj
},
function success(data) {
console.log(data);
}
);
}
and in my cartObj.php
<?php
/** Set up WordPress environment, just in case */
$path = preg_replace('/wp-content(?!.*wp-content).*/','',__DIR__);
require_once($path.'wp-load.php');
session_id() || session_start();
nocache_headers();
$_SESSION['ajjx'] = $_POST;
$value = '';
if (array_key_exists('ajjx', $_SESSION)) {
if (array_key_exists('cartobj', $_SESSION['ajjx']) {
$value = $_SESSION['ajjx']['cartobj'];
}
}
Header('Content-Type: application/json;charset=utf8');
die(json_encode(array(
'result' => $_SESSION['ajjx']['cart_obj'],
)));
Now I can see that $_SESSION['ajjx']['cart_obj'] is set and in console.log(data); I can see the session value. How can i use this value from $_SESSION['ajjx']['cartobj'] as cartobj in my_file.js
What I need is will create one file named get_session.php and in
that file, I will call the value of $_SESSION['ajjx']['cart_obj'] .
And then once my plugin is loaded I will call the value in
get_session.php & need to take the obj from the file and then add that value to add to cart function in the my_file.js. In that way, page reload doesn't
affect my cart.
Update
For getting the value I write the following function in my my_file.js
function get_cartObj(){
$.post(
'get_cartObj.php',
function success(data) {
console.log(data);
}
);
}
and in get_cartObj.php
<?php
/** Set up WordPress environment, just in case */
$path = preg_replace('/wp-content(?!.*wp-content).*/','',__DIR__);
require_once($path.'wp-load.php');
session_id() || session_start();
nocache_headers();
Header('Content-Type: application/json;charset=utf8');
json_encode(array(
'result' => $_SESSION['ajjx']['cart_obj'], // This in case you want to return something to the caller
));
but here get_cartObj() is not working as expected. No data coming in console.log(data);
The same way you saved it. Actually you can add a parameter to (save)CartObj:
function cartObj(operation, cartObj) {
$.post(
'cartObj.php',
{
op : operation,
cartobj : cartObj
},
function success(data) {
console.log(data);
}
);
}
and in the PHP code (7.4+ required because of the ?? operator)
if ($_POST['operation'] === 'set') {
$_SESSION['ajjx']['cartObj'] = $_POST['cartObj'] ?? [ ];
}
$value = $_SESSION['ajjx']['cartObj'] ?? [ ];
Header('Content-Type: application/json;charset=utf8');
die(json_encode(['result' => $value]));
Now calling the function with 'set' will save the Javascript cart into session, using 'get' will recover the cart.
update
You can also do it like this:
assuming that your page might receive a cart or it might not,
and you will always run the same AJAX code regardless,
then the PHP code must avoid removing the cart if the cartObj parameter is empty (you will need a different call to remove the cart when you need to do this; or you may do it from PHP).
session_id()||session_start();
if ('set' === $_POST['operation'] && !empty($_POST['cartObj'])) {
$_SESSION['ajjx']['cartObj'] = $_POST['cartObj'];
}
Header('Content-Type: application/json;charset=utf8');
die(json_encode(['result'=>$_SESSION['ajjx']['cartObj']??[]]));
This way, if you reload the page but the POSTed cart is now empty (because it's a reload), the AJAX script will not update the session, and it will return the previous session value.
Before im going to answer the question i have some dubt to clear, it looks like you are in a wordpress environment but you are not using his AJAX standard procedures. Check it out here https://codex.wordpress.org/AJAX_in_Plugins
About the issue since JS is client side and PHP is server side you need something to have the values available in JS. I can think of two option:
Print into the page with some PHP a little script tag which is made like this:
<script>
var myObjectVar = '<?php echo json_encode($_SESSION['ajjx']['cart_obj']); ?>';
</script>
You make a new AJAX call as soon as the page load to read that same value from PHP again and then use it to make what you need to do
Allow me to preface this by saying that I looked at multiple SO posts on this and I am still lost.
So in my php code I am fetching data from my database and then I am trying to insert it into an array as follows:
$arrayResult = array();
foreach ($result as $item) {
array_push($arrayResult, array("type" => $item['type'],
"count" => $item['count'])
);
}
echo json_encode($arrayResult);
My problem is as follows, the only time my JS shows any data is when I just print out the data on a successful AJAX call, any attempts at manipulating it fail totally. As in, no data shown at all.
var arrayResult = null;
$.get("../php/displayGraph.php",
function (data) {
arrayResult = (data);
var result = JSON.parse(arrayResult);
$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
The result of this is:
[{"type":"Entertainment","count":"4"},{"type":"Other","count":"31"},{"type":"Politics","count":"50"},{"type":"Sports","count":"3"},{"type":"Technology","count":"9"}]
I am honestly at a loss in terms of what I even need to do to make it work. And here I thought java was bad with json.
Try like this,
$.get("../php/displayGraph.php",
function (data) {
$.each(data, function (i,item){
console.log(item.type + " === " +item.count);
}
/*arrayResult = (data);
var result = JSON.parse(arrayResult);*/
//$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
Not sure why, but the following works
$.get("../php/displayGraph.php",
function (data) {
var result = JSON.parse(data);
$("#results").html(data);
console.log(result[1][0].count);
}
);
Certainly is a 2D array the way my php makes it, but i did not think this would be how to do as all the other tutorials i saw never had it like this.
I had created basic custom module. in that i just filled information form and that information will stored into the database. and that data i am showing into table format. now i want to edit and delete records from clicking links.
I want to call php function on clicking following links
links are:
while($data = $result->fetchObject()){
$rows[] = array(
$data->id,
$data->name,
$data->address,
$data->mob,
$data->gen,
$data->email,
$data->hob,
l('Edit' .$data->id,'/table', array('query' => array('edi'=>$data- >id))),
l('Delete' .$data->id, '/table', array('query' => array('del'=>$data->id))),
);
}
and the functions are as follows:
function form_values_edit($id){
$id_val = $id;
$my_object = db_select('demo_forms','n')
->fields('n')
->condition('id', $id_val )
->execute()
->fetchAssoc();
return drupal_get_form('demo_form', $my_object);
}
function delete_confirm($form, &$form_state, $id){
$form['delete'] = array(
'#type' => 'value',
'#value' => $id,
);
return confirm_form(
$form,
t('Are you sure you want to delete this?',
'/table',
t('This action cannot be undone'),
t('Delete'),
t('Cancel')
));
}
function delete_confirm_submit($form, &$form_state) {
$record = $form_state['values']['delete'];
if ($record ) {
$num_deleted = db_delete('demo_forms')
->condition('id', $record )
->execute();
drupal_set_message('The record has been deleted!');
}
$form_state['redirect'] = "/table";
}
Thanks
You cannot call a PHP function dynamically by clicking a link, as PHP is a server side language. HOWEVER if you load another page, before loading the page you can execute PHP code.
EDIT
if you need a PHP function dynamically, what I usually do (and this may be wrong according to some people) is call that function in an AJAX call. Note: I would generally use POST for this.
$.ajax(
url: 'url/to/php/function',
type: 'POST/GET',
data: {'data' : data},
success: function(res) {
// use the result stored in res
},
error: function(res) {
// use res to get the error result
}
);
Just add check for id field or another unique value in your php code and update or delete rows where id = ... With out unique value you can't do that. Describe your usability and post your html for more...
I'm trying to build an array of data that will then be ajax using post to php - below is my code:
$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
var profilePhotoArray = [];
$('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
var action = '';
alert( this.id );
if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
alert('attractive...');
action = 'attractive';
}
else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
alert('delete...');
action = 'delete';
}else{
alert('normal...');
action = 'normal';
}
profilePhotoArray[this.id+'_'+this.id] = action;
});
alert(profilePhotoArray.length);
for (i=0;i<profilePhotoArray.length;i++) {
console.log("Key is "+i+" and Value is "+array[i]);
}
$.post('scripts/ajax/ajax_approval_functions.php', {
'approvalProfilePhotos': '1',
'approvalProfilePhotosData': profilePhotoArray},
function(data) {
alert(data);
});
});
The if, else if, else section works fine as I can see the alerts.
When I try to alert the array length 'profilePhotoArray' it says 0 so I'm not populating the array correctly. Do I need to use .push()? I thought this format was ok?
Also do I need to do anything to the array before sending to php via ajax?
thankyou
** edit - I'm adding "profilePhotoArray[this.id+'_'+this.id] = action;" this.id twice just to prove this words as I will pass a second variable like this... am I better to use JSON for this?
Javascript arrays use numerical index, therefore your storage is failing. Use a javascript Object to store string based keys.
var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";
I would like to save a message in PHP variable and send it back with my other array variable that is already coming back. For instance, I have some error checking that takes place inside the PHP code and would like a string variable with the specific message sent back for use in my javascript.
Here is the PHP:
<?php
include('config-searchres.php');
$term = $_POST['resid'];
$sql = mysql_query("SELECT * FROM ap_form_8 WHERE id = '$term'"); //select first name (element_1_1) from form #8
if ($row = mysql_fetch_array($sql)){ //if reservation number exists
if ($row['element_11'] != 'Cancelled'){ //if reservation has not already been cancelled
if (strtotime($row['element_3']) >= strtotime(date("Y-m-d"))){ //if reservation has not already passed date
echo json_encode($row);
}
else //Reservation already passed (old reservation)
{
echo 'passed';
}
}
else //Reservation already cancelled
{
echo 'cancelled';
}
}
else //Reservation not found
{
echo 'not found';
}
mysql_close();
?>
As you can see, there are 3 different messages, "passed", "cancelled", and "not found"... if one of these conditions exists, I would like to send this string back to my javascript so I can display it in a DIV. However, I also want to send the $row data with it.
My javascript:
<script type="text/javascript">
$(document).ready(function(){
resetForms('reservation');
$('#form-reservation').submit(function(event){
event.preventDefault(); //the page will no longer refresh on form submit.
var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
$.ajax({
url: 'inc/searchres.php',
type: 'POST',
data: 'resid='+resCheck,
success: function(data){ //data is all the info being returned from the php file
$('#reservation-id').val(resCheck); //add read ID back into text box
var jsonData = $.parseJSON(data); //parse returned JSON data so we can use it like data.name, data.whatever
//****I wanted the line just below this to display the appropriate message sent back from the PHP****
$("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
$('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'], reservation_id:jsonData['id'], reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});
$("#res-cancel-message").html('');
},
error: function(){
$("#res-message").html('<a>There was an error with your request</a>');
$("#res-cancel-message").html('');
}
});
});
});
</script>
I marked with asterisks where I populate the DIV with a static message at this time, this is the line where I would populate the message from PHP. Any ideas?
You could add that message as one of your JSON properties and then search for it appropriately.
You can always wait a little with echoing json encoded $row.
Add $row and you message to an array variable, which you json encode and echo out.
Not 100% sure about syntax details/dots
$response_array = array('message' => 'yourmessage', 'row' => $row);
echo json_encode($response_array);
Send both in ajax. LIke
Dont echo anything in the body of your if else, just store the message in variable, say, $message = 'passed', now do this at the end of your php request page:
echo json_encode(array('message_js'=>$message, 'row_js' => $row));
This sends json array as responce so u can send as much variables in it as much u like. Just put them in an array() and convert them into json using json_encode()
to convert into json and pass as response. When recieved in success function of your ajax, just decode the two json variables : message_js and row_js.
You can use parsejson of jquery to get your variables then
Just pass the appropriate message from the server .let us suppose your message is in message variable:
$("#res-message").html('' + data.message +'Reservation ID Located, Information is displayed below');
By the time you convert your row data into the $row, it is an array. You can, if you dare, simply add your message to that array before you json_encode it.
$row["message"] = ...
You can do it this way:
$result = array();
if ($row = mysql_fetch_array($sql)){ //if reservation number exists
if ($row['element_11'] != 'Cancelled'){ //if reservation has not already been cancelled
if (strtotime($row['element_3']) >= strtotime(date("Y-m-d"))){ //if reservation has not already passed date
$result = array('status' => 'OK', 'data' => $row);
}
else //Reservation already passed (old reservation)
{
$result = array('status' => 'passed', 'data' => $row);
}
}
else //Reservation already cancelled
{
$result = array('status' => 'cancelled', 'data' => $row);
}
}
else //Reservation not found
{
$result = array('status' => 'not found', 'data' => null);
}
echo json_encode($result);