I have this javascript to update a php session variable :
$(document).ready(function(){
$('#facebook_img').live('click',function(){
login_condetion = 1;
$.ajax({
type: "POST",
url: 'facebook_login_condition_variable.php',
data:{login_condetion:login_condetion},
dataType: "json",
success: function(data)
{
alert(123);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
/*alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);*/
}
});
});
});
I print the session value before and after this code but it never change and when I alert responsText I get nothing and XMLHttpRequest gives me object object error .
This is my php code :
<?php
$temp = $_POST['login_condetion'];
if(!empty($temp) && $temp != 0)
{
$_SESSION['do_not_allow_auto_facebook_login'] = 1;
}
else
{
$_SESSION['do_not_allow_auto_facebook_login'] = 0;
}
$go = $_SESSION;
echo json_encode($go);
?>
Is there any problem with dataType of ajax function ? or it is a php session problem ? Please help me because I have been stuck here for long time.
Some suggestions..
Do you start the session at top of the page where you use it.
session_start();
in php code replace
$go = $_SESSION;
with
$go = $_SESSION['do_not_allow_auto_facebook_login'];
3.Do you need the datatype json, if not remove this line
echo json_encode($go);
and use
echo $go;
Use session_start() at the top of your script:
<?php
session_start();
...
Related
<script>
$(document).ready(function(){
var id = 1;
var name = "Abu";
$.post("update.php", {id: id, name: name}, function(data)
{
});
});
</script>
update.php
<?php
$id = $_POST['id'];
$name = $_POST['name'];
echo $id.'<br />';
echo $name.'<br />';
?>
From the above code, I want to use jquery pass the id and name from js to the update.php to update the record. However, I get the following error: Undefined index .... What am I doing wrong?
hii michael you can set the ajax post request like this
$.ajax({
type: 'POST',
url: 'abc.php',
data: {box:id,keys:name},
success: function(msg) {
alert(msg);
}
});
then in php file you can check with isset if value is set or not
You can also test other approaches (since you still don't show more details from your element inspector)with following things:
1.Name attributes in POST data with serialized string:
var data = "name=nameString";
$.post("file", data, function(data) {
}, "json");
2.Or use map:
var data = {
name : "name"
};
$.post("file", data, function(data) {
}, "json");
To handle this variable in PHP , keep the same use:
$name = $_POST['name'];
Why is PHP adding a line break to my simple AJAX result? This couldn't be much easier. Am I missing something?
Here is my JS:
$(document).ready(function() {
$('#inputEmail').change(function(){
// Check to see if email exists
var email = $('#inputEmail').val();
//alert(email);
$.ajax({
url : "php/checkUserEmail.php",
type: "POST",
dataType: "text",
data: {email: email},
success: function(data){
alert(data);
if(data === "exists"){
alert(data);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("ajax error");
}
});
});
});
Here is my php:
<?php
include_once("db_connect.php");
// Catch results sent via $.post and assigns them to php variables.
$email = $_POST['email'];
// Check to see if email exists
$sql = "SELECT * FROM users WHERE email = '$email'";
$conn->prepare($sql);
$result = $conn->query($sql);
$rowCnt = $result->num_rows;
if($rowCnt == 0){
echo trim('new');
}else{
echo trim('exists');
}
For whatever reason, my result data string is returned as /r/nexists, rather than just exists, and thus never gets into my if block, even if I only use == to evaluate the condition. I tried adding the trim() function as you can see without result. Your help is much appreciated as this has taken me hours of time for a stupid if condition.
Check if there is an "empty" space after or before the php question marks, those line-breaks are also represented as part of the response.
I mean here
<?php?>
And here
I found a solution but I still do not like or understand what is happening. You should be able to return a simple string for a result. Anyway, what I did was to just echo the number of rows returned from the DB to my ajax success function. I then checked if the result was > 0 on the client and am finally in my IF block. Here is what I did:
JS:
$(document).ready(function() {
$('#inputEmail').change(function(){
// Check to see if email exists
var email = $('#inputEmail').val();
//alert(email);
$.ajax({
url : "php/checkUserEmail.php",
type: "POST",
dataType: "text",
data: {email: email},
success: function(data){
console.log(data);
if(data > 0){
console.log("HURRAY! I'm in my IF");
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("ajax error");
}
});
});
});
Here is the PHP:
// Catch results sent via $.post and assigns them to php variables.
$email = $_POST['email'];
// Check to see if email exists
$sql = "SELECT * FROM users WHERE email = '$email'";
$conn->prepare($sql);
$result = $conn->query($sql);
$rowCnt = $result->num_rows;
echo $rowCnt;
?>
This works, and is actually maybe alittle more elegant, but you should be able to return a string without issue.
John
Hi i got a problem im doing a ajax post to a php file but in the php file its empty
JS
google.maps.event.addListener(marker, 'click', function(marker, i) {
return function() {
var rid = locations[i][4]; //get id to varible
console.log(rid);
$.ajax({
url: uri+'/helper.php',
type: 'post',
data: {'referens': rid},
success: function(data){
console.log(rid);
window.location = uri+'/helper.php';
},error: function(data){
alert('error');
}
});
}
}(marker, i));
and my helper.php
<?php
$referens = $_POST['referens'];
echo $referens;
echo 1;
?>
the output in helper.php is only 1 and not my referens post
what if i want to use it like this in same file with location.reload();
success: function(data){
console.log(data);
location.reload();
},error: function(data){
alert('error');
}
});
}
}(marker, i));
</script>
<?php include_once('helper.php');
var_dump($referens); ?>
and helper.php
<?php
$referens = $_REQUEST['referens'];
echo $referens;
echo 1;
?>
As per your comments on other answers and on your post, I would like to mention this:
console.log(rid);
window.location = uri+'/helper.php';
In your success callback rid is 91 as it should be as per your comments and that is absolutely correct because at the php file you are trying to access a POST var.
But when this line executes window.location = uri+'/helper.php'; then location changes and it makes a GET request, so it fails.
To get this var at PHP end you should try with $_REQUEST('referens') and you have to send it with url like this:
window.location = uri+'/helper.php?referens=' + rid;
and at your php end:
<?php
$referens = $_REQUEST['referens']; // <---change here.
echo $referens;
echo 1;
?>
From the docs [$_REQUEST()]:
An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
Your code looks fine.
You are printing the wrong variable.
Change
success: function(data){
console.log(rid);
window.location = uri+'/helper.php';
}
To
success: function(data){
console.log(data); // Here you are getting return in data not as rid
window.location = uri+'/helper.php?rid='+rid; // See, pass rid here.
}
in helper.php
<?php
$referens = $_REQUEST['referens'];
echo $referens;
echo 1;
?>
Hello im using a login script with ajax and i want to callback and display my data
email and usernam to stock it in local storage.
i can get the data in json but i want to display this data in console.log
this is my codes
send_ajax.js
$(document).ready(function(e) {
$("#contactSubmitButton").click(function(){
var email = $("#contactEmailField").val();
var password = $("#contactNameField").val();
$.ajax({
type: "POST",
url: "http://hubafrica.co/webservices/get_user.php",
data: "email="+email+"&password="+password,
dataType: "json",
cache: false,
beforeSend: function(){ $("#contactSubmitButton").val('Chargement...');},
success: function(data) {
alert(data);
if(data)
{
iterateJson(data);
var url="http://hubafrica.co/webservices/get_user.php";
$.get(url,function(data){
// loop through the members here
$.each(json.data,function(i,dat){
console.log(dat.email);
window.localStorage.setItem("id", dat.id);
});
});
//window.location.href = "user_dashboard.html";
}else{
$("#formSuccessMessageWrap").fadeIn('slow');
$("#contactSubmitButton").val('se connecter');
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
});
script.php
<?php
header("Content-Type:application/json");
header('Access-Control-Allow-Origin: *');
include("../config/config.php");
$account=array();
if (isset($_POST["email"])){
$email = htmlspecialchars($_POST["email"]);
$pass = htmlspecialchars($_POST["password"]);
$sql = mysql_query('SELECT * FROM `b2b_user` where email="'.$email.'" and password="'.$pass.'"');
$num = mysql_num_rows($sql);
if($num > 0){
$row = mysql_fetch_assoc($sql);
$account['id'] = $row['id'];
$account['email'] = $row['email'];
echo '{"members":'.json_encode($account).'}';
}
}
?>
be for send response from backend you need to formate your data in json. Once you get in response you need to parseJSON()and the you can menuplate.
change here:use data.members to access data:
in your php construct like this:do not append string.
$account1= array('members'=>$account);
echo json_encode($account1);
script:
$.each(data.members,function(i,dat){
console.log(dat.email);
window.localStorage.setItem("id", dat.id);
});
You can either use
alert(JSON.stringify(data));
or
Console.log(JSON.stringify(data));
Following line of code turns an object/array in to a JSON text and stores that JSON text in a string.
JSON.stringify('/array variable here/')
Hope it helps.
I have an array that i pass from javascript to php and in php page i am trying to put it in session to be used in the third page. The code is as below
JavaScript:
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
var jsonString = JSON.stringify(table_row);
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: jsonString},
success: function(data) {
alert("It is Successfull");
}
});
test1.php
<?php
session_start();
$check1 = $_POST['myJSArray'];
$_SESSION['array']= $check1;
echo $check1;
?>
test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
on submit i call the function in javascript and the form takes me to test2.php. It is giving error on test2.php page Notice: Undefined index: array in C:\xampp\htdocs\test\test2.php on line 13
Any suggestions please do let me know.
You don't need to stringify yourself, jquery does it for you, if you stringify it, jQuery will believe you want a string instead
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: table_row},
success: function(data) {
alert("It is Successfull");
}
});
However, on the php side, you still need to decode it as it is always a string when you get it from $_POST. use json_decode to do it.
$check1 = json_decode($_POST['myJSArray']);
look at your test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
if it's only the code in the file then the error you got C:\xampp\htdocs\test\test2.php on line 13 is mindless, because there is not line 13,
but if you have something about the code you show us, may there be something echoed before?
because session has to be started before any output,
otherwise I've tested whole script and works fine...
To check if session really started (otherwise $_SESSION will not work), try this:
if(session_id())
{
echo "Good, started";
}
else
{
echo "Magic! strangeness";
}
if problem not found in test2.php you can check test1.php echo $_SESSION['array'] after saving it, and in your javascript callback function alert data param itself,
I'm sure you can catch the problem by this way.
i got it to work, the code is below
Javascript file: in page index.php
Either you can call this function and pass parameter or use code directly
var table_row = []; //globally declared array
var table_row[0]=["123","123","123"];
var table_row[1]=["124","124","124"];
var table_row[2]=["125","125","125"];
function ajaxCode(){
var jsonArray = JSON.stringify(table_row)
$.ajax
({
url: "test1.php",
type: "POST",
dataType: 'json',
data: {source1 : jsonArray},
cache: false,
success: function (data)
{
alert("it is successfull")
}
});
}
Page: test1.php
session_start();
unset($_SESSION['array']);
$check1 = $_POST['source1'];
$_SESSION['array']= $check1;
echo json_encode(check1);
Page: test2.php //final page where i wanted value from session
if(session_id())
{
echo "Session started<br>";
$test = $_SESSION['array'];
echo "The session is".$test;
}
else
{
echo "Did not get session";
}
?>
In index page i have a form that is submitted and on submission it calls the ajax function.
Thank you for the help, really appreciate it.