I am trying to send the username to php using ajax.
Here is my js.
$('#username').blur(function(){
var username = $("#username").val();
$.ajax({
type: "POST",
url: "dbquery.php",
data: username,
success: function(result){
$("#dbdata").html(result);
}
});
});
And here is php.
$value = $_GET['username'];
I know it is about the ajax because everything worked fine when the ajax part was written in pure javascript.
first of all your ajax type is post but you getting value using GET[] This is mistake here.
try this
$('#username').blur(function(){
var username = $("#username").val();
$.ajax({
type: "POST",
url: "dbquery.php",
data: {'username':username},
success: function(result){
$("#dbdata").html(result);
}
}); });
and you have to use this to get value
$value = $_POST['username'];
Send data as an object as $_GET reads associative array of variables passed to the current script via the URL parameters
data: {username:username},
You are using type:"POST" and trying to retrieve the values in GET Array in the PHP code .Change the method to GET
$('#username').blur(function(){
var username = $("#username").val();
$.ajax({
type: "GET",
url: "dbquery.php",
data: username,
success: function(result){
$("#dbdata").html(result);
}
});
});
Use below code
$('#username').blur(function(){
var username = $("#username").val();
var dataString = 'username ='+ encodeURIComponent(username) ;
$.ajax({
type: "POST",
url: "dbquery.php",
data: dataString ,
success: function(result){
$("#dbdata").html(result);
}
});
});
First: You are using POST in ajax. and GET in PHP, which is wrong.
If we use POST then in the PHP file, we use $_POST[”] to get the
value. If we use GET then we use $_GET[]
Second: data is passed as an object as data: {username: username}. This means that if we use $_POST[‘username’] in the PHP file, we will get the value of the username.
Your final code will be
AJAX
$('#username').blur(function(){
var username = $("#username").val();
$.ajax({
type: "POST",
url: "dbquery.php",
data: {username:username},
success: function(result){
$("#dbdata").html(result);
}
});
});
PHP
$value = $_POST['username']
Please pass data as an Object. To access data in PHP you have to use $_POST['username'], $_POST['password'] etc
$('#username').blur(function(){
var data = {
username:$("#username").val(),
password: $("#password").val()
};
$.ajax({
type: "POST",
url: "dbquery.php",
data: data,
success: function(result){
$("#dbdata").html(result);
}
});
})
Related
I have written a php script:
cch.php:
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
json_encode($array);
$stmtcheck->close();
And jquery for submitting form is
recover.php:
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function()
{
}
});
});
The script is returning more than one variable and the returned data should be in JSON format.
How do I read the data in jQuery?
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function(data) //parameter missing
{
var json = $.parseJSON(data);
console.log(json);
//in console you will get the result response
}
});
});
Hello your php code should echo the JSON output like this:
<?php
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
$stmtcheck->close();
echo json_encode($array);
?>
Now, in your javascript, you can use JSON.parse method to get the JSON.
Also, specifying your response type as JSON will automatically return a JSON object.
$("#formUnlock").submit(function (e) {
e.preventDefault();
$.ajax({
url: '../scripts/cch.php',
method: 'POST',
data: $('#formUnlock').serialize(),
dataType: 'JSON',
success: function (json_string) {
var res = JSON.parse(json_string);
console.log(res);//This should output your JSON in console..
}
});
});
I have an JQuery function which submits data from a php form to a different php file(submitForm.php). The submission works fine and there isn't any problem whatsoever, below is the handler:
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
success: function(data) {
}
});
}
Now, I want to be able get data from the submit form (submitForm.php), and load it into a different page.
This is my submitForm.php
<?php
$name="Amanda";
$age="23";
$data = array("name"=>"$name","age"=>"$age");
header("Content-Type: application/json");
echo json_encode($data);
?>
This is how my new submitHandler looks like
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
success: function(data) {
var name= html(name);
var age=html(age);
$("#message").load("newpage.php",{name:name,age:age});
}
});
}
I think I am doing it wrong, I would be grateful if somebody could correct me or give an idea as to how to do this. Thanks
It should be like this. If you want to take your returner data you should use formal parameter of success function.
submitHandler : function(){
$.ajax({
type: "POST",
cache:false,
url: "submitForm.php",
data: $('#form').serialize(),
dataType : 'json',
success: function(data) {
var name= data.name;
var age=data.age;
$("#message").load("newpage.php",{name:name,age:age});
}
});
}
Edit: Also you need dataType: 'json' line.
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
}
});
Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I've tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright...
And yea usual string were echoed correctly :-)
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
Quoting from PHP Manual
php://input is a read-only stream that allows you to read raw data from the request body.
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
UPDATE:
When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.
If you must get that using $_POSTyou would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.
To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property.
The following should work as you expected:
this.getAbsence = function() {
var strJSONData = JSON.stringify(this);
alert(strJSONData);
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'ajax/selectSingle.php',
data: 'm=getAbsence&Absence=' + strJSONData,
success: function(data) {
alert(data);
}
});
}
try this
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(vThis),
success : function(data){
alert(data);
}
});
}
EDIT
I think we can also do this!
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ajax/selectSingle.php?m=getAbsence",
data: vThis,
success : function(data){
alert(data);
}
});
}
and in PHP
print_r($_POST);
On PHP side try this:
$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);
i want to post an array from java script to php by ajax. But i don't know how do that, especially send it to php function like controller class. Correct me if i'm wrong, this is my java script source, as a function to send an array :
<script>
function send(){
var obj = JSON.stringify(array);
window.location.href = "post.php?q=" + obj;
}
</script>
i was try, but still fail. really need help..
As described in the JQuery API documentation, you can use
var rootPath="http://example.com/"
var jsonData = $.toJSON({ q: array });
var urlWS = rootPath + "post.php";
$.ajax({
url: urlWS,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function(result) {
// do something here with returned result
}
});
var array= [];
array[0] = 'hi';
array[1] = 'hello';
$.ajax({
url: 'http://something.com/post.php',
data: {array: array},
type: 'POST'
});
try like this,
var data_to_send = $.serialize(array);
$.ajax({
type: "POST",
url: 'post.php',
data: data_to_send,
success: function(msg){
}
});
or
you can pass as json like below,
$.ajax({
type: "POST",
url: 'post.php',
dataType: "json",
data: {result:JSON.stringify(array)},
success: function(msg){
}
});
var arr = <?php echo json_encode($postdata); ?>;
ajax: {
url:"post.php"
type: "POST",
data: {dataarr: arr},
complete: function (jqXHR, textStatus) {
}
You can try this .this will work
example
ajax code:
$.ajax({
url: 'save.php',
data: {data: yourdata},
type: 'POST',
dataType: 'json', // you will get return json data
success:function(result){
// to do result from php file
}
});
PHP Code:
$data['something'] = "value";
echo json_encode($data);