I am defining a key for 'id', instead of the variable 'action_upd's value(which is "action"), my php reads literally 'action_upd' and not the value
If I do in my php:
if($_POST['action_upd']){ echo "Action"}
my $.ajax will do --> alert "Action"
action_upd = "'" + action_upd + "'"; <-- same result
.
action_upd = "action";//used to be 'cow' if you check some comments
id = "1234";//just an id of an item
$.ajax({
type: 'POST',
url: './DB/DB.php',
data: { action_upd:id,'val': val},
success: function (result) {
alert(result);
},
error : function(result){
alert(result + "error");
}
});
Put action_upd in quotes if you want it to be a string and not a variable. Otherwise your code will do cow:id instead of action_upd:id when executed
$.ajax({
type: 'POST',
url: './DB/DB.php',
data: { 'action_upd':id,'val': val},
success: function (result) {
alert(result);
},
error : function(result){
alert(result + "error");
}
});
I seperated 'action_upd' and 'id', my idea was the key would change dependent of an option i choosed and would have the id
//original
data: { action_upd:id ,'val': val},
if 'action_upd' was (for example) 'update_item', if(isset($_POST['update_item'])){ update();}
//end result
data: { 'action_upd':action_upd,'id':id,'val': val},
need an extra if to check action_upd was iniciated then check the action
Related
I have a global javascript file 'Global.js' with a Global Handler 'GlobalHandler.ashx',
what i am trying to do is to render some data in the back-end (inside the handler ), than return text data using context.Response.Write(MyString)
The question is how to append the data to my html element .
I looked into the response (200) and the data is there , but i don't know the reason of not appending my text into the html element
I have tried to append them like the classic way success:function(data){
$(elementID).html(data);}
But that doesnt work
Here In Global.js
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here In MyPage.aspx
$(document).ready(function () {
GetProfession("Profession");
});
HERE In the Handler
string functionName = context.Request["functionName"];
GroupDAO GroupDAO = new GroupDAO();
if (functionName.Equals("GetProfession"))
{
var ListOfGroups = GroupDAO.GetGroups();
string Builder = "";
foreach (var group in ListOfGroups)
{
Builder+="<option value='" + group.GroupID + "'>" + group.GroupName + "</option>";
}
context.Response.Write(Builder);
}
I am expecting to have those options appended to the html element 'Profession'
but this unfortunately it does not happening
I found the answer , i did not recognize the logical reason of such behaviour ,
but the data was not in the success method even if the statuc code was 200 .
in fact it was in the error: properties of ajax request .
what i have done is :
instead of appending the data in success to the html element .
i did it in the response text
.
Here is the code before not working :
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here is the one that works
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "text/html; charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data, fata, meta) {
},
error: function (err) {
$("#Profession").html(err.responseText);
//alert(err.responseText);
}
});
}
$(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},
dataType: "text",
success: function (data) {
console.log(data); //<------
}
});
});
I want to pass the my data to PHP, but when I am trying to use it for a query it is empty, so I added the console.log before and after the AJAX script.
Before it gives me the right value ("id") of the selected product, for example "9", but the console.log in the AJAX script just returns an empty value "".
What is the problem with this? Do I miss-understand the code of AJAX?
UPDATE:
case 'linie':
if (isset($_POST['pId'])){
$t = $_POST['pId'];
}
$sql = 'SELECT l.id, l.bezeichnung as bezeichnung '
. 'FROM l "
. 'LEFT JOIN 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;
This is the relevant part of my PHP code where I try to get the previous input.
UPDATE 2:
$(document).ready(function () {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id);
$.ajax({
method: "POST",
url: "m/a/a.class.php",
data: { pID: $('#p').val() },
async: true,
dataType: 'text', (...)
When I changed it to this it worked for me :)
I guess you are playing data data.
This data
data: {produktId: p_id},
is not same as this data
success: function (data) {
Better way of writing it will be
$("#produkt").change(function () {
var p_id = $(this).val();
console.log(p_id); //<-------
$.ajax({
url: "modules/ausschuss/ausschuss.class.php",
method: "POST",
data: {produktId: p_id},
dataType: "text",
success: function (response) {
console.log(response); //<------
}
});
});
Notice the success block parameter
So this data data: {produktId: p_id}, is detail which you pass to an ajax call.
And the ajax call may or may not return response which is returned in success block as response.
Example
Using the following jQuery, how can I read through the values of the JSON that's returned? With it how it is, the jQuery doesn't even run as there is an error in: alert("A" + obj.sender[0]);
var session_id = $(this).find(".session_id").val();
$.ajax({
type: 'POST',
url: '../php/read.php',
dataType: "json",
data: {sesh_id: session_id},
success: function (response) {
var obj = jQuery.parseJSON(response);
alert("A" + obj.sender[0]);
},
error: function (response) {
alert("Err: " + response.status);
}
});
The value of response is:
[{
"sender":"email#example.com",
"details":"details1",
"date":"2017-01-04 16:11:04"
},
{
"sender":"someone#example.com",
"details":"details2",
"date":"2017-01-04 16:11:05"
},
{
"sender":"blah#example.com",
"details":"details3",
"date":"2017-01-04 16:11:06"
}]
The issue you have is that your index accessor is in the wrong place as obj is an array, not the sender property, so it should be obj[0].sender.
You also don't need to call JSON.parse() on the response, as jQuery does that for you automatically as you specified dataType: 'json'. Try this:
$.ajax({
type: 'POST',
url: '../php/read.php',
dataType: "json",
data: { sesh_id: session_id },
success: function (response) {
console.log("A" + obj[0].sender);
},
error: function (response) {
console.log("Err: " + response.status);
}
});
Finally, note that console.log() is much more preferable when debugging over alert() as it doesn't coerce data types.
I just want to get back some return value from the ajax data post. I am not sure why I am not getting something back in success. Please review the code and tell me where I am wrong
My jquery code
$("#btnlogin").click(function(){
var email = $("#emaillog").val();
var password = $("#passlog").val();
console.log('test');
/* $.ajax({
url: 'home2/login_user',
//data: {'title': title}, change this to send js object
type: "post",
data: 'email=' + email+'&password='+password,
success: function(output) {
url:"home2/login_user",
data: 'email=' + email+'&password='+password,
alert(output);
}
});*/
$.ajax ({
url:"home2/login_user",
type: "post",
dataType: 'json',
data: 'email=' + email+'&password='+password,
success: function (data) {
$.each(data, function(key, value) {
console.log(key,'--',value);
});
//iterate here the object
}
});
});
My php code
public function Login_user()
{
$email = $this->input->post('email');
$password = $this->input->post('password');
$data['result'] = $this->Home_model->login_to_user($email,$password);
echo json_encode ($data['result']);
}
In php code I echo the result but in in jquery. I am not getting any result in success
Thanks
use parseJSON
var obj = jQuery.parseJSON(data);
console.log(obj.key);
The reason is because your backend code does not seem to be able to find the username and password parameters. You're passing them the wrong way at this line of code:
data: 'email=' + email+'&password='+password,
Replace the string with a JavaScript object:
data: { email: email, password: password }
well, first, you are passing the parameters like it was a get request, and its not.
Change the way you passing to something like this.
$.ajax ({
url:"home2/login_user",
type: "post",
dataType: 'json',
data: { field1: "hello", field2 : "hello2"},
success: function (data) {
$.each(data, function(key, value) {
console.log(key,'--',value);
});
//iterate here the object
}
});
In this code, I would want my "userid" from postgresql, which will be the "response" of ajax or variable "res", to be stored in a global variable "id" so I can use it into future use.
var id;
function addUser()
{
$.ajax({
url: siteloc + scriptloc + "adduser.py",
data: {username:$("#login").val(), password:$("#password").val(), email:$("#email").val()},
dataType: 'json',
success: function (res) {
window.id = res;
console.log(id);
}
});
}
It all goes well in the console.log(id), showing the id in the console. But when I proceed to the next function,
function setpersonalinfo()
{
$.ajax({
url: siteloc + scriptloc + "setpersonalinfo.py",
data: {userID:id,
fullname:$("#fullname").val(),
birthday:$("#birthday").val(),
gender:$("#gender").val() },
dataType: 'json',
success: function (res) {
console.log("Successfully added.");
}
});
}
The id in "userID:id" is not recognized. How do I do this?
Creating an object with the property id like so...
var data = new Object({id: ""});
And then set data.id as the output,
function addUser()
{
$.ajax({
url: siteloc + scriptloc + "adduser.py",
data: {username:$("#login").val(), password:$("#password").val(), email:$("#email").val()},
dataType: 'json',
success: function (res) {
data.id = res;
console.log(data.id);
}
});
}
and in your other function reference data.id,
function setpersonalinfo()
{
$.ajax({
url: siteloc + scriptloc + "setpersonalinfo.py",
data: {userID:data.id,
fullname:$("#fullname").val(),
birthday:$("#birthday").val(),
gender:$("#gender").val() },
dataType: 'json',
success: function (res) {
console.log("Successfully added.");
}
});
}
Sorry about the formatting.
Asynchronously: Inside the addUser()'s ajax success function, call setpersonalinfo() which makes sure that the window.id is already set and ready to use.
Single-ajax: A better way to do this is to simply call setpersonalinfo() and let the server determine if the user exists already, or if no id value is submitted then assume that a new user would have to be created first. Proper input validation would have to detect duplicate user credential anyway, so that's not unnecessary work. setpersonalinfo() would then return a user id and you could set global variables at that time. Or ideally, instead of using globals, you would use closure to protect the value of the user id from being reset using the javascript console.
Synchronous: Just use the "asysc": false property when calling addUser() so that setpersonalinfo() is not called until the user id property is set.
Try this: create a closure that encapsulates your user data handling, then make the returned id a variable within your closure. It's also a good idea to use the following pattern in your js (called 'module').
function Users() {
//Global vars
var newUserId;
var methods = {
add: function(callback) {
$.ajax({
url: siteloc + scriptloc + "adduser.py",
data: { username: $("#login").val(), password: $("#password").val(), email: $("#email").val() },
dataType: 'json',
success: function (res) {
newUserId = res;
console.log(newUserId);
if (typeof(callback) == "function") {
callback();
}
}
});
},
updatePersonalInfo: function () {
$.ajax({
url: siteloc + scriptloc + "setpersonalinfo.py",
data: {
userID: newUserId,
fullname: $("#fullname").val(),
birthday: $("#birthday").val(),
gender: $("#gender").val()
},
dataType: 'json',
success: function (res) {
console.log("Successfully added.");
}
});
}
};
return methods;
}
//Usage example. add() could also pass the new user's id to the callback as a parameter, so
//you wouldn't have to store it at all.
var users = new Users();
users.add(function () {
users.updatePersonalInfo();
});