My aim is to update a WordPress post using AJAX. My code so far:
Script:
$.ajax({
type: 'POST',
url: ajax_url,
data: {
'action': 'wp_post',
'ID': post_id,
'post_title': post_title
},
success: function( data ) {
$( '.message' )
.addClass( 'success' )
.html( data );
},
error: function() {
$( '.message' )
.addClass( 'error' )
.html( data );
}
});
PHP:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
if ( $id == 0 ) {
$error = 'true';
$response = 'This failed';
echo $response;
} else {
$error = 'false';
$response = 'This was successful';
echo $response;
}
}
As you can see the $response variable in my PHP function is being passed to the success function in my script and the value of $response is displayed on the page.
I want to modify my success function to do something like this:
success: function( data ) {
if( $error == 'true' ) {
// do something
} else {
// do something else
}
},
The problem is, I am having trouble passing both the $response and $error variables in my PHP function to the success function in my scipt.
Can anyone let me know how to pass $response and $error to my script's success function?
Is there a better approach I should be taking?
I'm newish to AJAX so forgive me if the question is very basic.
You shoud encode the response of the php script as json, as follows:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
if( data.status == 'error' ) {
// error handling, show data.message or what you want.
} else {
// same as above but with success
}
},
You can create a JSON array like this one, in the backend:
$arr = array('error' => true, 'something' => 'foo');
echo json_encode($arr);
And then parse the json array to fetch the returned values, like this:
success: function( data ) {
var error = '';
var something = '';
for(var i = 0; i < data.length ; i++)
{
error = data[i].error;
something = data[i].something;
}
if( error ) {
// do something
} else {
// do something else
}
},
Wherea you echoed the array from the backend to the frontend, you can't simply access PHP variables within the JavaScript.
Note that there might be a syntax error, since I'm not testing it.
What you are looking for is json_encode()
This converts a PHP array to JSON.
For example:
$dataArray = array( 'message' => 'Error', 'data' => data);
echo json_encode($dataArray);
You cannot directly use PHP variables within JavaScript. The best you can do is manipulate PHP output in your JavaScript code.
For example, you could print $response as either 'error' or 'no_error' - and in your AJAX callback, check that var data does not equal 'error' (For example).
if you use:
echo json_encode($response);
on your .php function, remember to use:
var data = $.parseJSON(data);
on your ajax success.
Example:
function php_ajax_function() {
// whatever you want to do...
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
console.log(data);
var data = $.parseJSON(data);
if( data.status == 'error' ) {
// do something
} else {
// do other thing
}
}
the javascript variable data contains your echoed $response variable. So using your example, it would be something like this. Be sure you are also asking for html as your return data in the ajax function. here is the docs on that: http://api.jquery.com/jquery.ajax/
success: function( data ) {
if( data == 'This failed' ) {
// do something
} else {
// do something else
}
},
Related
I'm trying to pass two number and check if their product is true or false. I can see call made successfully in network tab and when i click that link, output is correct to. But i m stuck at retrieving that result. It doesn't show anything in data1.
function call(){
console.log(fun);
$.ajax({
url: "http://localhost/mt2/checkanswer.php",
dataType: "jsonp",
type: "POST",
//window.alert("what");
data: {
num1:2,
num2:2,
answer:5
},
success: function( data1 ) {
console.log(data1);
$( "#timeDiv" ).html( "<strong>" + data1 + "</strong><br>");
}
<?php
// get two numbers and the answer (their product) and return true or false if the answer is correct or not.
// using this as an api call, return json data
// calling <your host>/checkanswer.php?num1=4&num2=5&answer=20 will return true
// calling <your host>/checkanswer.php?num1=4&num2=5&answer=21 will return false
if(isset($_GET['num1']) && isset($_GET['num2']) && isset($_GET['answer']) && is_numeric($_GET['num1']) && is_numeric($_GET['num2']) && is_numeric($_GET['answer'])) {
$product = $_GET["num1"] * $_GET["num2"];
if ($product === intval($_GET['answer'])) {
$result = true;
} else {
$result = false;
}
header('Content-type: application/json');
echo json_encode($result);
}
?>
https://drive.google.com/open?id=1ocF344ZxG3HXJR0WQha1kOoVM9bCepnI "console"
The issue is your Javascript is submitting the data via JS as a post request and your PHP is looking for a get request.
if(isset($_GET['num1']) && isset($_GET['num2']) && isset($_GET['answer']) && is_numeric($_GET['num1']) && is_numeric($_GET['num2']) && is_numeric($_GET['answer'])) {
..
}
So either change method: 'POST' to method: 'GET' or change $_GET[..] to $_POST[..].
Also that's one wild if statement. You could break it up so it's not so long and isn't as hard to read. This also allows you to add some additional information based on where your code 'fails.'
if ( isset($_GET['num1'], $_GET['num2'], $_GET['answer']) ) {
if ( !is_numeric([$_GET['num1'], $_GET['num2'], $_GET['answer']]) ) {
// Our numbers aren't numeric!
$message = 'Not all variables are numeric';
$result = false;
} else {
$message = 'We did it!';
$result = $_GET['num1'] + $_GET['num2'] == $_GET['answer'];
}
} else {
// We didn't have all of our request params passed!
$message = 'We didn\'t have all our variables';
$result = false;
}
header('Content-type: application/json');
echo json_encode([ 'message' => $message, 'result' => $result]);
Edit
Based on epascarello's comment remove dataType: 'jsonp'.
I'm using json to post data to controller but i can't do some effects if data is inserted to database successfully,
This if statement does not work in this javascript code ?
I mean .like-btn .html() does not work but data inserted in database ?
My experience in Javascript between 0 and 10 :D
Using Codeigniter 3.0.3
Here's my javascript
<script type="text/javascript">
$(document).ready(function() {
$(".like-btn").click(function(event) {
var liker_id = "<?php echo $this->session->userdata('id'); ?>";
var post_id = $(this).attr('post-id');
jQuery.ajax({
type: "POST",
url: "<?php echo base_url('home/AddLike'); ?>",
dataType: 'json',
data: {liker_id: liker_id, post_id: post_id},
success: function(res) {
if (res)
{
$('.like-btn[post-id = '+post_id+']').html('<span class="fa fa-check"></span> Liked');
}
}
});
});
});
</script>
Here's my controller
function AddLike() {
$this->load->helper('string');
$this->load->model('users_model');
$this->users_model->Add_like();
}
And here's my model method
function Add_like() {
$this->db->where('liker_id', $this->input->post('liker_id'));
$this->db->where('post_id', $this->input->post('post_id'));
$query = $this->db->get('likes_table');
if($query->num_rows() == 0) {
$data = array(
'liker_id' => $this->input->post('liker_id'),
'post_id' => $this->input->post('post_id')
);
$this->db->insert('likes_table', $data);
return true;
}
}
Just change below on your model:
change return to echo
function Add_like() {
$this->db->where('liker_id', $this->input->post('liker_id'));
$this->db->where('post_id', $this->input->post('post_id'));
$query = $this->db->get('likes_table');
if($query->num_rows() == 0) {
$data = array(
'liker_id' => $this->input->post('liker_id'),
'post_id' => $this->input->post('post_id')
);
$this->db->insert('likes_table', $data);
echo true;
}
}
You should debug your code of ajax response. And you should check whether you are getting any response in res variable.
Important
1)In if condition you should use double quotes("") to wrap variable post_id like
$('.like-btn[post-id = "'+post_id+'"]').html...
2) Another thing is you should return "true" as string not as boolean and check with string in ajax success block.
Solved add this line at the end of controller method
echo true;
code after edit
function AddLike() {
$this->load->helper('string');
$this->load->model('users_model');
$this->users_model->Add_like();
echo true;
}
I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.
I currently have my jQuery outputting the result in the same div as per error or success:
HTML
<div id="error-message").html(res);
JQUERY
jQuery('#register-me').on('click',function(){
$("#myform").hide();
jQuery('#loadingmessage').show();
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd,
}
jQuery.post( ajaxurl, ajaxdata, function(res){
$('#loadingmessage').hide();
$("#myform").show();
jQuery("#error-message").html(res);
});
});
PHP
$error = '';
$uname = trim( $_POST['username'] );
$email = trim( $_POST['mail_id'] );
$fname = trim( $_POST['firname'] );
$lname = trim( $_POST['lasname'] );
$pswrd = $_POST['passwrd'];
if( empty( $_POST['username'] ) )
$error .= '<p class="error">Enter Username</p>';
if( empty( $_POST['mail_id'] ) )
$error .= '<p class="error">Enter Email Id</p>';
elseif( !filter_var($email, FILTER_VALIDATE_EMAIL) )
$error .= '<p class="error">Enter Valid Email</p>';
if( empty( $_POST['passwrd'] ) )
$error .= '<p class="error">Password should not be blank</p>';
if( empty( $_POST['firname'] ) )
$error .= '<p class="error">Enter First Name</p>';
elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) )
$error .= '<p class="error">Enter Valid First Name</p>';
if( empty( $_POST['lasname'] ) )
$error .= '<p class="error">Enter Last Name</p>';
elseif( !preg_match("/^[a-zA-Z'-]+$/",$lname) )
$error .= '<p class="error">Enter Valid Last Name</p>';
if( empty( $error ) ){
$status = wp_create_user( $uname, $pswrd ,$email );
if( is_wp_error($status) ){
$msg = '';
foreach( $status->errors as $key=>$val ){
foreach( $val as $k=>$v ){
$msg = '<p class="error">'.$v.'</p>';
}
}
echo $msg;
} else {
$msg = '<p class="success">Registration Successful</p>';
echo $msg;
}
} else {
echo $error;
}
die(1);
}
}
I'm getting confused on how to get the results in 2 different places.
1: Error = display errors and show the form, ideally errors should be displayed below each form field, at the moment is a div on top of the form
2: Success = hide the form, display only the success msg
METHOD 1
If you would like to have an error message per validated field then:
You have a form input, for example:
<input name="myfield" id="myfield" type="text">
Next to it, you can add a div or span with your alert/error message and appropriate id, something like:
<input name="myfield" id="myfield" type="text">
<span id="myfield_Error" class="none">Please fill this field</span>
Where class="none" in your css, is used to hide the error container. Something like:
.none {display:none;}
Now for your jquery part:
var myfield= $("#myfield").val();
if (myfield=='') { $("#myfield_error").show(); }
The trick here is to named your error containers in a similar way as your target form element you validate. So for id="fieldA" you will have the error id="fieldA_error".
EDIT1:
If you need to use classes, you need to modify a little the code.
You need to form an array of element to check.
Loop through the array.
And use somethign like:
var fieldName = $(this).attr('name');
var fieldVallue = $(this).val();
if (fieldVallue=='')
{
$("#"+fieldName+"_error").show();
}
else
{
$("#"+fieldName+"_error").hide;
}
Method 2
If you just like to have 2 different containers, one for success and one for error/failed validation, then you need to output something different from your php file.
So your php file can output someting like:
$report['status'] = 'error'
$report['message'] = 'error in xxxx field - please use a proper email'
echo json_encode($report);
Then in your ajax success you can check what response you got. You parse your json response and based on your 'status', you put your 'message' in different containers
I hope this is what you look for.
Alternatively you can assign an error handler as follow
var jqxhr = jQuery.post(
ajaxurl,
ajaxdata,
function(res){
$('#loadingmessage').hide();
$("#myform").show();
jQuery("#error-message").html(res);
}
).fail(function() {
alert("error");
});
and send a non-2xx code from your php code (with http_response_code) if it doesn't validate.
It would be easier for you to return (for example) JSON to the front end instead of one string. The JSON would containt key/value pairs in the form of ID => Message.
For example:
$errors = array();
if( empty( $_POST['passwrd'] ) ) {
$errors['st-psw'] = "Password should not be blank";
}
if( empty( $_POST['firname'] ) ) {
$errors['st-fname'] = 'Enter First Name';
} elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) ) {
$errors['st-fname'] = 'Enter Valid First Name';
}
...
...
if( empty( $errors ) ){
$response['success'] = true;
} else {
$response['success'] = false;
$response['errors'] = $errors;
}
echo json_encode($response);
Then you will loop the JSON object in your javascript and insert the error messages after each target.
Encode result array in JSON format and return the response.
<?php
if ($validation==false)
{
$result = array ('response'=>'error','message'=>'Some validation error');
}
else
{
$result = array ('response'=>'success','message'=>'Success');
}
echo json_encode($result);
?>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
dataType: "json",
success: function (data) {
if (data.response == 'error') {
alert('error');
} else if (data.response == 'success') {
alert('success');
} else {
alert('sorry there was an error');
}
}
});
</script>
I do not understand because when the data were entered into the login are correct and I make this comparison response.success == "success" nothing happens, I check with firebug and the result is this:
Response
[{"ncontrol":"09680040","nombre":"Edgardo","apellidop":"Ramirez","apellidom":"Leon","tUser":"Admin","status":"success"}]
jQuery.ajax script to send data
// jQuery.ajax script to send json data to php script
var action = $("#formLogin").attr('action');
var login_data = {
ncontrol: $("#ncontrolLogin").val(),
password: $("#passwdLogin").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: login_data,
dataType: "json",
success: function(response)
{
**if(response.status == "success")** {
$("#status_msg").html("(+) Correct Login");
}
else {
$("#status_msg").html("(X) Error Login!");
}
}
});
return false;
And is PHP Script for processing variables from jQuery.ajax
$ncontrolForm = $_REQUEST['ncontrol'];
$passForm = $_REQUEST['password'];
$jsonResult = array();
$query = "SELECT * FROM users WHERE ncontrol = '$ncontrolForm' AND cve_user = SHA('$passForm')";
$result = mysqli_query($con, $query) or die (mysqli_error());
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if( $num_row >= 1 ) {
$_SESSION['n_control'] = $row['ncontrol'];
$_SESSION['t_user'] = $row['tUser'];
$jsonResult[] = array (
'ncontrol' => $row['ncontrol'],
'nombre' => $row['nombre'],
'apellidop' => $row['apellidop'],
'apellidom' => $row['apellidom'],
'tUser' => $row['tUser'],
'status' => 'success',
);
header('Content-Type: application/json');
echo json_encode($jsonResult);
}
You have an array, so do it this way:
if(response[0].status == "success") {
The object is the first item in the array.
EDIT:
Looking more closely at your PHP, it looks like you might be intending to loop through several rows in your query response and add them to your $jsonResult. Am I seeing it right?