jQuery each() results to array to php to database - php

Basically what I am doing is making a sort of invitation system, the user clicks on users and they go into a list, that all works, I can get the ids of them using each() but I need to pass it through jQuery Ajax to php to send it to the database for notifications. This is basically what I have:
$(".group-video-create").click(function(){
var url = $(".group-input-url").val();
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var checked_url = url.match(exp,"<a href='$1'>$1</a>");
if(checked_url)
{
$("#group-input-names li").each(function(){ // This is the relevant code
var user_id = $(this).attr("id"); // Here too
}); // & here
if(user_id)
{
$.ajax({
type: "POST",
//url: "",
//data: "", //this would be an array of all of the ids, (could be 1, could be 100).
cache: false,
success: function(html){
///Once all invitations have been sent to the database it would then load a new div and hide the previous one.
}
});
}
}
});
if you want to see what I'm trying to accomplish just go here:
http://www.kithell.com/#/video
usr: PhpFreak#yahoo.com
pass: phpfreaklogin
It's under Group Video. (You should be automatically directed there once logged in)

You might be able to use jQuery.serialize to bundle up all of your form data. Also, jQuery.post is a nice shortcut for doing a POST request with jQuery.ajax.
A rough example might look this:
$.post( '/my-ajax-service.php',
$('#MyForm').serialize(),
function(data, txtStatus, jqXHR) {
//Do stuff
});

Here is one possibility
http://jsfiddle.net/nickywaites/9GZ2e/
$(function() {
//I would use jQuery Map to build Array
//http://api.jquery.com/map/
var ids = $("#group-input-names li").map(function() {
return $(this).attr("id");
}).get(); //Get Required to convert to regular javascript array
console.log(ids);
var invites = {}
invites.users = ids;
//Then use JSON.stringify() to pass array to server
//https://github.com/douglascrockford/JSON-js
if (ids.length > 0) {
$.ajax({
type: "POST",
//url: "",
data: JSON.stringify(invites),
cache: false,
success: function(html) {}
});
}
});

Related

How would I pass in various types of data via AJAX .post()?

I am trying to pass in mutliple data into AJAX .post(). This is what I've done so far:
$('form#tutorTableForm').live('submit', function()
{
var cid = $('#courseSelect').val();
var lid = $('#lessonSelect').val();
var lessonCount = $('#lessonSelect option:selected').attr('id');
$.post('', $(this).serialize(), function(response){
alert(response);
});
return false;
});
I want to also pass in cid and lid. How would I do that?
I'm using live instead of on because our app is using the old version.
I guess you could create an object that contains all the data, like this:
var cid = $('#courseSelect').val();
var lid = $('#lessonSelect').val();
var lessonCount = $('#lessonSelect option:selected').attr('id');
var postdata = {
formdata: $(this).serialize(),
cid: cid,
lid: lid
};
$.post('', postdata, function(response){ alert(response); });
place them inside the form as input hidden or whatever and the serialize should add them automatically. without seeing your html it's a bit difficult to see exactly what you need.

jQuery.ajax() success callback store data to return

I'm trying to get some data from a PHP script in a project right now. All examples I found searching for AJAX callback functions "use" the data already in the callback itself, but I want to fetch data and store it in a way ready to be returned.
function getEle (id) {
var element = [];
$.ajax({
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id;
element[1] = content;
// if I alert(element[1]); here it will work!
}
});
alert(element[1]); // here it just won't :/ ("undefined")
return element;
}
Somewhere in my script some function needs to getEle(ments) but all I get is undefined.
is there a way to do what I want? Or is there maybe a better way to do this?
A solution would be to pass a callback function to getEle():
getEle(id, callback){
$.ajax({
/* some options, */
success: function(){
var content = data;
element[0] = id;
element[1] = content;
callback(element);
}
})
}
And then pass a function containing the code of what to do when you have the element content:
getEle('myId', function(element){
alert(element[1]);
});
Two things are failing here:
Variable scope - You define the variable content inside the AJAX callback. This makes it inaccessible from the surrounding code. You could omit the var and just write content = data which makes it accessible globally.
Asynchronicity - Becaus AJAX is asynchronous the script following the callback will be executed before the callback was executed. The only way to solve that problem is to use the callback as it's intended to.
Take a look at this.
function getEle (id, callback) {
var element = [];
$.ajax({
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id;
element[1] = content;
callback(element);
}
});
}
}
getEle ("someID", function(someElement) {
alert(someElement);
});
Here's what's happening in your code:
the array "element" is initialized.
the AJAX call is made with a success callback function
while it's waiting for that AJAX to run, it goes ahead with the rest of your code and alerts element[1], which doesn't exist yet
the success callback runs and populates the array "element".
You might consider a global variable to solve this:
var element = [];
function getEle (id) {
$.ajax({
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id; // the global "element" is set
element[1] = content;
}
});
}
// element[0] will exist now, but only after the AJAX call is complete
Alternatively, you could turn your AJAX into a synchronous call:
function getEle (id) {
var element = [];
$.ajax({
async: false, // forces synchronous call
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id;
element[1] = content;
}
});
alert(element[1]); // now it is set
return element;
}
The only other option I can see is to keep everything tied up inside the "success" callback, which you already discovered works fine.
Your callback executes some time after the rest of your code finishes.
You need to pass the value back using a callback, the way $.ajax does.
Your alert ends up being undefined because the AJAX call is asynchronous. So while that AJAX call is waiting for the server's response, the script continues on to the alert, at which point element[1] is not yet defined.
You should place your return element line inside of the success callback function.

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Sending a global variable

I have a piece of Javascript that forwards a users' selected information to an external PHP file, and returns information. In the code below, you can see it sends {'report' : report} via POST to that file. That works fine.
Essentially I need to add another variable to be sent. It's called 'id', but it's in another function. Is there a way to make that variable global and then incorporate it so it's sent in my code snippet? (and when will the global variable be cleared?)I can also send it via the 'url' attribute, and use GET in my PHP...just not sure how to implement.
$('#adminSelectReport a').live("click", function () {
//Get id from clicked link:
var report = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': report
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
UPDATE: Here is the other snippet that sends 'id' to another page, getting information. I need to retain this ID, however, and use it on my original code.
$('#adminSelectCompany a').click(function() {
//Get id from clicked link:
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {'id': id},
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg);
$('#adminSelectReport').fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
So it sounds like they select a Company via a link, then they select a Report via another link, and you need to remember which Company was selected.
In order to avoid global variables, I'd probably just add a class to the selected Company link, and then fetch that element by the selected class, and grab its ID. You could use the class for styling as well if that's needed.
var companies = $('#adminSelectCompany a');
companies.click(function () {
// remove class from previously selected, and add to new one
companies.filter('.selected').removeClass('selected');
$(this).addClass('selected');
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {
'id': this.id
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg)
.fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
$('#adminSelectReport a').live("click", function () {
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': this.id,
'company': $('.selected')[0].id
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
You can achieve this by assigning the value as a property of JavaScripts "global" namespace called window. Simply assign the id you want to make global to window.my_id, then refer to it in the click callback.
Note: If you're setting the global variable in another function, remember to check for its existance in the function that will use the variable, ie: var my_id = null; if (window.my_id != undefined) { my_id = window.my_id; }
Here's an implementation:
$('#adminSelectReport a').live("click", function () {
//Get id from clicked link:
var report = $(this).attr('id');
var company = window.report_company_id != undefined ? window.report_company_id : null;
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': report,
'company': company
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
.
$('#adminSelectCompany a').click(function() {
//Get id from clicked link:
var id = $(this).attr('id');
window.report_company_id = id;
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {'id': id},
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg);
$('#adminSelectReport').fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
Lastly I would advise against global variables if possible, or at least minimize the usage by wrapping common function/purposes in objects and prefixing the names with the project name or something.
Change
data: { 'report': report },
To
data{ 'report': report, 'id': YOUR ID },
Why don't you send the second variable like that:
data: {'report': report, 'id': your_id },
edit: arf too slow!

jQuery AJAX referencing $(this) within success function

I have a voting system which sends an id of the clicked item to a PHP script, the PHP updates the database and echos back the new vote counts via an JSON encoded array.
This is the jQuery:
$(".vote_up").click(function(){
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
$(".votes_up").find(id).html(data[x].vote_up);
$(".votes_down").find(id).html(data[x].vote_down);
}
}
});
});
So when i construct the item in the first place, i take the record ID in the database and set it as the items ID. So what i'm trying to do is reference the exact item that was clicked and set it's HTML to the data thats coming back from the PHP. I've checked in Firebug and I'm getting correct data back but the count of votes isnt changing. Any ideas?
This is the PHP for reference:
$query = "SELECT vote_up, vote_down FROM posts WHERE id = '".$id."'";
$result1 = mysql_query($query);
$output = Array();
while ($row = mysql_fetch_array($result1)){
$output[] = Array(
"vote_up" => $row['vote_up'],
"vote_down" => $row['vote_down'],
);
}
echo json_encode($output);
If you just want this in the success: callback to refer to the element that was clicked, just set the context: property for the AJAX request.
$.ajax({
context: this, // set the context of the callbacks
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data) {
// now "this" refers to the element that was clicked
}
You can test it by doing something a little more generic, like:
$(this).html("yep, it works");
... then if that works, consider that it doesn't really make sense to do .html() on the same element in a loop, because each time .html() overwrites the entire content.
Use .append() instead if you're appending data from the loop:
for(var x in data) {
$(this).append(data[x].vote_up);
$(this).append(data[x].vote_down);
}
Wouldn't:
$(".votes_up").find(id).html(...);
Really just need to be:
$('#' + id).html(..);
If you define a variable within the click() method callback, you'll be able to reference it within your ajax success callback. Something similar to this should do you:
$(".vote_up").click(function(){
// Assign the clicked element to a scoped variable...
var target = $(this);
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
// Then refer to it within your callback
target.html(data[x].vote_up);
target.html(data[x].vote_down);
}
}
});
});

Categories