i am facing an problem in sending data from ajax to php i would need some help
$.ajax({
type: "post",
url: "/raffle.php",
dataType: "json",
data: {
"postraffle": "true",
"title": $("#rtitle").val(),
"message": $("#mess").val(),
"maxentry": $("#maxentry").val(),
"duration": $("#durr").val(),
"filter": $("#reffil").val(),
"split": $("input[name=split]:checked").val(),
"pub": $("input[name=rafflepub]:checked").val(),
"stype": $("input[name=stype]:checked").val(),
"invo": $("input[name=invo]:checked").val(),
"items[]": itms,
"games[]": gmes,
},
success: function(data){
if(data.status == "fail")
{
alert(data.message);
$("#rafBut").removeAttr("disabled");
$("#rafBut").attr("value", "Raffle it!");
}
else if(data.status == "ok")
{
alert(data.message);
}
}
});
and the php script is here
<?php
// getting data from AJAX
$raffle_title = $_POST['title'];
$raffle_message = $_POST['message'];
$raffle_maxentry = $_POST['maxentry'];
$raffle_duration = $_POST['duration'];
$raffle_filter = $_POST['filter'];
$raffle_split = $_POST['split'];
$raffle_pub = $_POST['pub'];
$raffle_stype = $_POST['stype'];
$done = false;
$data = array(
'status' => 'ok',
'message' => 'saved! redirecting you!',
'datakey' => 'HALLEYO!',
);
$host ="localhost"; // enter your host.
$pass =""; // enter your password.
$db = "test"; // Enter your database..
$user ="4"; // enter your username.
# MYSQL Connection
$con=mysqli_connect($host,$user,$pass,$db);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
foreach($_POST['items'] as $item){
$query = "INSERT INTO table (heading,content,items) VALUES ('".$_POST['title']."', '".$_POST['message']."','".$item."')";
// this should also be done for each item
if (!mysqli_query($con, $query)) {
printf("Error: %s\n", mysqli_error($con));
}
}
echo $data;
?>
Now the function of the above script is to get the data from ajax and upload it to mysql database and send an response to the ajax script back which currently doesnt work.
i think there may be problem with my mysql query (php mysqli parameterized queries)
Some help would be really appreciated.
Thanks!
Try replacing
echo $data;
with
echo json_encode($data);
echoing data will give just "Array" string, not anything JSON encoded
You can not print arrays!
You must chenge it echo $data; to echo json_encode($data);.
Related
I'v got a problem with my site registration form. Getting 'null' from server, using json format of exchange.
Code:
JS part of code:
$("#customer-form").submit(function() {
var form_data = {
customer_name: $("#customer_name").val(),
customer_dir: $("#customer_dir").val(),
confirm_dir: $("#confirm_dir").val(),
customer_fname: $("#customer_fname").val(),
customer_address: $("#customer_address").val(),
customer_inn: $("#customer_inn").val(),
customer_kpp: $("#customer_kpp").val(),
customer_ogrn: $("#customer_ogrn").val(),
customer_okpo: $("#customer_okpo").val(),
};
$.ajax({
type: "POST",
url: "customer_form.php",
data: form_data,
dataType: "json",
success: function(data) {
console.log(data.status);
},
error: function(xhr, status) {
console.log("Error"+" "+xhr.responseText +" "+ status)
}
});
});
PHP
<?php
$customer_fname=trim($_POST["customer_fname"]);
$customer_fname=strip_tags($customer_fname);
$confirm_dir=trim($_POST["confirm_dir"]);
$confirm_dir=strip_tags($confirm_dir);
$confirm_dir = md5($confirm_dir);
$customer_name=trim($_POST["customer_name"]);
$customer_name=strip_tags($customer_name);
$customer_dir = trim($_POST["customer_dir"]);
$customer_dir=strip_tags($customer_dir);
$customer_dir=md5($customer_dir);
$customer_address=trim($_POST["customer_address"]);
$customer_address=strip_tags($customer_address);
$customer_inn=trim($_POST["customer_inn"]);
$customer_inn=strip_tags($customer_inn);
$customer_kpp=trim($_POST["customer_kpp"]);
$customer_kpp=strip_tags($customer_kpp);
$customer_ogrn=trim($_POST["customer_ogrn"]);
$customer_ogrn=strip_tags($customer_ogrn);
$customer_okpo=trim($_POST["customer_okpo"]);
$customer_okpo=strip_tags($customer_okpo);
if($customer_dir==$confirm_dir){
$con = new mysqli("localhost", "root", "", "berezka");
$sql = "SELECT * FROM CUSTOMER where customer_name='".$customer_name."'";
$result = $con->query($sql);
if($row = $result->fetch_assoc()){
$response = array("status"=>"Login has been already given");
echo json_encode($response);
}
else{
$sql_2 = "INSERT INTO customer (`customer_id`, `customer_fname`, `customer_name`, `customer_dir`, `customer_address`, `customer_inn`, `customer_kpp`, `customer_ogrn`, `customer_okpo`) VALUES ('', '$customer_fname', '$customer_name', '$customer_dir', '$customer_address', '$customer_inn', '$customer_kpp', '$customer_ogrn', '$customer_okpo')";
mysqli_query($con, $sql_2);
$response = array("status"=>"Registration is ok");
echo json_encode($response);
// mysqli_free_result($result);
// mysqli_close($con);
}
}
else{
$response = array("status"=>"Password doesnt match");
echo json_encode($response);
}
?>
Here is my error in firefox firegub or Chrome console:
Uncaught TypeError: Cannot read property 'status' of null
I was trying to use JSON.Parse or etc. Tried to make json message by object,array or another format.
Please add header info:
header('Content-Type:application/json');
before sending the response.
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 insert data to mysql database using php service and json but when i click nothing happens it shows no error no message and the data is not added to the data base help please
here is the 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',
data: data,
dataType: 'json',
success: function()
{alert("success");}
error: function()
{alert("fail");}
});
}
and this my php file insert.php
<?php
$json = $_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'])";
if (mysqli_query($conn, $sql)) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
You don't have "data" key in your $_POST array, you have "email" and "mdp", which you can access directly:
$email = mysqli_real_escape_string($_POST['email']);
$mdp = mysqli_real_escape_string($_POST['mdp']);
There is no json passed in this way, similarly when you have get string, you also don't need to parse it. Turn on error reporting, then you will see that $_POST['data'] is undefined.
BTW, use mysqli_real_escape_string to sanitize the input to prevent from injection.
"Insert.php" - > Not use for get data $json = $_POST['data'];
Only use this and try
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$email = $_POST['email'];
$mdp = $_POST['mdp'];
$new1 = json_encode($email);
$new2 = json_encode($mdp);
$sql = "INSERT INTO user ('email','mdp') VALUES ('".$new1."','".$new2."')";
$insert = mysqli_query($sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Your PHP code seems to be correct, but please try the jQuery AJAX code as follows:
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",
error: function () {
alert('fail');
},
success: function (data) {
alert('success');
}
});
}
In your data section has to be passed as JSON String, secondly you missed to in include the data contentType. Here content type is set as application/json, therefore pass the data as JSON string.
Why I'm getting the error in my jquery even though my record inserting in database? I add some changes in this code, I convert it into mysqli function. But the problem is the error message comes out? Why is that?
The error message is came from below on my script
Here's my code
Script
$(document).ready(function(){
$("#save").click(function(){
ajax("save");
});
$("#add_new").click(function(){
$(".entry-form").fadeIn("fast");
});
$("#close").click(function(){
$(".entry-form").fadeOut("fast");
});
$("#cancel").click(function(){
$(".entry-form").fadeOut("fast");
});
$(".del").live("click",function(){
if(confirm("Do you really want to delete this record ?")){
ajax("delete",$(this).attr("id"));
}
});
function ajax(action,id){
if(action =="save")
data = $("#userinfo").serialize()+"&action="+action;
else if(action == "delete"){
data = "action="+action+"&item_id="+id;
}
$.ajax({
type: "POST",
url: "ajax.php",
data : data,
dataType: "json",
success: function(response){
if(response.success == "1"){
if(action == "save"){
$(".entry-form").fadeOut("fast",function(){
$(".table-list").append("<tr><td>"+response.cat_name+"</td><td>"+response.cat_code+"</td><td>"+response.letter+"</td><td><a href='#' id='"+response.row_id+"' class='del'>Delete</a></td></tr>");
$(".table-list tr:last").effect("highlight", {
color: '#4BADF5'
}, 0000);
});
$(".entry-form input[type='text']").each(function(){
$(this).val("");
});
}else if(action == "delete"){
var row_id = response.item_id;
$("a[id='"+row_id+"']").closest("tr").effect("highlight", {
color: '#4BADF5'
}, 0000);
$("a[id='"+row_id+"']").closest("tr").fadeOut();
}
}else{
alert("unexpected error occured, Please check your database connection");
}
},
error: function(res){
alert("Unexpected error! Try again.");
}
});
}
});
AJAX
<?php
error_reporting(0);
$mysqli = new mysqli("localhost", "root", "", "2015");
if(isset($_POST) && count($_POST)){
$cat_name = $mysqli->real_escape_string($_POST["cat_name"]);
$cat_code = $mysqli->real_escape_string($_POST["cat_code"]);
$letter = $mysqli->real_escape_string($_POST["letter"]);
//$phone = mysql_real_escape_string($_POST['phone']);
$item_id = $_POST['item_id'];
$action = $_POST['action'];
if($action == "save"){
$result = $mysqli->query("insert into category values('','".$cat_name."','".$cat_code."','".$letter."')");
$lid = mysqli_insert_id();
if($lid){
echo json_encode(
array(
"success" => "1",
"row_id" => $lid,
"cat_name" => htmlentities($cat_name),
"cat_code" => htmlentities($cat_code),
"letter" => htmlentities($letter),
//"phone"=>$unique_id,
)
);
}else{
echo json_encode(array("success" => "0"));
}
}
else if($action == "delete"){
//echo "delete from info where id = '".$item_id."'";
$res = $mysqli->query("delete from category where id = '".$item_id."'");
if($res){
echo json_encode(array( "success" => "1","item_id" => $item_id));
}else{
echo json_encode(array("success" => "0"));
}
}
}else{
echo json_encode(array("success" => "0"));
}
?>
The Reponse returned in success block was zero because this statement here $lid = mysqli_insert_id(); returned nothing.
Replace $lid = mysqli_insert_id(); with $mysqli->insert_id , as this is the right syntax to get the id of the recently added/inserted row.
Happy Coding:)
I got it. mysqli_insert_id() needs the connection of the database.
It should be like this
mysqli_insert_id($mysqli);
I have a issue with my ajax form submission.I am dynamically submitting a form and using php at the server side to process it.This is the ajax success function.
$.ajax({
type: "POST",
url: "register.php",
data: "uname="+uname+"&eid="+eid+"&pwd="+pass+"&cpwd="+cpass+"&country="+coun+"&contact="+contact,
dataType: "html",
success: function(data){
if(data!="error")
{
//alert(data);
$("#user_status", window.parent.document).html("Welcome "+data+" | <a href='forum/logout.php'>Logout</a>");
if(window.parent.document.getElementById('post_user_name'))
$("#post_user_name", window.parent.document).html(msg);
parent.$.fancybox.close();
}
if(data=="error")
{
//alert(data);
$("#status").html("<span><center><font class='formright err_msg' style='width:176px;'>The user is already register with us.</font><center></span>");
return false;
}
Now if the user is valid he is logged in and f not there has to be an error like "Already exists".The valid part works fine but for invalid I return an error from the php file but still my error message doesn't show up and just error is printed on the screen.I am using fancybox for my forms(jquery fancybox)
PHP code is
if($_POST['pwd']==$_POST['cpwd'])
{
$username = $_POST['uname'];
$email = $_POST['eid'];
$password = md5($_POST['pwd']);
$cpassword = $_POST['cpwd'];
$contact_no = $_POST['contact'];
$country = $_POST['country'];
$cnt = $checkUser['cnt'];
if($cnt!=0)
{
echo "error";
//exit;
/*$_SESSION['error_msg'] = 'Email Address already exists';
redirect_to_link("index.html");*/
}
else
{
//echo "entered here";
$userArray = array();
//$user = return_post_value($_POST['uname']);
$userArray['uname'] = return_post_value($_POST['uname']);
$userArray['email'] = return_post_value($_POST['eid']);
$userArray['password'] = md5(return_post_value($_POST['pwd']));
$userArray['contact_no'] = return_post_value($_POST['contact']);
$userArray['country'] = return_post_value($_POST['country']);
//print_r($userArray);
//exit;
$userObj->addUserValue($userArray);
$_SESSION['username']= $userArray['uname'];
echo $userArray['uname'];
// return $user;
}
The echo $userArray['uname']; part works but echo "error" doesn't.Checked in Firebug response header,i can see the error word returned.
Can anyone throw some light on it?
Thanks
Use this to compare if($.trim(data)!="error")
And don't recheck for if($.trim(data)=="error")
use
if($.trim(data)!="error")
{
//
}
else{
//
}