Display json data from post jquery - javascript

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.

Related

AJAX pass 2 variables into the php file

<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 does my jQuery Ajax GET-request not receive a response from the server?

I am trying to let jQuery dynamically add html to my page. Unfortunately, I don't receive a response from my server. My JS code sends a GET request, which contains a parameter (bodypart). The server should return a response including the results from the database, but the response is empty.
What causes this problem?
JAVASCRIPT:
function getData() {
var sPanelHeading = '<div class="col-lg-3"><div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">Symptomen van ' + bodypart + '</h3></div>';
$( "#abc" ).append(sPanelHeading);
$.ajax({
url: 'controller.php',
data: 'bodypart=Autism',
dataType: 'json',
}).done(function(data) {
$( "#abc" ).append('<div class="panel-body" style="overflow-y: scroll;"><span class="list-group-item"><b>Vaak voorkomende symptomen</b></span></div><div class="list-group">');
for (var c in data) {
$("#abc").append('<span class="list-group-item">');
$("#abc").append(c);
$("#abc").append('</span">');
}
}).always(function(data) {
console.log(data);
});
}
PHP:
<?php
require_once( 'config.php' );
$bodypart = $_GET['bodypart'];
$sql = "SELECT c_name FROM condition WHERE c_name = '$bodypart'";
$result = $conn->query($sql);
$json_response = array();
if ($result->num_rows > 0) {
while($row = mysql_fetch_assoc($query)) {
$json_response[] = $row;
}
print json_encode($json_response);
}
$conn->close();
?>
1st : instead of
data: 'bodypart=Autism',
use
data: {'bodypart':'Autism'},
2nd
echo json_encode($json_response);
Basics of $.ajax
$.ajax({
url: 'controller.php',
type: 'GET',
data: {'bodypart':'Autism'},
dataType: 'json',
success : function(data){
alert(data);
}
});
in php
<?php
$bodypart = $_GET['bodypart'];
echo $bodypart;
?>
output should alert Autism .. if this Ok you can complete your stuff .. if something went wrong .. check your php file path

Ajax post to PHP not working

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;
?>

Receive multiple value from php file via ajax call

Below is my ajax call code. I want to send one data in .php file via ajax call and want to get two values from .php file. This two values I want to set in different 'input' tags whose id are 'course_name' and 'course_credit'.
Here my ajax call return correct value(real value from DB table) of 'course_name' input tag.
But 'MY PROBLEM IS' the value of input tag whose id is 'course_credit' shows 'success'. How can I get the correct value(real value from DB table) of id 'course_credit' ?
I have a 'select' tag which id is 'c_select'
HTML:
<input type="text" name="course_name" id="course_name" value=""/>
<input type="text" name="course_credit" id="course_credit" value=""/>
AJAX :
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
});
});
get_course_info_db.php
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name,$c_credit;
exit();
?>
AJAX code:-
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(value){
var data = value.split(",");
$('#course_name').val(data[0]);
$('#course_credit').val(data[1]);
}
});
});
PHP code:-
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name.",".$c_credit;
exit();
?>
The success callback is Function( PlainObject data, String textStatus, jqXHR jqXHR ); http://api.jquery.com/jQuery.ajax/
php:
$data = array(
'name' => $c_name,
'credit' => $c_credit,
);
echo json_encode($data);
javascript:
success: function(data) {
var result = $.parseJSON(data);
$('#course_name').val(result.name);
$('#course_credit').val(result.credit);
}
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
second arguement is the status of http request, you have to encode the answer, i suggest you JSON
in your php
$c_credit = $all_course_data['c_credit'];
echo json_encode(array('name' => $c_name,'credit' => $c_credit));
exit();
and in your javascript
success: function(response,status){
var datas = JSON.parse(response);
$('#course_name').val(datas.name);
$('#course_credit').val(data.credit);
}
this is not tested, but this is the way to do it
I'd suggest using JSON to encode the data you fetch from the database.
Try changing your ajax call as follows:
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
dataType: 'json', // jQuery will expect JSON and decode it for you
success: function(reply_data){
$('#course_name').val(reply_data['c_name']);
$('#course_credit').val(reply_data['c_credit']);
}
});
});
And your PHP as follows:
include('db_connection.php');
// Escape your input to prevent SQL injection!
$c_id = mysql_real_escape_string($_POST['c_id']);
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
echo json_encode($all_course_data);
exit();
I haven't tested this but I imagine it'd work for you.

Why I still get object object error in javascript?

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

Categories

Resources