Form submission in JSON format via AJAX - php

I'm trying to submit a HTML form to a server and it fails. I have several issues here.
I'm making a CORS request. It is a request by the client and I can't do anything about it.
( My app resides in localhost:3000/login.html & My server resides in http://localhost:3001/Login/auth )
The server in localhost:3001 accepts JSON requests and give back a JSON Responce.
(I have disabled the web-security in the browser to allow the CORS Requests)
So, I have created the HTML Form and tried to submit it with AJAX. Here you can see the code.
$(function(){
$("#loginform").submit(function(e){
e.preventDefault();
// var data = $("#loginform").serialize();
var data = {"username" : $("#username").val(),"password" : $("#password").val()};
alert(JSON.stringify(data));
$.ajax({
type: "POST",
url: "http://localhost:3001/Login/auth",
data: data,
contentType: "application/json",
crossDomain : true,
dataType: "json",
success: function(data) {
alert("success" + JSON.stringify(data));
},
error:function(data){
alert('error : '+JSON.stringify(data));
}
});
});
});
I have created the mock server in PHP (codeigniter). Here is the code for that.
public function auth(){
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$debug_export = var_export(file_get_contents('php://input'), true);
file_put_contents('new.txt',$debug_export . PHP_EOL, FILE_APPEND);
$user = 'admin';
$pass = 'admin';
$token = '1';
foreach($input_data as $key=>$value) {
if ($key === 'username') {
$this_user = $value;
}
if ($key === 'password') {
$this_password = $value;
}
}
if(isset($this_user) && isset($this_password)){
if($this_password === $pass && $this_user === $user){
echo json_encode(array('token'=>$token));
}else{
echo json_encode(array('token'=>'null'));
}
}
return 0;
}
When I submit a form, I get a response like this.
....
<p>Severity: Warning</p>
<p>Message: Invalid argument supplied for foreach()</p>
<p>Filename: controllers/Login.php</p>
<p>Line Number: 77</p>
....
My 'new.txt' file has the log details as following.
''
'username=admin&password=admin'
I have really no idea what I'm doing wrong here. Can anyone help me out here?

Related

I am unable to post data using ajax on url friendly blog detailing page where I am already using url value in Query

I know that it may be so tricky!
In detail:
on the blog detailing page(blog-single.php/title) I have a subscription form this subscription form is working fine on another page with the same PHP action file and ajax
and blog-single.php/title is also working fine until I did not submit the form
On this page in the starting, I have bellow query
<?php
$query_head="SELECT * FROM blog_post WHERE friendly_url = '{$_GET['url']}' ";
$result_head= $fetchPostData->runBaseQuery($query_head);
foreach ($result_head as $k0 => $v0)
{
//----- some echo
}
?>
and my subscription form code:
<form action="" method="post" class="subscribe_frm" id="subscribe_frm2">
<input type="email" placeholder="Enter email here" name="email" id="subscribe_eml2">
<button type="button" id="subscribe2">Subscribe</button>
</form>
and ajax code is bellow:
$(document).ready(function() {
$("#subscribe2").click( function() {
subscribe_frm_val2 = false;
/*email validation*/
var emailReg2 = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($("#subscribe_eml2").val().length <= 0) {
$("#subscribe_eml_Err2").html("Required field");
//console.log("Required");
subscribe_frm_val2 = false;
}
else if(!emailReg2.test($("#subscribe_eml2").val()))
{
$("#subscribe_eml_Err2").html("Enter a valid email");
}
else{
$("#subscribe_eml2").html("");
subscribe_frm_val2 = true;
//console.log("final else");
if(subscribe_frm_val2 == true)
{
console.log("frm true");
var form = $('#subscribe_frm2')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "updation/subscribe_action.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 6000000,
beforeSend: function(){
// Show image container
$("#submition_loader").show();
//alert ("yyy");
},
success: function (data) {
// console.log();
$(document).ajaxStop(function(){
$("#subscribe_eml_Err2").html(data);
});
},
complete:function(data){
// Hide image container
$("#submition_loader").hide();
}
});
}
else{
alert('Please fill all required field !');
}
}
});
});
When I submit my form above the first query is giving a warning like below:
Warning: Invalid argument supplied for foreach() in D:\xamp\htdocs\my\bootstrapfriendly\category.PHP on line 13
and after warning page doing misbehave
I think the error because of URL passing but I am not sure how to solve it
Please help me with solving it.
Thank's
I got the solution
its very simple just converted my relative URL into an absolute URL
I just created a PHP function for base URL
function base_url(){
if(isset($_SERVER['HTTPS'])){
$protocol = ($_SERVER['HTTPS'] != "off") ? "https" : "http";
}
else{
$protocol = 'http';
}
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
and then using this base URL function inside script like this
$.ajax({
----
url: "<?php echo base_url()?>/updation/subscribe_action.php",
-----
});

Phonegap returns object Object but echo correct data

I'm making a phone app using PhoneGap with PHP on the server side. the Login function has been working fine, but AJAX returns an error [object Object] while PHP returns the correct value's in JSON.
it's for making a phone app for an existing website and using its database.
the data my PHP prints is correct yet I receive an error response from ajax.
Alert(response)
Gives an [object Object] return value on error
whenever I try
alert(response.val)
I strangely get undefined, but in the network, I can see the printed data is correct in JSON.
{{"user_id":"390","response":"Success"}}
but when I look in the console on my browser I see an unexpected error.
Unexpected parameter ':'
my ajax function is as follows
$(document).ready(function () {
$("#btnLogin").click(function () {
var gebr = $("#login_username").val().trim();
var pass = $("#login_password").val().trim();
var dataString = "username=" + gebr + "&password=" + pass + "&login=";
var msg = "";
$("#message").html("Authenticating...");
if (gebr != "" && pass != "") {
$.ajax({
type: "POST",
data: dataString,
dataType: "json",
//contentType: "application/javascript",
crossDomain: true,
url: "http://url/page/app/index.php?&jsoncallback=?",
headers: "application/json",
success: function (response) {
var user_id = response.user_id;
var success = response.response;
localStorage.setItem("user_id", user_id);
window.location = "home.html";
alert("login successfull");
},
error: function (response) {
$("#message").html("error..");
alert(response);
}
});
} else {
msg = "Please fill all fields!";
$("#message").html(msg);
}
return false;
});
PHP
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
$gebruikersnaam = $_REQUEST['username'];
$wachtwoord = md5($_REQUEST['password']);
$user = [];
//if user and password are filled
if (!empty($gebruikersnaam) && isset($wachtwoord)) {
//checks if user_id has been found
if (!$found_user_id) {
$msg = "user not found!";
print json_encode($msg);
} else {
if (($gebruikersnaam == $user['gebruikersnaam'] && $wachtwoord == $user['wachtwoord']) && ((!empty($user['single_allowed_ip_address_for_login']) && $user['single_allowed_ip_address_for_login'] == $_SERVER['REMOTE_ADDR'])|| empty($user['single_allowed_ip_address_for_login']))) {
//responds with this data
$user_id = $user['user_id'];
$response[] = array(
'user_id' => $user_id,
'response' => 'Success'
);
print json_encode($response);
} else {
$msg = "user is incorrect";
print json_encode($msg);
}
}
}
I have been wanting to get a successful response and saving the user_id in local storage so it can be used on a different page.
Edit:
after using console.log on the response i got an odd object.
​
abort: function abort()​
always: function always()​
catch: function catch()​
done: function add()​
fail: function add()​
getAllResponseHeaders: function getAllResponseHeaders()​
getResponseHeader: function getResponseHeader()​
overrideMimeType: function overrideMimeType()​
pipe: function pipe()​
progress: function add()​
promise: function promise()
​
readyState: 4
​
setRequestHeader: function setRequestHeader()​
state: function state()
​
status: 200
​
statusCode: function statusCode()
​
statusText: "load"
​
then: function then()​
<prototype>: {…
which is strange because none of these functions are made and the only thing which i can recognize is the statuscode.
You need to correct your JSON. {{"user_id":"390","response":"Success"}} is not valid JSON. It needs to be {"user_id":"390","response":"Success"}.
You're getting a strange object in your console.log because your response in the error: function (response)... is actually the jqXHR jQuery object and will not return your response directly in its arguments. Stick with success: function(response)... and output whatever your server sends back.

Ajax call using angular js

I am a new Angularjs user.I am facing a problem,when i submit a signup form,I have applied validation using AngularJs. At the same time if all the input fields are valid then i have send an $http Ajax call to check the email address,already exist or not.The issue is my php file did not receive email data.
$http({
method : 'POST',
async: false,
url: 'http://localhost/angular/signup/emailcheck.php',
data: { email: $scope.user.email }, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data)
{
$scope.info = data;
if($scope.userForm.$valid && $scope.info === '0') {
alert('our form is amazing' + $scope.info);
}
else{
alert('Already exist');
}
}).error(function(response,status)
{
console.log('ERROR HERE'+ status);
});
My Php file code:
$email = $_POST['email'];
$sql = "SELECT * FROM user where username = '".$email."'";
$result = mysql_query($sql);
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
....
....
....
....
....
}
I have checked and found that php file did not receive email value at all.
$http({
method : 'POST',
async: false,
url: 'http://localhost/angular/signup/emailcheck.php',
data : $.param($scope.user), // this will definitely wor
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data)
{
$scope.info = data;
if($scope.userForm.$valid && $scope.info === '0') {
alert('our form is amazing' + $scope.info);
}
else{
alert('Already exist');
}
}).error(function(response,status)
{
console.log('ERROR HERE'+ status);
});
Try removing http://localhost from url and then see it may be CORS.
Just a guess: your url is pointing to localhost but has no port number, this is unusual, maybe you forgot it?
data: $.param({
email:$scope.user.email
})
Or this way: (modify the php)
Angular HTTP post to PHP and undefined
I have just found that in php file,
$_POST or $_GET will not work, to receive data.
Use the following:
$data = file_get_contents("php://input");
$objData = json_decode($data);
$email = $objData->email;
In my case it works.

Php function return is an empty array using Ajax otherwise not

I'm using CakePHP framework. My problem is that when I print a php function then it gives me an array with a lot of members but when using the same function with Ajax then the response is empty.
Ajax response function:
public function functionOne(){
$this->autoRender = false;
if ($this->request->is('ajax')) {
if(!$this->request->data['amount']) {
$json['errors'][] = 'Fill in all the required fields';
}elseif(!is_numeric($this->request->data['amount'])){
$json['errors'][] = 'Field amound has to be a number';
}
if(!$this->request->data['currency_from']){
$json['errors'][] = 'Fill in all the required fields';
}
if(!$this->request->data['currency_to']){
$json['errors'][] = 'Fill in all the required fields';
}
if(!$this->request->data['rate_date']){
$json['errors'][] = 'Fill in all the required fields';
}
if(isset($json['errors'])){
$json['status'] = 'error';
}else{
$json['status'] = 'success';
$json['curs'] = $this->functionTwo($this->request->data['date1']);
$json['rates'] = $this->functionThree($this->request->data['date'], $this->request->data['from'], $this->request->data['to'], $this->request->data['amount']);
}
print_r(json_encode($json));
}
}
View file ajax request:
$(document).ready(function(){
$('#converter').on('submit', function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: '<?php echo $this->Html->url(array(
"controller" => "cur",
"action" => "functionOne"
));
?>',
data: form.serialize(),
type: 'post',
async: true,
success: function (data) {
var json = data;
if (json.status == 'error') {
$('#errors').show();
$('#currencies').hide();
$('#errors').html('');
$.each(json.errors, function (k, v) {
$('#errors').append("<span>" + v + "</span>");
});
}
if (json.status == 'success') {
var json = data;
$('#errors').hide();
$('#currencies').show();
}
}
});
})
});
getCur method returns an array in format "code" => "name". It gets the currencies from reading different sources XML files. When I print the function outside of the response it gives me a correct result but with ajax it just gives me an empty array.
Errors are coming through the response though.
Thanks!
What version of Cake are you using??
Depends on the version of cake.
1.3.x:
$this->RequestHandler->isAjax();
2.x
$this->request->is('ajax');
Also can you check your chrome network tab for any specific issue.
Try to :
echo your json like echo json_encode($json);
In success callback, parse data variable by using :
success : function(data){
var json = $.parseJSON(data);
console.log(json);
}
See the data inside console.
Mistake was that I created the instances inside the method so ajax thought that I did not have any.
Thanks for replying!

jQuery AJAX with PHP returning via JSON (Login form)

I don't know what I do wrong..
I have 2 files:
login.php
index.php
<script type="text/javascript">
$(document).ready(function(){
$('#btnLogin').bind('click', loginToWebsite);
});
function loginToWebsite(){
$.ajax({
url: "login.php",
type: "POST",
data: "username=" + $("#username").val()+"&password=" + $("#password").val(),
datatype:"json",
success: function(status)
{
if(status.success == false)
{
$("#loginform").effect("shake", {times:2}, 100);
$("#login_message")
.attr('class', 'ui-state-error')
.html('<strong>ERROR</strong>: Your details were incorrect.<br />');
}
else {
$("#login_message")
.attr('class', 'ui-state-highlight')
.html('<strong>PERFECT</strong>: You may proceed. Good times.<br />');
}
}
});
}
</script>
login.php gile looks this way:
<?php
if (isset($_POST['username'])&& isset($_POST['password']))
{
if (login ($_POST['username'], $_POST['password'])){
$data = array("success" => true);
echo json_encode($data);
}
else {
$data = array("success" => false);
echo json_encode($data);
}
}?>
But i get undefined back from login.php (via json)
If I try to alert(status.success) it prints undefined
And I can see i the header that the username and password are getting send to the login.php page.
The PHP function
login() is implemented elsewhere (and returns true or false)
It seems the value pass to javascript through variable "status" is a string. So you have to convert the string to json object. To convert string to json object use following script. Use the latest jquery library because older one using different functions to convert string to json.
var obj = jQuery.parseJSON(status);
alert(obj.success);
I guess that you have something bad in your php script output, and it cannot be parsed as json.
Try to use some debugging web proxy (http://www.charlesproxy.com/ for example, there is a free demo)
Add console trace to see the data
success: function(status)
{
console.log(status);
// ... function body
}
Your code in php file is incorrect
if login = false
{
$data['success'] = false;
echo json_encode($data);
}
else {
$data['success'] = true;
echo json_encode($data);
}

Categories