Sending a global variable - php

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!

Related

Pass input value to ajax get Laravel

I am fairly new to Laravel and ajax in general, what I am trying to implement is to pass the value of an input field through an ajax get request.
My request looks like this:
function getInfo() {
$.ajax({
url: "info",
dataType: "json"
}).success(function(data){
$('#result').append(JSON.stringify(data));
}).fail(function(){alert('Unable to fetch data!');;
});
}
$('#infoSubmit').click(getInfo);
I have setup a route for my function in laravel that works like this
public/info/Variable <--
When I add a variable after info/
I get the data for that variable (e.g profile name)
I need to pass this variable from an inputfield to ajax request to something like this:
url: "info/+$inputfieldVariable"
Change:
url: "info",
TO:
url: "info/" + $('input-field-selector').val(),
Not sure about the correctness of your JS code: Shouldn't you be using done instead of success?
JavaScript:
function getInfo() {
var myFieldsValue = {};
var $inputs = $("#myForm :input");
$inputs.each(function() {
myFieldsValue[this.name] = $(this).val();
});
$.ajax({
url: "info",
dataType: "json",
data: myFieldsValue,
type: "GET" // Even if its the default value... looks clearer
success: function(data){
$('#result').append(JSON.stringify(data));
},
error: function(){
alert('Unable to fetch data!');
}
});
return false;
}
$('#infoSubmit').click(getInfo);
Untested but should be something like that

Serialize() form in an existing ajax function

Actually the following function works fine, but now I need to add other variable in order to return from the php file the right statement.
function sssssss1(page) {
loading_show();
$.ajax({
type: "GET",
url: "load_data.php",
data: "page=" + page,
success: function (msg) {
$("#search").ajaxComplete(function (event, request, settings) {
loading_hide();
$("#search").html(msg);
});
}
});
}
I need to add the following two variable to be read by my php file. I have tried different solution, but nothing seem working
var form2 = document.myform2;
var dataString1 = $(form2).serialize();
How to add those variable in my existing function? Any idea?
You can send object as data,
this line:
data: "page="+page,
could be
data: {mypage:"page="+page, form2:document.myform2, dataString1:$(form2).serialize()}
and your PHP can get it like:
$page = $_GET['mypage'];
$form2 = $_GET['form2'];
$dataString = $_GET['dataString1'];
Hope it Help.

Ajax Submit using PHP and mysql

There are may button son php page. I want to submit value of button and the delete record from table using that value. Ajaxz code is
$('#product-table td #delete').live("click", function () {
var doDelete = confirm('Are you sure you want to delete this record?');
deleteLinkObj = $(this);
if (doDelete) {
var id = $(this).attr('accesskey');
$("#deleteid").val(id);
$.ajax({
url: "purchase.php",
data: {deleteid:id},
dataType: 'html',
success: function() {
}
});
}
else { return false; }
});
On PHP I am trying to use value of deleteid but its not coming
PHP code is
if(#$_POST['deleteid']!="")
{
$sql="delete from purchasedetails where purchaseid='".$_POST['deleteid']."'";
if(!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
else
{
$msg="Data is deleted";
}
}
I have tried usinng isset($_POST['deleteid']) then also its showing error
In your ajax call you aren't setting the request method to POST, therefore it will default to GET, that is why your post var is never present:
$.ajax({
type: 'POST',
url: "purchase.php",
data: {deleteid:id},
dataType: 'html',
success: function() {
}
});
As a quick fix for your SQL Injection vulnerability you can cast the id as int, but you should consider upgrading to PDO or MySQLi because the library you're using is deprecated.
$sql="delete from purchasedetails where purchaseid='".(int)$_POST['deleteid']."'";
Storing your purchaseid as the elements accesskey is not the best place, it would be better as a data-myid attribute, so you can access it with $(this).data('myid').
By default $.ajax take type as GET, hence you need to define the type in you code
You can try like this $.ajax syntax-
$.ajax({
url: "purchase.php",
data: $("#deleteid").val(id),
type: POST
dataType: 'html',
success: function() {

JQuery: How to apply this click function to all elements of the same class on the page?

My page consists of a list of records retrieved from a database and when you click on certain span elements it updates the database but at present this only works for the first record to be displayed.
(Basically changes a 0 to 1 and vice versa)
These are my two html elements on the page that are echoed out inside a loop:
Featured:<span class="featured-value">'.$featured.'</span>
Visible:<span class="visible-value">'.$visible.'</span>
Here is what I have:
$(document).ready(function() {
$('.featured-value').click(function() {
var id = $('.id-value').text();
var featured = $('.featured-value').text();
$('.featured-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$('.featured-value').html(data);
$('.featured-value').fadeIn('slow');
}
});
return false;
});
// same function for a different span
$('.visible-value').click(function() {
var id = $('.id-value').text();
var visible = $('.visible-value').text();
$('.visible-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&visible="+visible,
success: function(data) {
$('.visible-value').html(data);
$('.visible-value').fadeIn('slow');
}
});
return false;
});
});
It was working fine with one using id attributes but now I'm using class the fadeIn part of the success query isn't working but I'm hoping the .each will fix this.
UPDATE
The full loop is as follows:
while ($event = $db->get_row($events, $type = 'MYSQL_ASSOC'))
{
// open event class
echo '<div class="event">';
echo '<div class="id"><span class="row">Event ID:</span><span class="id-value"> '.$id.'</span></div>';
echo '<div class="featured"><span class="row">Featured: </span><span class="featured-value">'.$featured.'</span></div>';
echo '<div class="visible"><span class="row">Visible: </span><span class="visible-value">'.$visible.'</span></div>';
echo '</div>';
}
Cymen is right about the id selector causing you trouble. Also, I decided to refactor that for you. Might need some tweaks, but doesn't everything?
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
The click function is getting the same id and value on each click because you've bound it to the class. Instead, you can take advantage of event.target assuming these values are on the item being clicked. If not, you need to use event.target and navigate to the items within the row.
$('.featured-value').click(function(event) {
var $target = $(event.target);
var id = $target.attr('id');
var featured = $target.text();
$target.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$target.html(data).fadeIn('slow');
}
});
return false;
});
So something like that but it likely won't work as it needs to be customized to your HTML.

jQuery each() results to array to php to database

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) {}
});
}
});

Categories