Ajax response isn't showed on page - javascript

My ajax is
$.ajax({
type: 'POST',
url: ajax.ajax,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function(msg){
$('#success_message').fadeIn().html(data);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}
});
This is the PHP part
function form(){
global $wpdb;
$table = cars;
foreach ($_FILES as $file) {
if($file['error'] == UPLOAD_ERR_NO_FILE) {
continue;
}
$valid_ext = array( 'img' , 'png');
$extension_upload = strtolower( substr( strrchr($file['name'], '.') ,1) );
if ( in_array($extension_upload,$valid_ext) ) {
$name_upload = uniqid() . $file['name'];
$url_insert = trailingslashit( plugin_dir_path( dirname( __FILE__ ) ) ) . 'uploads';
wp_mkdir_p($url_insert);
$name_insert = trailingslashit($url_insert) . $name_upload;
$action = move_uploaded_file($file['tmp_name'],$name_insert);
$data = array( 'customer_resume' => $name_upload );
$format = array( '%s' );
$success=$wpdb->insert( $table, $data, $format );
$msg_true = 'Upload ok ';
} else {
$msg_error = 'Upload error';
}
}
$result = !isset($msg_error);
$msg = array();
if($result) {
$msg['error'] = 'true';
$msg['true'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['false'] = $msg_error;
}
header('Content-Type: application/json');
echo json_encode($msg);
}
And the HTML where I try to show the success or error message
<div id="error_message"></div>
<div id="success_message"></div>
When I click on Submit button I everything works fine and saved in database but there is no indication wheather is success or no. I've tried to add this msg's but still nothing shows on page.

PHP side:
You need to print same variable for success and failure:
if($result) {
$msg['error'] = 'true';
$msg['msg'] = $msg_true;
} else {
$msg['error'] = 'false';
$msg['msg'] = $msg_error;
}
JavaScript Side:
The AJAX response will come as
data.error -> true or false.
data.msg -> Success or Error message depending upon program logic.
...
success: function(data){
$('#success_message').fadeIn().html(data.msg);
...

What is hiding behind "ajax.ajax" ?
Also if you want to show your data you need to use "msg"
success: function(msg){
$('#success_message').fadeIn().html(msg);
setTimeout(function() {
$('#success_message').fadeOut("slow");
}, 2000 );
}

Related

Wordpress - Javascript redirect after login success not working

I'm building my wordpress login page, everything is working fine. So I decided to implement facebook social login using their SDK. Social login works fine and login successfully.
The problem is that after login the user should be directed to the homepage of the website "www.mywebsite.com". I tried to manage the redirect with javascript code, but after successful login no redirection happens.
Can anyone help me figure out what I'm doing wrong?
This is the part where I'm trying to create the redirect
jQuery.post(ajaxurl, data, function(response) {
if (response.success) {
wp_safe_redirect( '/' );
exit;
} else {
document.getElementById('login-form-message').innerHTML = response.message;
}
});
This is the complete code that concerns the social login of facebook
/* Manage Social Login Script */
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxx',
cookie : true,
xfbml : true,
version : 'v15.0'
});
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
document.getElementById('facebook-login-button').addEventListener('click', function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', {fields: 'name,email'}, function(response) {
var data = {
'action': 'facebook_login',
'facebook_id': response.id,
'access_token': FB.getAuthResponse().accessToken,
'email': response.email,
'username': response.name
};
jQuery.post(ajaxurl, data, function(response) {
if (response.success) {
wp_safe_redirect( '/' );
exit;
} else {
document.getElementById('login-form-message').innerHTML = response.message;
}
});
});
} else {
document.getElementById('login-form-message').innerHTML = 'User cancelled login or did not fully authorize.';
}
}, {scope: 'email'});
});
}
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
This is the PHP code that handles the ajax request
//** Facebook Login AJAX Handler **/
function facebook_login_handler() {
// Verify ID token
$facebook_id = $_POST['facebook_id'];
$access_token = $_POST['access_token'];
$email = $_POST['email'];
$username = $_POST['username'];
$response = wp_remote_get( 'https://graph.facebook.com/v3.3/' . $facebook_id . '?access_token=' . $access_token );
$facebook_response = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! isset( $facebook_response['id'] ) ) {
$response = array(
'success' => false,
'message' => 'Invalid Facebook ID token'
);
echo json_encode( $response );
wp_die();
}
// Check if the user already exists in our database
$user = get_user_by( 'email', $email );
if ( ! $user ) {
$user = get_user_by( 'login', $username );
}
if ( $user ) {
// Update user meta with Facebook ID
update_user_meta( $user->ID, 'facebook_id', $facebook_id );
// Log the user in
wp_set_current_user( $user->ID );
wp_set_auth_cookie( $user->ID );
$response = array(
'success' => true,
'message' => 'Login successful'
);
} else {
// If the user does not exist, create a new account
$user_data = array(
'user_login' => $username,
'user_email' => $email,
'user_pass' => wp_generate_password()
);
$user_id = wp_insert_user( $user_data );
if ( is_wp_error( $user_id ) ) {
$response = array(
'success' => false,
'message' => $user_id->get_error_message()
);
echo json_encode( $response );
wp_die();
} else {
update_user_meta( $user_id, 'facebook_id', $facebook_id );
wp_set_current_user( $user_id );
wp_set_auth_cookie( $user_id );
$response = array(
'success' => true,
'message' => 'Registration and login successful'
);
}
}
echo json_encode( $response );
wp_die();
}
Man, wp_safe_redirect() - this is wordpress function, not javascript...
Use location.href = 'Your Url'
After several hours of searching I figured out that the problem lay in: jQuery.post(ajaxurl, data, function(response). So I changed the code as follows and the redirect is working fine.
From this
jQuery.post(ajaxurl, data, function(response) {
if (response.success) {
location.href = '<?php echo home_url(); ?>';
} else {
document.getElementById('login-form-message').innerHTML = response.message;
}
});
To this
// Invia la richiesta ajax al server per elaborarla
$.ajax({
type: 'POST',
url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
data: data,
success: function(response) {
console.log(response);
if (response.success) {
// reindirizzamento alla pagina home
window.location.href = '/';
} else {
// reindirizzamento alla pagina di login
window.location.href = '/experimental-layout';
}
}
});

How to upload an image to server directory using ajax?

I have this ajax post to the server to send some data to an SQL db :
$.ajax({
method: "POST",
url: "https://www.example.com/main/public/actions.php",
data: {
name: person.name,
age: person.age,
height: person.height,
weight: person.weight
},
success: function (response) {
console.log(response)
}
})
in the server i get this data with php like this :
<?php
include "config.php";
if(isset ( $_REQUEST["name"] ) ) {
$name = $_REQUEST["name"];
$age = $_REQUEST["age"];
$height = $_REQUEST["height"];
$weight = $_REQUEST["weight"];
$sql = "INSERT INTO persons ( name, age, height, weight )
VALUES ( '$name', '$age', '$height', '$weight' )";
if ($conn->query($sql) === TRUE) {
echo "New person stored succesfully !";
exit;
}else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit;
}
};
?>
I also have this input :
<input id="myFileInput" type="file" accept="image/*">
and in the same directory as actions.php i have the folder /images
How can i include an image ( from #myFileInput ) in this ajax post and save it to the server using the same query in php ?
I have searched solutions in SO but most of them are >10 years old,i was wondering if there is a simple and modern method to do it,i'm open to learn and use the fetch api if its the best practice.
You should use the formData API to send your file (https://developer.mozilla.org/fr/docs/Web/API/FormData/FormData)
I think what you are looking for is something like that:
var file_data = $('#myFileInput').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'https://www.example.com/main/public/actions.php',
contentType: false,
processData: false, // Important to keep file as is
data: form_data,
type: 'POST',
success: function(php_script_response){
console.log(response);
}
});
jQuery ajax wrapper has a parameter to avoid content processing which is important for file upload.
On the server side, a vrey simple handler for files could look like this:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'];
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
via ajax FormData you can send it . refer here . Note : data: new FormData(this) - This sends the entire form data (incldues file and input box data)
URL : https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/
$(document).ready(function(e) {
$("#form").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data) {
if (data == 'invalid') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e) {
$("#err").html(e).fadeIn();
}
});
}));
});
If you are not averse to using the fetch api then you might be able to send the textual data and your file like this:
let file=document.querySelector('#myFileInput').files[0];
let fd=new FormData();
fd.set('name',person.name);
fd.set('age',person.age);
fd.set('height',person.height);
fd.set('weight',person.weight);
fd.set('file', file, file.name );
let args={// edit as appropriate for domain and whether to send cookies
body:fd,
mode:'same-origin',
method:'post',
credentials:'same-origin'
};
let url='https://www.example.com/main/public/actions.php';
let oReq=new Request( url, args );
fetch( oReq )
.then( r=>r.text() )
.then( text=>{
console.log(text)
});
And on the PHP side you should use a prepared statement to mitigate SQL injection and should be able to access the uploaded file like so:
<?php
if( isset(
$_POST['name'],
$_POST['age'],
$_POST['height'],
$_POST['weight'],
$_FILES['file']
)) {
include 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$obj=(object)$_FILES['file'];
$name=$obj->name;
$tmp=$obj->tmp_name;
move_uploaded_file($tmp,'/path/to/folder/'.$name );
#add file name to db????
$sql = 'INSERT INTO `persons` ( `name`, `age`, `height`, `weight` ) VALUES ( ?,?,?,? )';
$stmt=$conn->prepare($sql);
$stmt->bind_param('ssss',$name,$age,$height,$weight);
$stmt->execute();
$rows=$stmt->affected_rows;
$stmt->close();
$conn->close();
exit( $rows ? 'New person stored succesfully!' : 'Bogus...');
};
?>

Ajax ResponseText is getting true but can't write to div

Ajax Code:
jQuery(document).ready( function($) {
var valueCheck;
$('#acf-field_5cdc07b87c8f8-field_5cdc08405814f').on( 'change', function () {
valueSelect = $(this).val();
if ( parseInt ( valueSelect ) > 0 ) {
$.ajax( ajaxurl, {
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: { action: 'hesaplama', // The name of the WP action
value: valueSelect, // the dataVAlues
},
dataType: 'json',
success: function ( response ) { // to develop in case of success
if ( response.success ) {
sonucum = response.html; // Here we get the results of the PHP remote function
$('#xcvb').html( sonucum );
}
else {
$('#xcvb').html( '<span>Bu #id: ' + valueSelect + ' ye ait bir içerik bulunamadı.</span>' );
}
},
error: function ( errorThrown ) { // to develop in case of error
console.log( errorThrown );
},
});
}
});
});
Functions.PHP :
function hesaplayici(){
$id = (int) $_POST['value'];
$sonucum = the_field('sertifika_aciklamasi', $id);}
Responsetext show on console but can't write to my div ( id: #xcvb ) Any one can help me about this ?
https://up.uac.ist/images/2019/06/17/Screenshot_2.png
https://up.uac.ist/images/2019/06/17/Screenshot_3.png
Looks like you have a few things wrong here. This is the proper way to use Ajax with Wordpress.
$.ajax({
type: 'POST',
url: ajax_object.ajax_url,
data: {
action: 'hesaplama',
value: valueSelect
},
error: function (data) {
console.log(data);
},
success: function (data) {
console.log(data);
if ( data == '') {
$('#xcvb').html( '<span>Bu #id: ' + valueSelect + ' ye ait bir içerik bulunamadı.</span>' );
}
else {
$('#xcvb').append( data );
}
}
});
You should try echoing your response.
function hesaplayici(){
$id = $_POST['value'];
$sonucum = the_field('sertifika_aciklamasi', $id);
echo $sonucum;
die();
}
add_action( 'wp_ajax_send_hesaplayici', 'hesaplayici' );
add_action( 'wp_ajax_nopriv_hesaplayici', 'hesaplayici' );
Please try it like this:
on php side:
$return = ['myvarname' => 'your data here'];
echo json_encode($return);
exit();
on js side:
success: function ( response ) {
$(#idofyourdiv).html(response.myvarname);
}

How to get ajax responses from php?

I run the ajax via this php with js:
function ajax_Person() { ?>
<script type="text/javascript">
jQuery("#createCat").on("click", function(e){
e.preventDefault();
person();
});
function person(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_person', catName: jQuery('#newCat').val(), catDesc: jQuery('#descRiption').val() },
success: function(data) {
jQuery(".modal-body").html("Done!");
}
});
}
</script>
<?php }
Then I run
function data_person(){
$catname = $_POST['catName'];
$catdesc = $_POST["catDesc"];
$cat_ID = get_cat_ID( sanitize_title_for_query($catname) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = $catname;
$cat_desc = $catdesc;
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
echo 'Category added successfully';
} else {
echo 'Error while creating new category';
}
} else {
echo 'That category already exists';
}
}
In both cases I get "Done!" as a response. I need to set up responses based on:
if( wp_insert_category( $my_cat ) ) {
echo 'Category added successfully';
} else {
echo 'Error while creating new category';
}
} else {
echo 'That category already exists';
}
The above php bits work if I run them as a standard php.
try:
on your php
if( wp_insert_category( $my_cat ) ) {
echo json_encode( 'Category added successfully');
} else {
echo json_encode( 'Error while creating new category');
}
} else {
echo json_encode( 'That category already exists');
}
on js instead
$(".modal-body").html("Done!");
use
$(".modal-body").html(data);

Get Success Results From AJAX call

I am trying to get the results from an AJAX call, but I keep getting the error results of the function and I have no idea why.
Here is the javascript:
var curfrndurl = "http://www.website.com/app/curfrnd.php?frndid=" + secondLevelLocation + "&userid=" + items;
$("#loadpage1").click(function(event){
event.preventDefault();
$.ajax({
url: curfrndurl,
dataType: 'json',
type: "GET",
success: function (data){
if (data.success) {
alert("Hi");
$("#curstatus").html(data);
$("#curstatus2").hide();
$("#subtform").hide();
}
else
{
alert("Bye");
$("#curstatus2").html(data);
$("#curstatus").hide();
$("#addform").hide();
}
},
error: function() {
alert('Doh!');
}
});
});
The PHP file is:
<?php
$userdbme = $_GET['userid'];
$frndid = $_GET['frndid'];
$query2 = mysql_query("SELECT * FROM follow WHERE yoozer1='$userdbme' AND yoozer2='$frndid' ORDER BY followid DESC LIMIT 0,1");
$numfriends = mysql_num_rows($query2);
if ($numfriends!=0)
{
echo json_encode(array(
'success' => true
//'user_name' => $userdb
));
echo "<h4>Current Friends</h4>";
}
else {
echo json_encode(array('success' => false));
echo "<h4>Not Friends</h4>";
}
?>
Any help would be greatly appreciated! Thanks!
If you want to echo JSON data, then you need to make sure you don't echo anything else before or after the data.
echo json_encode(array(
'success' => true
));
echo "<h4>Current Friends</h4>";
This is not parsable as JSON, because of the "extra" stuff after the JSON data. Try this:
echo json_encode(array(
'success' => true,
'html' => "<h4>Current Friends</h4>"
));
Then you can do: $("#curstatus").html(data.html);

Categories

Resources