I must make an application, and I've decided to use PhoneGap, but my Ajax always say "ERROR", and I don't know why, because the insert works very well...
$("#test").click(function() {
var name = $("#name").val();
var password = $("#password").val();
alert(name+' '+password);
$.ajax({
type: "POST",
url: "http://191.165.1.16/PULZ/ajax_action.php",
// contentType: "application/json; charset=utf-8",
dataType: "json",
data : {
actionname : 'insert',
name:name,
password:password
},
success: function(data) {
alert("work");
},
error: function(data) {
alert("There was an error loading the feed");
}
});
});
And my PHP code
if (isset($_POST["actionname"]) && !empty($_POST['actionname'])){
$actionname = $_POST['actionname'];
if($actionname == 'insert'){
$connect = new PDOsql();
$name = $_POST['name'];
$password = md5($_POST['password']);
$sql="INSERT INTO user(name,password) VALUES(?,?)";
$opt = array($name, $password);
$connect->query($sql,$opt);
$connect = null;
die(
json_encode(
array(
'state'=>'success'
)
)
);
}
}
Try this
JAVASCRIPT
$("#test").click(function() {
var name = $("#name").val();
var password = $("#password").val();
alert(name + ' ' + password);
$.ajax({
type: "POST",
url: "http://191.165.1.16/PULZ/ajax_action.php",
// contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
actionname: 'insert',
name: name,
password: password
},
headers: {
'Content-Type': 'application/json'
}
success: function(data) {
alert("work");
},
error: function(data) {
alert("There was an error loading the feed");
}
});
});
PHP
if (isset($_POST["actionname"]) && isset($_POST['name']) && isset($_POST['password'])){
$actionname = $_POST['actionname'];
$name = $_POST['name'];
$password = $_POST['password'];
if($actionname == 'insert'){
$connect = new PDOsql();
$name = $_POST['name'];
$password = md5($_POST['password']);
$sql="INSERT INTO user(name,password) VALUES($name,$password)";
$opt = array($name, $password);
$connect->query($sql,$opt);
$connect = null;
die(
json_encode(
array(
'state'=>'success'
)
)
);
}
}
You can't use "empty()" with a non variable element, you will receive a internal server error "500", always.
Note: Prior to PHP 5.5, empty() only supports variables; anything else
will result in a parse error. In other words, the following will not
work: empty(trim($name)). Instead, use trim($name) == false.
PHP Manual - empty
Related
i am totally lost, I used the AJAX below to post data to PHP and echo "1". However, the code couldnt get into the "if (result==1)" code block. It always go into the ELSE block I have attempted to alert(result). It shows 1 without any problem. Apologize for my bad explanation. Any help is deeply appreciated.
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $form.serialize(),
success: function(result) {
// ... Process the result ...
//alert(result);
if (result=="1")
{
swal({
type: "success",
title: "Congratulation!",
text: "Please check your email inbox",
animation: "slide-from-top",
showConfirmButton: true
}, function(){
var username = $("#username").val();
var password = $("#password").val();
});
}
else
{
//alert(result);
swal({
type: "error",
title: "",
text: result,
animation: "slide-from-top",
showConfirmButton: true
});
}
}
});
My PHP Code is as below:
if($dum=="TRUE")
{
$password2 = $_POST['password2'];
$fullname = $_POST['fullname'];
$country = $_POST['id_country'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$agent = $_POST['agent'];
$term = $_POST['term'];
$sql = "INSERT INTO usercabinet (username, password, password2, fullname, country, mobile, email, agent, term, emailconfirm, identityconfirm, feeds)
VALUES ('$username', '$password', '$password2', '$fullname', '$country', '$mobile', '$email', '$agent', '$term', '0', '0', 'Welcome to Our New Cabinet')";
if ($conn->query($sql) === TRUE) {
// "New record created successfully, Success!!<br>";
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $fullname;
$_SESSION['country'] = $country;
$_SESSION['mobile'] = $mobile;
$_SESSION['email'] = $country;
$_SESSION['term'] = $term;
$_SESSION['emailconfirm'] = 0;
$_SESSION['identityconfirm'] = 0;
$_SESSION['feeds'] = "Welcome to Cabinet";
echo "1";
}
What could be the possible reason of fail?
Try the following:
result = trim(result);
if(result == 1){
This will remove any trailing spaces from the string. Or you can make sure there is no space after or before <?php ?> tags. OR better yet, you can submit json response from PHP Like:
$result = ['status' => 'success'];
echo json_encode($result);
And in your js something like:
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $form.serialize(),
dataType: 'json',
success: function(result)
{
if (result.status=="success")
}
});
I'm new using ajax and I have a code to display from wordpress some information from database columns.
I have this PHP code to connect with the database and create the JSON file:
<?php
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
?>
In a wordpress page I have this code, I build a form where if the user click the submit button call doLogin()
<script type="text/javascript"> function doLogin(){
data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: "Mywebsiteurl.php",
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
} </script>
I need to show in <div id="forma"> a kind of list usign html, for example:
Id: VALUE ID
Name: VALUE NAME
and more information...
When i try to print in my website the required information using $('#forma').html(data); I obtain error or just an empty space.
How can I fix it? thanks.
In WordPress we need to hook the ajax hook to your check_user function here.
add_action('wp_ajax_your_action_from_js', 'your_function');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_your_action_from_js', 'your_function');
Check below code for how it is done regarding your context.
In functions.php
function check_user() {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
}
add_action('wp_ajax_check_user', 'check_user');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_check_user', 'check_user');
In your JS called file.
In the script the action is related to your _your_action_from_js. So action is needed for knowing where the ajax has to hit. In our case it executes our check_user and returns the appropriate values.
<script type="text/javascript">
function doLogin(){
data = {action: 'check_user', username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: ajax_url,
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
Reference Simple AJAX Form: http://wptheming.com/2013/07/simple-ajax-example/
CODEX Reference: https://codex.wordpress.org/AJAX_in_Plugins
WordPress has specific methods to enable ajax requests.
// registering ajax request for Logged users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// registering ajax request also for public area
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback()
{
// Your code here
wp_die(); // this is required to terminate immediately and return a proper response
}
To call it:
jQuery(document).ready(function($) {
var data = {action: "my_action", username: jQuery("#user").val(), password: jQuery("#pass").val()}
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: data,
method: 'POST',
success: function(response) {
console.log(response);
},
error: function(a,b,c) {
}
});
});
Source: https://codex.wordpress.org/AJAX_in_Plugins
i want to add data to my database by passing as a json string then using php what i have done but adds an empty line in the database instead of adding the data that i sent and i get the alert("fail") message where is the mistake please
here is my save function
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp};
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
and here is my php file insert.php
<?php
$json = isset($_POST['data']) ? $_POST['data'] : "";
$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ('".$new['email']."','".$new['mdp']."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
Can you try this:
JS:
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp};
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: data,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
}
PHP Code:
<?php
$email = isset($_POST['email']) ? $_POST['email'] : "";
$mdp = isset($_POST['mdp']) ? $_POST['mdp'] : "";
$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ('".$email."','".$mdp."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
Get data using this way in PHP
$data = json_decode(file_get_contents('php://input'));
$email = $data ->email;
$mdp = $data ->mdp;
In your PHP, each individual variable that you're passing through (i.e. email and mdp) is passed as individual $_POST data, not into a single $_POST variable called 'data'. Right after your opening PHP tag, check for the email and mdp:
$email = (isset($_POST['email']) ? $_POST['email'] : "");
$mdp = (isset($_POST['mdp']) ? $_POST['mdp'] : "");
$conn= ....
You can try this:
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {'email': eml,'mdp': mp}; //json
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: data,//pass it here
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
}
php:
<?php
if(isset($_POST['email'],$_POST['mdp']) {
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ('".$_POST['email']."','".$_POST['mdp']."') ";
$insert=mysqli_query($conn, $sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
try like this,
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp};
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
// dataType: 'json',
data: {"data":JSON.stringify(data)},
// contentType: "application/json; charset=utf-8",
success: function (data) {
alert('success');
},
error: function () {
alert("fail");
}
});
}
Try this :
function save() {
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp};
$.ajax({
type: 'POST',
url: "http://localhost:800/test/insert.php",
//dataType: 'json',
data: {"data": JSON.stringify(data)},
//contentType: "application/json; charset=utf-8",
success: function (data) {
if (data == 'created')
alert('Success');
else
alert('Fail');
}
});
}
i want to make login form with session (with PHP + ajax), i send username from controller with json but it doesn't work. i don't know whats wrong, please help
this is the function in controller :
public function actionLogin()
{
$username = isset($_POST['username'])?$_POST['username']:null;
$password = isset($_POST['password'])?sha1($_POST['password']):null;
$json = new JsonHelper();
$result = array();
if($username && $password !=''){
$checkLogin = Administrator::model()->findByAttributes(
array('username'=>$username, 'password'=>$password));
$checkUser = Administrator::model()->findByAttributes(
array('username'=>$username));
$checkPass = Administrator::model()->findByAttributes(
array('password'=>$password));
$login = count($checkLogin);
$user = count($checkUser);
$pass= count($checkPass);
if($login==1)
{
$result['status'] = 'success';
$result['username'] = $username;
$json->addData('ajax', $result);
}
elseif($user == 1 && $pass == 0)
{
$result['status'] = 'wrongPass';
$json->addData('ajax', $result);
}
elseif($user == 0 && $pass == 1)
{
$result['status'] = 'wrongUser';
$json->addData('ajax', $result);
}
}
echo json_encode($json->getJson());
}
and this is the form_login.js file :
function login(){
var form = $('#login-form');
var formId = form.attr('id');
var action = form.attr('data-action');
var method = form.attr('data-method');
var formData = serializer(form); //don't mind this function
$.ajax(
{
url: action,
cache: false,
processData: false,
contentType: false,
type: method,
data: formData,
success: function(json)
{
// AJAX SUCCESS
var json = JSON.parse(result);
if(json['result']['ajax']['status']=='success')
{
//$_SESSION['username'] =json['username'];
window.location = baseUrl + "/appsterize/dashboard/index";
}
else if(json['result']['ajax']['status']=='wrongPass')
{
// Password wrong
alert("The password you entered is incorrect.");
}
else if(json['result']['ajax']['status']=='wrongUser')
{
// Username isn't exist
alert("Username isn't exist");
}
},
error: function(xhr, status, error)
{
// AJAX ERROR
var string = "<strong>Error!</strong> " + xhr['responseText'];
$(alertError).attr('data-text', string);
$(alertError).click();
},
});
}
some error is 'Uncaught ReferenceError: alertError is not defined'
Have an element with id = 'alertError'?
Could this be the solution:
$("#alertError").attr('data-text', string);
...
Basically, what #serakfalcon said above:
...
error: function(xhr, status, error)
{
// AJAX ERROR
var errorMsg = "<strong>Error!</strong> " + xhr['responseText'];
alert(errorMsg);
},
...
I would just like to know how to go about comparing the resulting echo from a $.ajax call in JavaScript. I attempted this and even though I get 1, it doesn't actually compare the results correctly.
jQuery:
$.ajax({
type: "POST",
url: "login.php",
data: user,
dataType: 'html',
success: function(result)
{
alert(result);
if(result == '1')
{
alert("logged in :D");
//document.location.replace('home.php');
}
else
{
alert("not logged in :<");
}
},
failure: function()
{
alert('An Error has occured, please try again.');
}
});
PHP:
<?php
session_start();
$host = "localhost";
$user = "root";
$passw = "";
$con = mysql_connect($host, $user, $passw);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$json = $_REQUEST['json'];
$json = stripslashes($json);
$jsonobj = json_decode($json);
$password = $jsonobj->password;
$email = $jsonobj->email;
mysql_select_db("tinyspace", $con);
$result = mysql_query("SELECT 1 FROM users WHERE email = '"
. $email . "' AND password = '" . $password . "'");
while($info = mysql_fetch_array( $result ))
{
if($info[0] == 1)
{
echo '1';
}
}
?>
There's probably a space or line break after the '1' that is echoed. Check if there's no space before the opening <?php tag and remove the closing ?> tag (you're allowed to do that, and it will prevent accidental whitespace being outputted.
You should be able to check by changing the javascript to:
alert('X' + result + 'X');
You'll see soon enough if there's any whitespace around result.
try to send json response
php:
echo json_encode(array(
'status' => 'ok',
));
js:
dataType : "json",
success : function(response) {
if (response.status == "ok") {
alert('success');
} else {
alert('error');
}
}