how make link without reload all page with jquery - php

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/

Related

Content fetch in main page from another page from database through ajax

I have written this code but it didn't work. I have searched so much but those code are not properly work. what should I do? I want to fetch data without refreshing whole page.
I have looked at this other question.
$(document).ready(function() {
$("#pair_form").submit(function(e) {
e.preventDefault();
var devicename = $("#devicename").val();
var id = $("#id").val();
var latitude = $("#latitude").val();
var longitude = $("#longitude").val();
var ignition = $("#ignition").val();
var Arming = $("#Arming").val();
function showData() {
$.ajax({
url: 'http://example.com/ddd/cfg.php',
method: 'get',
dataType: 'text',
success: function(response) {
$('#result').html(response)
}
});
}
});
});

How can I select multiple ids generated by a loop dynamically in Jquery and pass them to AJAX?

Ok , I am trying to get different id values through Jquery , and pass them to Jquery AJAX that will hit a PHP file so I can get some data back .... I'm not sure how to get all the multiple different ids because Jquery is only getting the first id of many of the unique id values generated by the while loop .. and I would like each unique ID to also be passed to the AJAX function in Jquery .. Your help would be so much appreciated . I'm still new to the Jquery world
<?php
require('../database/connection.php');
?>
<script type="text/javascript">
jQuery(document).ready(function() {
var ID = $('div#opposition img').attr("id"); alert(ID);
$.ajax({
type:'GET',
url :'get_users_images.php',
data:'screen_name='+ ID,
success: function(result){
$('div#opposition img').attr('src', result);
}
});
});
</script>
<?php
$select2 = "SELECT * FROM AUTHORS WHERE ID <> $id";
$result2 = mysql_query($select2);
$result_count = mysql_num_rows($result2);
echo '<div id ="opposition">';
while ($row2 = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo "<img id ='".$row2['Twitter']."' src='images/ajax-loader.gif' class ='image".$row2['Twitter']."'/>"; // echos different ids,
}
?>
</div>
You can send an stringified array of id's like this -
jQuery(document).ready(function () {
var ID = $('div#opposition img').map(function(){
return this.id;
}).get();
$.ajax({
type: 'GET',
url: 'get_users_images.php',
data: { screen_name : JSON.stringify(ID)},
success: function (result) {
$('div#opposition img').attr('src', result);
}
});
});
If I am correct, Actually , why you are placing the set of images returned by php in one
img tag, $('div#opposition img').attr('src', result); . Rather I think you must do something like $('div#opposition').innerHTML(result) .

Post ajax to PHP - variable isn't being uploaded

I am trying to pass a variable from my ajax to my php script. I can't see to get it to work. It keeps on giving me NULL when I do a var_dump on the variable.
JQUERY:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: id
});
LinkUpload(id);
function LinkUpload(id){
$("#link-upload").dialog();
}
});
});
</script>
PHP:
$id = $_POST['id'];
$query = mysql_query("SELECT * FROM xcart_slideshow_slides where slideid='$id'")or die(mysql_error());
$sli = mysql_fetch_array($query);
$slide_id = $sli['slideid'];
$link = $sli['link'];
var_dump($id);
I need the $id variable to post so I can dynamically change the dialog box when the click function is activated.
EDIT:
So I have changed some of my coding:
Jquery:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.post(
"slide-show-link.php",
{ id: id },
function(data,status){alert("Data: " + data + "\nStatus: " + status); }
);
// alert(id);
LinkUpload(id);
});
function LinkUpload(id){
$("#link-upload").dialog();
}
});
I wanted to see if the data was in fact being passed so I threw an alert in the .post. This is the error I'm getting now:
I have tried passing plain text and echoing it back on the page but it fails. It is just not passing.
Try this -
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: { id : id }
});

How can I take jquery id in session

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();

How to continuously update a part of the page

http://pastebin.com/dttyN3L6
The file that processes the form is called upload.php
I have never really used jquery/js so I am unsure how I would do this or where I would put the code.
It has something to do with this setInterval (loadLog, 2500);
Also, how can I make it so the user can submit a form without the page refreshing?
$.ajax({
type: "POST",
url: "upload.php",
data: dataString,
success: function() {
}
});
return false; `
and
<?php
$conn1 = mysqli_connect('xxx') or die('Error connecting to MySQL server.');
$sql = "SELECT * from text ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn1, $sql) or die('Error querying database.');
while ($row = mysqli_fetch_array($result)) {
echo '<p>' . $row['words'] . '</p>';
}
mysqli_close($conn1);
?>
</div>
<?php
if (!isset($_SESSION["user_id"])) {
} else {
require_once('form.php');
}
?>
You can submit a form without refreshing a page something like this:
form.php:
<form action='profile.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='result'>Result comes here..</div>
profile.php:
<?php
// All form data is in $_POST
// Now perform actions on form data here and
// create an result array something like this
$arr = array( 'result' => 'This is my result' );
echo json_encode( $arr );
?>
jQuery:
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
// loop to set the result(value)
// in required div(key)
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
And If you want to call an ajax request without refreshing page after a particular time, you can try something like this:
var timer, delay = 300000;
timer = setInterval(function(){
$.ajax({
type : 'POST',
url : 'profile.php',
dataType: 'json',
data : $('.ajaxform').serialize(),
success : function(data){
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
}, delay);
And you can stop the timer at any time like this:
clearInterval( timer );
Hope this will give you a direction to complete your task.
This is pretty simple.
To access elements using Jquery you use css selectors, for example, to get value of an input field with name "foo" you do the following:
var fooVal = $("input[name=foo]").val();
To send it over to the server you are to append an event listener (for example, click) to the submit button/any other element
var data = { varName : fooVal };
var url = "http://example.com";
var responseDataType = "json";
function parseResponse(JSON)
{
// your code handling server response here, it's called asynchronously, so you might want to add some indicator for the user, that your request is being processed
}
$("input[type=submit]").on('click', function(e){
e.preventDefault();
$(this).val("query processing");
$.post(url,data, parseResponse, responseDataType);
return false;
});
If you want to do constant updates, you can, of course, add timers or some other logic. But I hope you get the idea of how to proceed to such cases;
To answer part of your question, you can use ajax.
<html><head></head><body>
<div id="feed"></div>
<script type="text/javascript">
var refreshtime=10;
function tc()
{
asyncAjax("GET","upload.php",Math.random(),display,{});
setTimeout(tc,refreshtime);
}
function display(xhr,cdat)
{
if(xhr.readyState==4 && xhr.status==200)
{
document.getElementById("feed").innerHTML=xhr.responseText;
}
}
function asyncAjax(method,url,qs,callback,callbackData)
{
var xmlhttp=new XMLHttpRequest();
//xmlhttp.cdat=callbackData;
if(method=="GET")
{
url+="?"+qs;
}
var cb=callback;
callback=function()
{
var xhr=xmlhttp;
//xhr.cdat=callbackData;
var cdat2=callbackData;
cb(xhr,cdat2);
return;
}
xmlhttp.open(method,url,true);
xmlhttp.onreadystatechange=callback;
if(method=="POST"){
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send(qs);
}
else
{
xmlhttp.send(null);
}
}
tc();
</script>
</body></html>

Categories