this is the method to get userinfo from gmail. i dont know how to pass username values to code behind can any one help ..
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken/acToken,
data: null,
success: function (resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
I think you need the response you got from ajax call in the code behind. For that you have to set the value to a hidden field. So that you can access the values in code behind using its ID.
You can use this code if you are working with ASP .net
HTML code --
<asp:hiddenfield ID="user" runat="server"></asp:hiddenfield>
Jquery
$("#user").val(user); // Add data to html field
CodeBehind
Object user = user.Value;
Related
JAVASCRIPT
$(document).ready(function() {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id);
$.ajax({
url: "m/a/a.class.php",
method: "POST",
data: {pId: p_id},
success: function (data)
{
console.log(data); //<------ this gives me an empty output
alert("success!");
}
});
});
});
I am trying to get a the id of a selected value out of the selectpicker, when i change the selectpicker, i get the alert "success!" and in the console it shows the result, which is correct. When i want to use this result in PHP, which i am using ajax for, it gives me an odd output so i can't use the variable for the following sql statement.
What am i doing wrong? For you to understand i want to get the post input for product, so i can filter the next selectpicker by the id of "product", so i want to get dependant selectpicker "onchange". I already read many other questions, and it works in other examples when i use something like this in the success function:
success: function (data)
{
$('#state').html(data);
}
But this isn't working for my example here, because when i use the "$_POST['produkt_id']" it either gives me an empty query or it has a mistake in it, since it passes the data from my screenshot. Thanks in advance and feel free to ask questions.
UPDATE:
This is where I am trying to get the previous input.
case 'linie':
if(isset($_POST['pId'])) {
$t = $_POST['pId'];
$sql = 'SELECT id, bezeichnung '
. 'FROM l "
. 'LEFT JOIN ' .produkte p ON p.id=l.p_id '
. 'WHERE l.p_id =' . "$t" . 'AND l.deleted=0 AND p.deleted=0 '
. 'ORDER BY l.bezeichnung ';
break;
}
the error says it. PHP you're using is calling "include_once" and the file which you're trying to include, doesn't exist.
that makes the PHP to return a response with error in it, and the response - because of that error text - is not a valid JSON anymore.
In your ajax code you should put your url route path for file request it hink you put the file path of your project system that's why your ajax file could not find and include your file for ajax request execution
$.ajax({
url: "modules/ausschuss/ausschuss.class.php", //remove this
url: "full url for your file execution"
method: "POST",
data: {produkt_id: produkt_id},
success: function (data)
{
alert("success!");
}
});
I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>
I have a function here from a change event on a dropdownlist. When the selection gets changed I want to update a row in my database. Should I use javascript or ajax. I don't want the page to be refreshed. I think it should be ajax, but not sure? If ajax, can anyone point me to a tutorial/video/etc?
Here is where I want to update my db row.
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function(event) {
// call db and update row
}, false);
Looks like you using asp.net mvc.
You can write your ajax calls with pure javascript Ajax docs or the easiest way, using JQuery.
You need to add one action on your controller to receive the ajax data, and then insert/update your db.
See this, this and this.
Most common scenario would be making an ajax call using HTTP POST/PUT to a controller method, which would then handle the data and update the database directly or pass through to your service/data layer code.
Probably the easiest way to make the call would be using the jQuery.ajax method. Documentation can be found here: http://api.jquery.com/jquery.ajax/
You can try something like this
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
var name = $('#TextBox1').val();
var email = $('#TextBox2').val();
if (name != '' && email != '') {
$.ajax
({
type: 'POST',
url: 'Home/UpdateDB', //if it is plain asp.net then UpdateDB is declared as WebMethod
async: false,
data: "{'name':'" + name + "','email':'" + email + "'}",
contentType: 'application/json; charset =utf-8',
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#TextBox1').val('');
$('#TextBox2').val('');
alert("Data Saved Successfully");
}
},
error: function (result) {
alert("Error Occured, Try Again");
}
});
}
})
});
</script>
fg
iuou
uouienter link description here
uiouidfgsdfgddfgdfgdfgdgdgd##
Heading
##*
uio
uiopomkl
hjlkdsg
dsf
dfgdg
Blockquote
I have a simple ajax request which get from server a generated HTML, like:
$.ajax({
url: '/GetData'
type: "POST",
dataType: "html",
data: ...,
success: function(data) {
// here I want to change `name` attributes of inputs
// before print on page
// but it doesn't work, so, how to manage this ?
$(data).find("input[name='test']").prop("name", "anotherValue");
$("myDiv").prepend($(data));
}
});
and my action is simple:
[HttpPost]
public ActionResult GetData(){
return PartialView("myview", new MyModel());
}
I want to change input name attributes before print them in html page. If I do in success function (see above) then no change is made.
Why ? To to achieve this ?
try something like
$("input").each(function() {
if($(this).prop("name") == "test") $(this).prop("name", "anotherValue");
});
Data cannot be edited unless you append them to the DOM
So, use String.Replace function
var removed=data.replace("name='test'","anotherValue")
.replace('name="test"',"anotherValue");
$("myDiv").prepend(removed);
or do this
$(data).prependTo("myDiv").find("input[name='test']").prop("name", "anotherValue");
I'm trying to implement voting very similar to Stack Overflow's. There are multiple items that all have a vote button next to it. Currently, I have it working, but it's done server side, posts back, and takes a while to reload the data. Here is the flow:
You click the vote button,
it fires a javascript function which clicks a hidden ASP.NET button (did it this way because there are multiple vote buttons per page),
the button fires,
it updates the database, and then
the page posts back and refreshes, showing the update.
How do I leverage javascript and AJAX to eliminate this bad user experience? I want it to work like Stack Overflow's, but I'm not using MVC. Any help, examples, suggestions would be great. Thanks.
Update:
I have this implemented, but when I place breakpoints on the Web Method it doesn't even fire and I always get the error alert. Any ideas?
javascript:
<script type="text/javascript">
$(document).ready(function () {
$("[id^=VoteMeUp]").click(function (event) {
var dta = '{ "VoteId":' + $(event.target).val() + '}';
$.ajax(
{
type: 'POST',
data: dta,
url: 'Default.aspx/SaveUpVote',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//$(event.target).text("Vote Casted");
alert("Vote Casted");
},
error: function (x, y, z) {
alert("Oops. An error occured. Vote not casted! Please try again later.");
}
}
);
});
});
</script>
Code Behind (you can use C#, I'm familiar with both):
Imports System.Web.Services
Imports System.Web.Script.Services
<WebMethod()>
Public Shared Function SaveUpVote(ByVal VoteID As Integer) As Boolean
Dim test As Boolean = False
Dim mySQL As New SQLHandler
test = mySQL.UpdateVoteByID(VoteID)
Return test
End Function
HTML:
<input type="image" src="images/vote.png" id="VoteMeUp1" value="321" />
When a vote is cast for a given button, call the server method using ajax (for aspx) as follows:
$(document).ready(function() {
$("[id^=VoteMeUp]").click(function(event) {
var dta = '{ "VoteId":' + $(event.target).val() + '}';
$.ajax(
{
type: 'POST',
data: dta,
url: 'Default.aspx/SaveUpVote',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$(event.target).text("Vote Casted");
},
error: function(x, y, z) {
alert("Oops. An error occured. Vote not casted! Please try again later.");
}
}
);
});
});
In Default.aspx.cs
[WebMethod]
public static void SaveUpVote(int VoteId)
{
string UpdateSQL = "UPDATE TableName SET Votes = Votes + 1 WHERE PKID = #VoteId";
//do DB stuff
return;
}
Sample HTML:
...
<body>
<button id="VoteMeUp1" value="817">1 - Vote for this</button>
<button id="VoteMeUp2" value="818">2 - Vote for that</button>
</body>
...
the easiest method to do this would be WebMethods.
Add a ScriptManager to your page with EnablePageMethods set to true
aspx page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
Assign a web method attribute to the method which increments the votes in your (c# here) code behind:
c# code behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string ChangeVote(string Arg){
...logic to change votes
}
in your javascript event, you can then access the code behind via pagemethods, and define functions to call on success and fail cases:
javascript:
PageMethods.ChangeVote("sent item", OnChangeVoteComplete,OnChangeVoteFail);
function OnChangeVoteComplete(arg){
//arg is the returned data
}
function OnChangeVoteFail(arg){
//do something if it failed
}
the success function receives the data returned by the WebMethod. You can use this to update the display on the page.
When use clicks on the UpVote button, make an ajax call to the server where you execute a query againist the database to increment the vote.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
Vote UP
</body>
<script type="text/javascript">
$(function(){
$("#aUpVote").click(function(){
$.post("myajaxserverpage.aspx?qid=12",function(data){
alert(data);
});
});
});
</script>
</head>
and in the server page (myajaxsever.aspx), read the values and execute your query to increment the Vote column value. value of qid is the question id this you can read from the page because it is going to be dynamic.