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 ;)
Related
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);
}
I have the following jquery code that posts data to a php file and works fine on localhost. But when this code is now on the server the script returns an error instead of data.
$.ajax({
type: 'POST',
url: 'scripts/info.php',
data: {
accountNumber: accountNumber,
agentName: name
},
success: function( data ) {
alert(data)
},
error: function(xhr, status, error) {
// check status && error
alert(status)
}
});
This is the code in the php file that handles the post request:
$args0 = array(
'accountNumber' => $_POST['accountNumber'],
'dateReceived' => date("Y-m-d"),
'firstNames' => $_POST['agentName'] '
'regNumber' => $_POST['accountNumber'],
'surname' => $_POST['agentName']
);
try {
$client = new SoapClient(WSDL_URL, array(
'trace' => 1,
'exceptions' => true,
'connection_timeout' => 300));
$params = array(
'arg0' => $args0,
);
$client->__setLocation(WSDL_LOCATION);
$response = $client->upload($params);
$response = $client->__getLastResponse();
echo $response;
Please help
$.ajax({
type:"post",
url:"/pay/index.php?submit_order=yes",
dataType:'json',
data:{
'rmb': $('#rmb').val(),
'couponid': $('#cid').val(),
'title' :$('#title').text(),
'user' :$('#user').text(),
'phone' :$('#phone').text(),
'code' :$('#code').text(),
'size' :$('#size').text(),
'isinvoice':$('[name=isinvoice]').val()
},
beforeSend:function(){
beforeSend.attr('disabled',true);
beforeSend.html('submitting').removeAttr('href');
},
success:function(data){
if(data.errorcode==1){
$('.pay-fail').show().text(data.message);
}else{
if(data.url){
location.href=data.url;
}else{
alert('post ok!');
}
}
},
error: function(){
alert('submit error,then try again');
}
})
This is my jQuery ajax for pay. It works on localhost and on server.
I'm triing to load a json data with ajax, but it doesn't work. Everytime ajax call the error function and doesn't call the success function.
my AJAX call :
$(document).on("click", "#myMovies .btn-update", function() {
var id = $(this).parent().data("id");
$.ajax({
url : 'index.php',
type : 'POST',
dataType: 'json',
data : 'id=' + id + '&action=update',
success : function(data){
$('#updateMovie')
.find('[name="title"]').val(data.title).end()
.find('[name="list"]').val(data.list).end();
},
error : function(jqXHR, textStatus, errorThrown){
console.log("error");
alert(textStatus);
alert(errorThrown);
}
});
});
The interessing part of index.php :
else if($_POST['action'] == "update") {
/*getSpecificMovie($_POST['id']);
$movies = getSpecificMovie();
$results = Utils::secureMoviesJSON($movies);
echo $results;*/
header("Content-Type: application/json", true);
$array = array(
'title' => 'test',
'list' => 'test');
echo json_encode( $array, JSON_FORCE_OBJECT );
}
Anyone know where is my mistake ?
Thank you for your answer.
I think the problem is at the 'JSON_FORCE_OBJECT' option. The data type the request expected is a json string. When adding JSON_FORCE_OBJECT to the json_encode function, the json string is not valid for the request.
else if($_POST['action'] == "update") {
/*getSpecificMovie($_POST['id']);
$movies = getSpecificMovie();
$results = Utils::secureMoviesJSON($movies);
echo $results;*/
header("Content-Type: application/json", true);
$array = array(
'title' => 'test',
'list' => 'test');
echo json_encode( $array);
die();
}
Also add a parser for the json to your javascript (parseJSON):
success : function(data){
data = $.parseJSON(data);
$('#updateMovie')
.find('[name="title"]').val(data.title).end()
.find('[name="list"]').val(data.list).end();
},
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
}
}));
}
I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}