jQuery Ajax sending empty data - php

I'm doing a code that send a data to a php file and send it back again and print it as a response however when i send the data it is sent as an empty data i did not know what is the problem this is the code that i tried:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi, "").split("\n");
function doRequest(index) {
// alert(resource[0]); The data here is ok and it is not empty whenever the data is sent the response is empty !
$.ajax({
url:'curl_check.php?email='+resource[0],
async:true,
success: function(data){
alert(data);
if (resource.length != 1) {
removeResourceLine();
doRequest(index+1);
}
}
});
}
doRequest(0);

since you're not sending the data using the data property of the ajax call object like so:
$.ajax({
...
data : { email : resource[0] }
...
});
you are sending it as part of the URL, so it should be picked up as a GET variable. in php, this looks like:
$email = isset($_GET['email']) ? $_GET['email'] : false;
that said, i'd suggest using the ajax data property and specifying the type property and setting it to GET or POST. you could also use $.ajaxSetup

Ok I am not sure what is wrong with what you are doing but I am going to give you code I use to send data to php and get a response. I am going to do it with json because it is awesome. I hope it helps:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi,"").split("\n");
function doRequest(index) {
$.post("curl_check.php", {
email: resource[0]
}, function(data, result, xhr){
if(result == 'success') {
console.log(data.success);
} else {
console.log('post failed');
}
}, "json");
}
The php code:
$json = array();
$email = $_POST['email']; //Please escape any input you receive
//Do what you have to do
$json['success'] = 'YAY IT WORKED';
die(json_encode($json));

Related

How to focus on a form field only if my data variable is not empty

I have been using php and ajax to validate if an email inserted in my form exists in my database.
I am using jquery to send the email value to my php file and return a message if the email is found. My code is working fine but I want if an email is found the cursor be on focus on the #usu_email field until the email be changed. After this, it should allow me to continue to next field.
This is the jquery code I am using:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
success: function(data, textStatus) {
if (data !== null) {
$("#eresult").html(data);
$("#usu_email").focus();
}
},
});
};
My problem is that if and email does not exist in my database the cursor keeps doing focus on my #usu_email field and does not allow me to continue to next field.
I will appreciate any help about this problem because I know very little about jquery.
First... Your condition if (data !== null) always will be true since there always will be a data provided... Be it an empty string.
The only case where there will be no data is on Ajax error... And the condition won't even be evaluated because the success callback won't execute.
Next, I assume that your Ajax request is triggered on $("#usu_email") blur... Else, I don't know how you achieve «does not allow me to continue».
Modify it in this way to compare a response:
function getemail(value) {
var usumail = $("#usu_email").val();
$.ajax({
type: "POST",
url: "ajax_email.php",
data: "usu_email=" + usumail,
datatype: "json",
success: function(data) { // There is only one argument here.
// Display the result message
$("#eresult").html(data.message);
if (data.email_exist == "yes") {
$("#usu_email").focus();
}
if (data.email_exist == "no") {
// Something else to do in this case, like focussing the next field.
}
},
});
};
On the PHP side, you have to provide the json response. It would look like something like this:
<?php
// You have this variable to compare against the database
$email = $_POST[usu_email];
// You say it is working.
// ...
// Then, you certainly have a result... Say it's $found (true/false).
// Build an array of all the response param you want to send as a response.
if($found){
$result[email_exist] = "yes";
$result[message] = "The submitted email already exist.";
}else{
$result[email_exist] = "no";
$result[message] = "A success message about the email here.";
}
// Add this header to the returned document to make it a valid json that doesn't need to be parsed by the client-side.
header("Content-type:application/json");
// Encode the array as a json and print it. That's what is sent in data as an Ajax response.
echo json_encode($result);
?>
Be carefull not to echo anything else. Not even a blank space or a line return.
Depends on what type of data you're expecting (simple text response or JSON), but at first i would start to replace your if(data !== null) with if(typeof data != "undefined" && data !== null && data != "") because the returned response might just be empty and not NULL.
If it doesn't work you should consider adding your php code to the question so we can figure out exactly what it returns when no matching email is found.

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.

Sending data with AJAX to a PHP file and using that data to run a PHP script

I'm currently trying to make live form validation with PHP and AJAX. So basically - I need to send the value of a field through AJAX to a PHP script(I can do that) and then I need to run a function inside that PHP file with the data I sent. How can I do that?
JQuery:
$.ajax({
type: 'POST',
url: 'validate.php',
data: 'user=' + t.value, //(t.value = this.value),
cache: false,
success: function(data) {
someId.html(data);
}
});
Validate.php:
// Now I need to use the "user" value I sent in this function, how can I do this?
function check_user($user) {
//process the data
}
If I don't use functions and just raw php in validate.php the data gets sent and the code inside it executed and everything works as I like, but if I add every feature I want things get very messy so I prefer using separate functions.
I removed a lot of code that was not relevant to make it short.
1) This doesn't look nice
data: 'user=' + t.value, //(t.value = this.value),
This is nice
data: {user: t.value},
2) Use $_POST
function check_user($user) {
//process the data
}
check_user($_POST['user'])
You just have to call the function inside your file.
if(isset($_REQUEST['user'])){
check_user($_REQUEST['user']);
}
In your validate.php you will receive classic POST request. You can easily call the function depending on which variable you are testing, like this:
<?php
if (isset($_POST['user'])) {
$result = check_user($_POST['user']);
}
elseif (isset($_POST['email'])) {
$result = check_email($_POST['email']);
}
elseif (...) {
// ...
}
// returning validation result as JSON
echo json_encode(array("result" => $result));
exit();
function check_user($user) {
//process the data
return true; // or flase
}
function check_email($email) {
//process the data
return true; // or false
}
// ...
?>
The data is send in the $_POST global variable. You can access it when calling the check_user function:
check_user($_POST['user']);
If you do this however remember to check the field value, whether no mallicious content has been sent inside it.
Here's how I do it
Jquery Request
$.ajax({
type: 'POST',
url: "ajax/transferstation-lookup.php",
data: {
'supplier': $("select#usedsupplier").val(),
'csl': $("#csl").val()
},
success: function(data){
if (data["queryresult"]==true) {
//add returned html to page
$("#destinationtd").html(data["returnedhtml"]);
} else {
jAlert('No waste destinations found for this supplier please select a different supplier', 'NO WASTE DESTINATIONS FOR SUPPLIER', function(result){ return false; });
}
},
dataType: 'json'
});
PHP Page
Just takes the 2 input
$supplier = mysqli_real_escape_string($db->mysqli,$_POST["supplier"]);
$clientservicelevel = mysqli_real_escape_string($db->mysqli,$_POST["csl"]);
Runs them through a query. Now in my case I just return raw html stored inside a json array with a check flag saying query has been successful or failed like this
$messages = array("queryresult"=>true,"returnedhtml"=>$html);
echo json_encode($messages); //encode and send message back to javascript
If you look back at my initial javascript you'll see I have conditionals on queryresult and then just spit out the raw html back into a div you can do whatever you need with it though.

jQuery JSON PHP Request

I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).

Pass data from JQuery to database via Javascript/AJAX/JSON/PHP

I am attempting to add data to my database from my HTML code via the use of JQuery, AJAX/JSON and PHP using an MVC model. Below is a small sample of what I am looking to achieve.
In my front end I have a checkbox with different options and a button named 'Add'. The selected elements from here are picked up by a Javascript function, which I have tested properly, once this is done I call another Javascript function to do the AJAX/JSON . What I am still fresh on is the actual AJAX/JSON process that sends the data to PHP.
My Javascript function:
function add_fruits(fruit_name, fruit_type){
var success = "Fruit added";
var error = "Fruit not added";
var params = {
'fruit_name' : fruit_name,
'fruit_type' : fruit_type
};
$.ajax({
type: "POST",
url: "add_fruits.php",
async: false,
data: params,
success: function(success){
alert(success);
},
error: function(error){
alert(error);
}
});
}
My PHP function:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
require_once 'lib/connection_files.php';
if($_SERVER['REQUEST_METHOD'] =='POST')
{
$fruit_name = no_sql_injection($_POST['fruit_name']);
$fruit_type = no_sql_injection($_POST['fruit_type']);
$fruits = new fruits();
$result = $fruits->add_fruits($fruit_name, $fruit_type);
$tmp = mysql_num_rows($result);
if($result == 1)
{//RESULT must return 1 to verify successful insertion to database
//send confirmation to front end
}
else
{
//send error message to front end
}
}
else{
//tell front end there was error sending data via AJAX
}
?>
Note that the add_fruits() function takes care of doing the Queries to the database, I did not include it here because it is irrelevant to my issue.
Just do echo in your PHP:
PHP
else {
//send error message to front end
echo "Error Adding Fruits";
}
JS
success: function(data) {
if (data == "1") {
//data added to db
}
else {
alert(data);
}
}

Categories