How can I take jquery id in session - php

This is my jQuery code for taking id value when I click itemslist
$(document).ready(function() {
$('.itemslist ul li').click(function()
{ $id = $(this).attr("class");
});
});
But session is not taking that id value
session_start();
$_SESSION['catname'] = $id;
$id= $_SESSION['catname'];
session_destroy();
Can any one please say the answer about this?

You can't assign values to PHP variables from withing Javascript/Jquery. You should make an AJAX call to a PHP file that handles the creation/destroying of the SESSION.
See this answer.

for that you need to call the Ajax to store the session value, given example code here
$(document).ready(function() {
$('.itemslist ul li').click(function() {
var id = $(this).attr("class");
$.ajax({
type : "POST",
url : youphppage.php,
data :"id="+id ,
success: function (msg) {
alert(msg); // you will get stored session value here
}
});
});
});
In your php page while ajax call,
session_start();
$_SESSION['catname'] = $_POST['id'];;
echo $id= $_SESSION['catname'];

you can use ajax for send your id to server page and store your id in session.
$(document).ready(function() {
$('.itemslist ul li').click(function()
{ id = $(this).attr("class");
$.ajax({
type : "POST",
url : Postpage.php,
data :"id="+id ,
success: function (json) {
alert(json);
}
});
});
Server side
session_start();
$id=$_REQUEST['id'];
$_SESSION['catname'] = $id;
$id= $_SESSION['catname'];
session_destroy();

Use jquery ajax to send the data in a php file in post method and retrieve the value on that page
$(document).ready(function() {
$('.itemslist ul li').click(function()
{ var a = $(this).attr("class");
var dataString = 'a=' + a;
$.ajax(function(){
type : "POST",
url : "session.php",
data : dataString,
cache: false,
success: function(data){
alert('session sent!');
}
});
});
});
and the session.php:
session_start();
$a= issest($_POST['a']):$_POST['a']:"";
$_SESSION['catname'] = $a;
session_destroy();

Related

don't retrieve object on php page which passed from ajax call

Hi i don't get retrieve Ajax Data to PhP page its throwing error. i pass data as json object.
The error i'm getting is
Edit.php
$('#regForm').on('submit', function (e) {
var url = document.URL; // Get current url
var id = url.substring(url.lastIndexOf('=') + 1);
var data1 = $("#regForm").serialize();
data = {data:data1,id:id};
console.log(data)
$.ajax({
method:"POST",
url: 'update.php',
dataType : 'json',
data: data,
success: function () {
alert('form was submitted');
}
});
});
update.php
if(isset($_POST["submit"]))
{
print_r($_POST['data']);
// Error::: Undefined index:data in
pass Id using hidden input field and then form data serialize then after you can use by name wise on php page.
$_POST['name'];
Read my comment, then look at this:
JavaScript may look like this
$('#regForm').on('submit', function(e){
var s = location.search.split('&'), serialId = s[s.length-1], idArray = serialId.split('=');
if(idArray.length === 2 && idArray[1].trim() !== '' && idArray[0].match(/^id$/i)){
var serialData = $(this).serialize()+'&'+serialId;
$.ajax({
method:'POST', url:'update.php', dataType:'json', data:serialData},
success:function(jsonObj){
console.log(jsonObj);
}
});
}
e.preventDefault();
});
PHP may look like this
<?php
if($_POST['id']){
// each property as $_POST[propertyHere]
// sending back to JavaScript
$c = new stdClass; $c->someProp = 'some value';
echo json_encode($c); // dataType is json so you should get Object as result
}
?>

Execute php using jquery post

I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard

delete data in sql using ajax and php in XDK

i want to delete a row of data in my sql when delete button is pressed in xdk. i searched for some codes but still doesnt delete the data.
this is the php file (delete.php)
<?php
include('dbcon.php');
$foodid = $_POST['foodid'];
$query = "DELETE FROM menu WHERE id ='$foodid'";
$result=mysql_query($query);
if(isset($result)) {
echo "YES";
} else {
echo "NO";
}
?>
and now here is my ajax code.
$("#btn_delete").click( function(){
alert("1");
var del_id = $(this).attr('foodid');
var $ele = $(this).parent().parent();
alert("2");
$.ajax({
type: 'POST',
url: 'http://localhost/PHP/delete.php',
data: { 'del_id':del_id },
dataType: 'json',
succes: function(data){
alert("3");
if(data=="YES"){
$ele.fadeOut().remove();
} else {
alert("Cant delete row");
}
}
});
});
as you can see, i placed alerts to know if my code is processing, when i run the program in xdk. it only alerts up to alert("2"); . and not continuing to 3. so i assume that my ajax is the wrong part here. Im kind of new with ajax.
<?php
$sqli= "*select * from temp_salesorder *";
$executequery= mysqli_query($db,$sqli);
while($row = mysqli_fetch_array($executequery,MYSQLI_ASSOC))
{
?>
//"class= delbutton" is use to delete data through ajax
<button> Cancel</button>
<!-- language: lang-js -->
//Ajax Code
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
$.ajax({
type: "GET",
url: "deletesales.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
return false;
});
});
</script>
//deletesales.php
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_database = 'pos';
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_database);
$id=$_GET['id']; <!-- This id is get from delete button -->
$result = "DELETE FROM temp_salesorder WHERE transaction_id= '$id'";
mysqli_query($db,$result);
?>
<!-- end snippet -->
A couple of things:
You should be testing using console.log() instead of alert() (imo)
If you open up your console (F12 in Google Chrome) do you seen any console errors when your code runs?
Your code is susceptible to SQL Injection, you will likely want to look into PHP's PDO to interact with your database.
Does your PHP file execute correctly if you change:
$foodid = $_POST['foodid'];
To
$foodid = 1
If number 4 works, the problem is with your javascript. Use recommendations in numbers 1 and 2 to diagnose the problem further.
Update:
To expand. There are a few reasons your third alert() would not fire. The most likely is that the AJAX call is not successful (the success handler is only called if the AJAX call is successful). To see a response in the event of an error or failure, you can do the following:
$.ajax({
url: "http://localhost/PHP/delete.php",
method: "POST",
data: { del_id : del_id },
dataType: "json"
})
.done(function( msg ) {
console.log(msg);
})
.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
More information on AJAX and jQuery's $.ajax can be found here
My "best guess" is a badly formatted AJAX request, your request is never reaching the server, or the server responds with an error.

Pass JavaScript variable to php script

I have 2 files "index.php" and "userip.php". I want to pass the variable varip to the file "userip.php" with ajax. If this is successful I want to share POST['name']; in a session. I thought that the session would be set but when I reload the index.php page the echo shows nothing. Can someone help me out?
index.php (jQuery section):
<script type="text/javascript">
$.getJSON("http://ip.jsontest.com/", function(data) {
var varip = "";
$.each(data, function(k, v) {
varip += v;
$.ajax({
type: "POST",
url: "userip.php",
data: "name="+varip,
success: function(data){
alert("ok");
}
});
});
});
</script>
index.php (php section):
<?php
echo $_SESSION['userip'];
?>
userip.php:
session_start();
if(!empty($_POST['name'])){
$variable = $_POST['name'];
$_SESSION['userip'] = $variable;
}
The problem is that you are missing session_start() in your index.php file, so at that point $_SESSION hasn't been loaded.
But it looks like you're getting the user's IP address?
<?php
echo $_SERVER['REMOTE_ADDR'];
change
data: "name="+varip,
to
data: { name: varip },

how make link without reload all page with jquery

I want create some pages like facebook to load data without changing page/header or chat-bar in footer. I know I can use this code:
$(function() {
$("a.load").click(function (e) {
e.preventDefault();
$("#content").load($(this).attr("href"));
});
});
But I have one problem. I want to give jQuery add-on data like.
go to this profile
so I can do more things with this like:
if (send-more-data=="its-profile-link") {
$id = even-more-data="ID:12235663" //posted on link with jquery
mysql_Query("select * from users where id = $id")
}
elseif {
//////
}
so its possible i send more data with ID in or class or somethings else? Please give me an example. And tell me is it better using .load() or $.ajax()?
Well you can pass get params into link:
$(function(){
$("a.load").click(function (e) {
e.preventDefault();
$("#content").load($(this).attr("href")+"?data1="+$(this).attr("some-data")+"&data2="+$(this).attr("some-more-data"));
});
});
OR
You can use even better - the mighty AJAX:
$(function(){
$("a.load").click(function (e) {
e.preventDefault();
var link = $(this).attr("href");
var param1 = $(this).attr("some-data");
var param2 = $(this).attr("some-more-data");
/* //$.post example
$.post(link, { data1: param1, data2: param2 },function(data) {
$("#content").html(data);
}); */
//or $.ajax - basically the same thing
$.ajax({
url: link,
data: { data1: param1, data2: param2 },
success: function(result) {
$("#content").html(result);
}
});
});
});
Then in php:
if (#$_REQUEST['data1']=="its-profile-link"){
$id = #$_REQUEST['data2'];
$id = mysql_real_escape_string($id); //or $id = (int)$id; if id is always integer.
mysql_Query("select * from users where id = $id")
}
elseif{
//////
}
<a id="my_a" some-data="asd">
console.log($('#my_a').attr('some-data')); // asd
http://api.jquery.com/attr/

Categories