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

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);
}

Related

Ajax response isn't showed on page

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 );
}

Switching from GET to POST

I have the following Ajax request:
// JavaScript
function myFunc(pid) {
$.ajax({
type : "GET",
url : "testback.php",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
// PHP
require_once ("dbconnect.php");
if (isset ( $_GET ['q'] )) {
if ($_GET ['q'] == "testrequest") {
$pid = $_GET ['pid'];
$query = "SELECT * FROM `tab1` WHERE `pid` = " . $pid;
$json = array ();
if ($result = $link->query ( $query )) {
while ( $row = $result->fetch_assoc () ) {
array_push ( $json, $row );
}
}
header ( "Content-type: application/json; charset=utf-8" );
die ( json_encode ( $json ) );
exit ();
}
die ();
}
It sends a request to my MySQL database and returns the expected output.
However, I now want to switch to POST, rather than GET.
When I just swap GET with POST:
// JavaScript
function myFunc(pid) {
$.ajax({
type : "POST", // POST
url : "testback.php",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
// PHP
require_once ("dbconnect.php");
if (isset ( $_POST ['q'] )) { // POST
if ($_POST ['q'] == "testrequest") { // POST
$pid = $_POST ['pid']; // POST
$query = "SELECT * FROM `tab1` WHERE `pid` = " . $pid;
$json = array ();
if ($result = $link->query ( $query )) {
while ( $row = $result->fetch_assoc () ) {
array_push ( $json, $row );
}
}
header ( "Content-type: application/json; charset=utf-8" );
die ( json_encode ( $json ) );
exit ();
}
die ();
}
I get the following error in the console:
parsererror SyntaxError: Unexpected end of JSON input
The request payload is still q=testrequest&pid=1.
What else do I need to change, in order to switch from GET to POST?
In your Ajax function you need to omit the content type as it is already defined in the Ajax Call. Delete the line "contentType : "application/json; charset=utf-8" shown below:
$.ajax({
type : "GET", // Or POST
url : "testback.php",
contentType : "application/json; charset=utf-8", // REMOVE THIS LINE!!
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
It should work just fine after that!
Cheers!
The $.ajax works but i advise to use $.get or $.post instead.
Be carrefull about your url when you use $.get, browsers have caracter limits (around 2000 caracters).
if (urlGet.length < 2000) {
// GET less than 2000 caractères use $.GET
$.get(urlGet, function () {
}).done(function (data) {
//OK do stuff with data returned
}).fail(function () {
//err
});
} else {
//Use $.POST params : { name: "John", age: "25" }
$.post(urlPost, { name: "John", age: "25" }, function () {
}).done(function () {
//ok
}).fail(function () {
//fail
});
}
You can create a function with this code and then have a simple call of your WebServices.
Here is the jQuery doucmentation :
$.GET https://api.jquery.com/jquery.get/
$.POST https://api.jquery.com/jquery.post/
Hope this help ;)

Sending PHP values with AJAX

I am trying to delete images with Ajax and all the php seems to work except when I try to send variables to another php document.
Php that shows and grabs neccessary values.
// show images
$image_display = "";
foreach(glob($pathimages.'*') as $filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$name_only = basename($filename, ".".$ext);
$image_display .= "<img src=\"images/" .$targetID."/" .$name_only.".".$ext. "\" width=\"30\" />
<a onclick=\"DeleteImage('".$name_only."','".$ext."','".$targetID"'); return false;\" href=\"javascript:;\">X</a>
<br />";
}
.JS document, I get the sent and the success messages when pressing the X
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
delete_imgs.php document
include('session_check.php');
$name_only = $_POST['name_only'];
$ext = $_POST['ext'];
$targetID = $_POST['targetID'];
$pathimages = "images/$targetID/";
unlink($pathimages . $name_only .".". $ext);
echo "Deleted";
Any thoughts are more than welcome since I have banged my brain out of my head by now ...!
Cheers!
Try with async:false
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
async : false,
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
Maybe that can help

jQuery autocomplete ajax request not displaying returned data

When I see on the debug developer tool ajax request responded with data but the data is not rendered in the text box. The data contains some special characters as you can see in the picture.
What is exactly wrong with the response function ? What (like utf-8 encoding maybe) should I add to the ajax call to display the special character ?
html:
<select name="selCat">
<option>....</option>
</select>
<input class="col-3" type="text" id="txtPOI" name="txtPOI" />
jquery:
$("#txtPOI").autocomplete({
source: function(request, response) {
$.ajax({
url: '<?php echo site_url("crowd/get_POIs") ?>',
data: {cat: selectedCode, q: request.term},
dataType: "json",
type: "post",
success: function(data) {
response(data);
},
fail : function ( jqXHR, textStatus, errorThrown ) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},minLength: 3
});
}
});
Controller :
function get_POIs(){
$cat = $this->input->post('cat');
$q = $this->input->post('q');
//echo $cat;
if (isset($cat) && isset($q)){
$cat = strtolower($cat);
$q = strtolower($q);
$data=$this->crowd->get_POIs($cat,$q);
//echo "aa";
$a_json = array();
if(count($data) > 0){
foreach ($data as $row){
$a_json_row["title"] = $row->title;
$a_json_row["contentid"] = $row->contentid;
$a_json_row["latitude"] = $row->latitude;
$a_json_row["longitude"] = $row->longitude;
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
}
}
}
Model :
function get_POIs($cat, $q){
$this->db->DISTINCT();
$this->db->select('title, a.contentid, latitude, longitude, address');
$this->db->from('attraction a');
$this->db->join('geographicdata g', 'a.contentid = g.contentid', 'left');
$this->db->where('cat3 = "'.$cat.'"');
$this->db->where('title like "%'.$q.'%"');
$this->db->order_by('title','ASC');
$query = $this->db->get()->result();
//die(var_dump($query));
//echo $this->db->get_compiled_select();
return $query;
}
I managed to solve this problem by modifying the code inside the success event. Here how I did it.
change from
success: function(data) {
response(data);
}
to
success: function(data) {
response( $.map( data, function( item )
{
return{
label: item.title,
value: item.title,
contentid: item.contentid,
latitude: item.latitude,
longitude: item.longitude
}
}));
}

Empty $_POST when posting from jquery.ajax

I am doing some Add, Edit, and Delete for my project in school. The codes in the add module went well, in fact I've added few records. Then, here comes the Edit module, at first it was quite good, similar codes was used from the add module. But as I try and try, the post in the edit module was empty.
here's my edit codes:
$(".careersEdit").click(function () {
var careersTableSelect = encodeURIComponent($("input:radio[name=careersTableSelect]:checked").val());
if (careersTableSelect > 0) {
$(".careersEditForm_load").show();
$(".careersEditForm_error").hide();
$(".careersEditForm").hide();
var dataStringCareersEdit = 'careersTableSelect=' + careersTableSelect;
$.ajax({
type: "POST",
url: "admin/careers/process/careersEditGet.php",
data: dataStringCareersEdit,
beforeSend: function(){
alert(dataStringCareersEdit);
},
success: function () {
setTimeout("", 5000);
fetchResult();
},
error: function () {
alert("Post Error");
}
});
function fetchResult() {
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "POST",
dataType: "json",
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result['position']);
$("input#careersEditCompany").val(result['company']);
$("input#careersEditLocation").val(result['location']);
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
}
} else {
$(".careersEditForm").hide();
$(".careersEditForm_load").hide();
$(".careersEditForm_error").show();
}
});
Here's the careersEditGet.php:
<?php
include('connect.php');
error_reporting(0);
$careersTableSelect = $_POST['careersTableSelect'];
//$careersTableSelect = $careersTableSelect + 1;
//echo $careersTableSelect;
$query = "SELECT * FROM atsdatabase.admincareers WHERE refNum ='" . $careersTableSelect . "' LIMIT 0 , 30";
$runQuery = mysql_query($query);
if (!$runQuery) {
die('Could not enter data: ' . mysql_error());
}
$result = mysql_fetch_row($runQuery);
$array = array(
'position' => "" . $result[1] . "",
'company' => "" . $result[2] . "",
'location' => "" . $result[3] . "",
);
echo json_encode($array);
mysql_close($connection);
?>
Yes, the code is ugly/wrong/crap, I'm quite new to jquery stuffs, about 3-4 days. To those that will help, please do correct me. I wanna learn this jquery ajax stuff. Gracias
Maybe try passing data in more common way:
change
data: dataStringCareersEdit,
to
data: { "careersTableSelect" : careersTableSelect },
Call your ajax function once like,
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "POST",
dataType: "json",
data: {careersTableSelect: careersTableSelect},
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result.position);// json not array
$("input#careersEditCompany").val(result.company);// json not array
$("input#careersEditLocation").val(result.location);// json not array
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
Thanks guys for all the effort to answer this question, I've consulted to a friend who's a web developer, taught me how to properly use ajax in jquery. ;)
You are doing something fundamentally wrong when u are posting Data from jQuery.Ajax..
The data should be an object and the key should be the name of the server side POST variable which will be used later in the PHP ...
Example :
data : {"server_side_vriable" : "Your_data_to_Post" }
......
var dataStringCareersEdit = 'careersTableSelect=' + careersTableSelect + "&careersTableSelect=" + careersTableSelect;
$.ajax({
type: "POST",
url: "admin/careers/process/careersEditGet.php",
data: {"careersTableSelect" : dataStringCareersEdit},
beforeSend: alert(dataStringCareersEdit),
success: function () {
alert("Fetching Result");
setTimeout("", 3000);
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "GET",
dataType: "json",
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result['position']);
$("input#careersEditCompany").val(result['company']);
$("input#careersEditLocation").val(result['location']);
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
},
error: function () {
alert("Post Error");
}
});

Categories

Resources