Jump to content

How to send multi page ids through Ajax


louisstephens
 Share

Recommended Posts

Currently, I have a page set up listing all child pages using a foreach loop and outputting some information (thus far, it is all gravy). However, I ran into a slight problem. I have a "button" on each item being rendered that when clicked needs to send the page id to another page for processing via ajax. I thought I could just save the item id like :

<?php $itemId = $item->id; ?>

And then encoding it below in my javascript:

var itemId = <?php echo json_encode($itemId); ?>;
var data = {
	itemId: itemId,
	};

$.ajax({
	type: "POST",
	url: "/intra/status/",
	data: data,
	success: function(){
		console.log(itemId);
	}
});

However, it is only posting the last page's id rendered by the foreach. Have I just overlooked something simple on this?

Link to comment
Share on other sites

Hi @louisstephens!

Are you putting all that js inside a foreach? If so the variable names are the same for each list element. Therefore they get overwritten and you always get the last value in your itemId.

Either change the variables to have index as part of their name (itemId1, itemId2) or (preferably) store the id as a data attribute and write a universal js which will get the corresponding data-attr value for each button click dynamically.

If I totally misunderstood you case, please forgive me and provide some more details.

  • Like 2
Link to comment
Share on other sites

You can use JSON.stringify(data)

Edit:

Sorry ddint read ur post entierly :).

Why dont u for example add data="<?=item->id?>" attribute to each button, then in ur script get the value
 

var itemId = $(this).attr("data");
var data = {
	id: itemId,
};

$.ajax({
	type: "POST",
	url: "/intra/status/",
	data: JSON.stringify(data),
	success: function(){
		console.log(itemId);
	}
});

 

  • Like 2
Link to comment
Share on other sites

Thanks @Ivan Gretsky and @lokomotivan! I meant to respond yesterday, but I got caught up in the code. I actually did go the data-id="" route which I believe will make things much easier to work with in the future. Now I just need to figure out the ajax get side (updating a div once the initial posting of ids is made) and Ill be in business. I appreciate all the help!

  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...