I am working on a project and am stuck. I am new to jQuery and JSON and I want to grab the current logged in user. I am able to pull the all the information from the user table, but I just want the user name so I can display it. I want to eventually append the current user to a html element
js code
var getUser = function(){
$.ajax({
url: 'xhr/get_user.php',
type: 'get',
dataType: 'json',
success: function(response){
if(response.error){
console.log(response.error);
}else{
console.log(response);
//$('#current_user').append(response);
}
}
});
};
php code
<?php
// check if logged in
// per project or all tasks?
//
error_reporting(E_ALL);
session_start();
session_regenerate_id(false);
require_once("reqs/common.php");
require_once("reqs/pdo.php");
//require_once("reqs/auth.php");
checkLoggedIn();
$userID = param($_GET, 'userID', $_SESSION["user"]);
$dbh = new PDB();
$db = $dbh->db;
$user = $dbh->getUser($userID);
exitjson(array("user"=>$user));
?>
Just use $.getJSON
$.getJSON("xhr/get_user.php",function(userData){
console.log(userData);
}).fail(function(xhr,textStatus,err){
console.log("error",err);
});
And remember to add JSON type header to php respond.
An example of PHP:
header('Content-type: application/json');
echo json_encode($user);
Related
I have error ->
"Failed to load resource: the server responded with a status of 405
(Method Not Allowed)"
when send Ajax data to PHP in larval.
(I made route)
Ajax code
function insertData()
{
var text = document.getElementById('humanText').value;
var user = document.getElementById('userName').innerText;
$.ajax({
type:"POST",
url: "insertContentData",
data:{text:text, user:user},
success: function(data){
alert(data);
}
});
document.getElementById('humanText').value = "";
};
insertData();
and my php code "insertContentData.php"
<?php
$data = $_POST['text'];
$user = $_POST['user'];
echo $data.", ".$user;
?>
why not work this?
Thanks for your help.
In the http world the "METHOD" normally used is "GET" which is simply pulling data from the server. When you want to send data from the user to the server you used "POST". These are the two most commonly used methods.
The errors says that the METHOD IS NOT ALLOWED. You are AJAX code shows that you are using the POST method.
In Laravel you need to define a route that allows for the POST method. So instead of Route::get($uri, $callback); it would be Route::post($uri, $callback); Some more information can be found in the Laravel Routing documentation. However I think you are missing some concepts based on the primitive PHP code you posted, that code should be inside a controller.
Try to run like this. I hope it works.
function insertData(){
var text = document.getElementById('humanText').value;
var user = document.getElementById('userName').innerText;
$.ajax({
type:"POST",
url: "insertContentData",
data:{text:text, user:user},
success: function(data){
alert(data);
}
});
document.getElementById('humanText').value = "";
};
window.onload = function(){
insertData();
}
<?php
$data = $_POST['text'];
$user = $_POST['user'];
echo $data.", ".$user;
?>
I want to send fields data from a form to a file via AJAX and I found this solution online: http://techglimpse.com/pass-localstorage-data-php-ajax-jquery/
The only problem is that I have multiple fields instead of a single field and I want to save the output (localStorage) in an HTML (or any other format) file instead of showing it in an #output div.
How can I do that?
You can see my work that I've done till now here: Save form data using AJAX to PHP
And here's my HTML/JS code: http://jsbin.com/iSorEYu/1/edit & PHP code http://jsbin.com/OGIbEDuX/1/edit
PHP:
<h1>Below is the data retrieved from SERVER</h1>
<?php
date_default_timezone_set('America/Chicago'); // CDT
echo '<h2>Server Timezone : ' . date_default_timezone_get() . '</h2>';
$current_date = date('d/m/Y == H:i:s ');
print "<h2>Server Time : " . $current_date . "</h2>";
$dataObject = $_POST; //Fetching all posts
echo "<pre>"; //making the dump look nice in html.
var_dump($dataObject);
echo "</pre>";
//Writes it as json to the file, you can transform it any way you want
$json = json_encode($dataObject);
file_put_contents('your_data.txt', $json);
?>
JS:
<script type="text/javascript">
$(document).ready(function(){
localStorage.clear();
$("form").on("submit", function() {
if(window.localStorage!==undefined) {
var fields = $(this).serialize();
localStorage.setItem("eloqua-fields", JSON.stringify( fields ));
alert("Stored Succesfully");
$(this).find("input[type=text]").val("");
alert("Now Passing stored data to Server through AJAX jQuery");
$.ajax({
type: "POST",
url: "backend.php",
data: fields,
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
</script>
NOTE: Replace the file format of your_data file to html in the PHP code if you want your JSON data in HTML format.
You are overcomplocating things. The check for localStorage can be way simpler (other options). jQuery has a serialze() function that takes all form elements and serializes it. You can store them under "eloqua-fields" so you can find it again. No need to do some fancy random retrival.
I'd like to add that not all of you code makes sense. Why use localstorage if you clear it every time the DOM is ready? Your validation does not abort the sending process if there are errors but I assume you just want to play around with stuff.
$(document).ready(function(){
localStorage.clear();
$("form").on("submit", function() {
if(window.localStorage!==undefined) {
var fields = $(this).serialize();
localStorage.setItem("eloqua-fields", JSON.stringify( fields ));
alert("Stored Succesfully");
$(this).find("input").val(""); //this ONLY clears input fields, you also need to reset other fields like select boxes,...
alert("Now Passing stored data to Server through AJAX jQuery");
$.ajax({
type: "POST",
url: "backend.php",
data: {data: fields},
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
For the server part if you just want to store your data somewhere.
$dataObject = $_POST['data'];
$json = json_decode($dataObject);
file_put_contents('your_data.txt', $json) ;
How to make an animated table only animate when a new record is added to the database.
Ajax/Js (in index.php):
$.ajax({
url : 'Not sure what goes here?',
data : {Not sure what goes here?},
dataType : 'application/json', // Is this correct?
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
var newitem = function(response){
var item = $('<div>')
.addClass('item')
.css('display','none')
.text(response)
.prependTo('#scroller')
.slideDown();
$('#scroller .item:last').animate({height:'0px'},function(){
$(this).remove();
});
}
My php (latest.php):
include ('db.php');
$sql2 = "SELECT * FROM `feed` ORDER BY `timez` DESC";
$res2 = mysql_query($sql2) or die(mysql_error());
while($row3 = mysql_fetch_assoc($res2)){
$user = $row3['username1'];
$action = $row3['action'];
$user2 = $row3['username2'];
echo ''.$user.''.$action.''.$user2.'<br>'; // Needs to be a json array?
I can't get this to work, here's how the table operates http://jsfiddle.net/8ND53/ Thanks.
$.ajax({
url : your_php_file.php',
data : {data you'r going to send to server}, // example: data: {input:yourdata}
success: function(response) {
$('#table_id').append('<tr>'+response+'</tr>'); // response is the date you just inserted into db
}
});
in your_php_file.php:
add the item into db
echo that inserted data # if you echo, then you can catch this with ajax success function then you append it into your table.
try to fill as below:
$.ajax({
type: "post"
url : 'locationOfphpCode/phpCode.php',
data : {data you want to pass}, //{name: "dan"}
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
in your php code you need to receive the data you have passed from the ajax call:
<?php
$name = $_POST['name'];
...
?>
you may add some validations in your php code.
hope this will help you.
the example you have given is using setInterval(newitem, 2000)
so you have to call ajax function on some fixed interval.
I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.
When I set the session in a file called signin.php:
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'array.php',
type: 'post',
data: {'user': $user}
});
";
In another file (index.php), I want to get:
<?php
session_start();
echo "log in as <span id=\"user\"></span><br/>";
$user = $_POST['user']
echo "
<script>
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
</script>
";
?>
I know I completely messed up with the code. What I want is that when the session is set in the signin.php file, I want $user in the content in "log in as $user" automatically updated without refresh the page, any help will be greatly appreciated!
First, work on diligently formatting your code more effectively. That code you posted was all over the place. This is a bad practice to get in and leads to errors, bugs, and other effects which can be difficult find due to the formatting.
If I follow what you're doing, when someone logs in and then hits the index.php page, you want to be able to load a user's information from another file that will give back the user data asynchronously?
signin.php
Your code is confusing in what it appears to be doing; you simply have not told us enough both in code and explanation to understand what the workflow entails.
For instance, in signin.php, you're echoing a <script> tag that does an $.ajax() request, but who/what get's this code? Is this part of the signin.php content, if the user successfully logs in? Does this mean the signin.php will load the page to use the $.ajax() here, or is that meant to run from the $.ajax() on success?
If it's the latter, you need to return regular Javascript with no markup (like a <script> tag wrapped around it) and use dataType: 'script' in the options.
Also, I would at least use a more descriptive word than array.php; if you're getting user data from it, name that file something like userdata.php.
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
dataType: 'script',
data: 'json=' + jQuery.serialize({user: '$user'})
});
";
Then in userdata.php, you can access it with $_POST['json'].
index.php
This honestly makes no sense:
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
);
Why is the setInterval() in an anonymous function that's run while setting $.text()? This is one of those What? moments, where I'm not even sure what you're trying to accomplish.
Before that though, you have:
$user = $_POST['user'] <<< Note here, you need a ; at the end
Why is this a $_POST? Does the signin.php use $_POST to log a user in? Here, I believe you want $_SESSION (I think, hope, ??), since that's where you stored the username when the user logged in using signin.php.
This is my best guess as to what you're trying to do (assuming you're returning JSON-formatted data):
<?php
session_start();
$user = $_SESSION['user'];
echo "log in as <span id=\"user\"></span><br/>";
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
data: 'json=' + jQuery.serialize({user:'$user'}),
dataType: 'json',
success: function(data){
$('#user').text(data.fullname);
}
});
</script>
";
?>
Try the following:
<?php
$user = 'john';
$_SESSION['user'] = $user;
?>
<script type="text/javascript">
$.ajax({
url: 'array.php',
type: 'post',
data: { 'user': <? echo json_encode($user) ?> }
});
</script>