String data not sending with $.ajax call to php page - php

When i pass number with function argument for sending using ajax its working properly but when i pass string such as given below its not receiving in php page.
function loadState(country) {
$.ajax({
url: 'cardstate.php',
type: 'get',
data: { 'country': country },
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data);
}
});
}
loadState("Pakistan")
// cardstate.php:
$country = $_GET['country'];
echo $country; // not receving string while when i put number its receiving

In your cardstate.php you should use json_encode
// cardstate.php:
$country = $_GET['country'];
echo json_encode($country); // not receving string while when i put number its receiving

function loadState(country) {
$.ajax({
url: 'cardstate.php',
type: 'GET',
data: 'country='+country, // <--- changed this as its GET
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data.country); // <---- made this change
}
});
}
loadState("Pakistan")
And in your PHP, use json_encode()
// cardstate.php:
$country = $_GET['country'];
echo json_encode(array('country' => $country));

Related

Unable to receive response from PHP to Ajax

This is my absolute first try on the subject:
I'm sending data throw email using javascript and PHP.
I have read previous responses on the subject, but I can't make it work.
My js code:
const messagesend = document.getElementById('message_form');
messagesend.addEventListener('submit', (eee) => {
eee.preventDefault();
var messageData = new Object();
messageData.name = document.getElementById('conname').value;
messageData.email = document.getElementById('conemail').value;
messageData.message = document.getElementById('conmessage').value;
messageData.verification = 'drovarcrete_message';
var messageString = JSON.stringify(messageData);
$.ajax({
type: "POST",
contentType: 'application/json',
url: 'messageSender.php',
data: messageString,
dataType: 'json',
success: function(data) {
alert("Message send.");
$('#contactModal').modal('hide');
$('#email_success_info').modal('show');
}
});
});
$("#modal2_close").click(function() {
$('#email_success_info').modal('hide');
});
My PHP works fine, with last line being:
echo 'Message send';
I have also tried: echo json_encode(array('success' => true));
However, the alert message doesn't show.
Use the following and see what is going on with your request:
$.ajax({
type: "POST",
contentType: 'application/json',
url: 'messageSender.php',
data: messageString,
dataType: 'json',
success: function(data) {
alert("Message send.");
$('#contactModal').modal('hide');
$('#email_success_info').modal('show');
},
error: function (error) {
console.log(error.responseText);
}
});

AJAX api request missing some data at controller $_GET

When i'm trying to send data(url) to API with ajax request, PHP CI controller not considering all parameters in $_GET. it just accepting up to &.
Is there any error in passing parameters? Please help. I tried passing direct url and encodeURI.
JQuery code
$.ajax({
type: "GET",
url: "<?= ROOT?>welcome/ajaxapiget",
data: encodeURI(http://localhost/webapi/list?categories[]=3&categories[]=12),
cache: false,
success: function (data) {
alert(data);
}
});
PHP
function ajaxapiget() {
$url = $_GET;`//its getting url as http://localhost/webapi/list?categories[]=3`
$curl = curl_init();
........
........
response $response;
}
also tried like this
$.ajax({
type: "GET",
url: "<?= ROOT?>welcome/ajaxapiget",
data: 'url=http://localhost/webapi/list?categories[]=3&categories[]=12)',
cache: false,
success: function (data) {
alert(data);
}
});
PHP
function ajaxapiget() {
$url = $_GET(url);`//its getting url as http://localhost/webapi/list?categories[]=3`
$curl = curl_init();
........
........
response $response;
}
When i alert
before sending request
url=http://localhost/webapi/courselist?categories[]=15&categories[]=17
response from controller (alert at ajax success)
$url = $_GET('url');
echo $url
alert response
http://localhost/webapi/courselist?categories[]=15
Try this
JQuery code
$.ajax({
type: "GET",
url: "<?= ROOT?>welcome/ajaxapiget",
data: {url:'http://localhost/webapi/list?categories[]=3&categories[]=12'},
cache: false,
success: function (data) {
alert(data);
}
});
PHP code
function ajaxapiget() {
$url = $this->input->get('url');//Getting $url as http://localhost/webapi/list?categories[]=3&categories[]=12
$curl = curl_init();
........
........
response $response;
}
Use $this->input->get() instead of $_GET[] in Codeingiter
Finally i solved this with encodeURIComponent
$.ajax({
type: "GET",
url: "<?= ROOT?>welcome/ajaxapiget",
data: 'url=http://localhost/webapi/list?' + encodeURIComponent('categories[]=15&categories[]=17'),
cache: false,
success: function (data) {
alert(data);
}
});
now the result is
http://localhost/webapi/courselist?categories[]=15&categories[]=17
encodeURIComponent will encode everything with special meaning, so you
use it for components of URIs
Source : https://stackoverflow.com/a/4540785

Jquery ajax response error

Here is a partial example of what I am trying to achieve.
I am trying to retrieve a value from ajax but the javascript result.success variable is undefined. I have the following:
PHP:
$result = array ("success" => null, "html" => "");
$result['success'] = true;
$result['html'] = "test";
echo json_encode($result);
Javascript/jQuery:
var ID = 1
$.ajax({
type: 'POST',
url: '/ajax/load.php',
contentType: "application/json; charset=utf-8",
datatype: 'json',
data: {ID: ID},
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function(result) {
if (result.success) {
// do something
}
});
The response I am getting from ajax (retrieved from chrome dev tools) is {"success":true,"html":"Test"}
This looks fine to me however in the JavaScript result.success is undefined. I believe this will be simple I just can't see where the issue lies..
Your error is here:
datatype: 'json',
Javascript is case sensitive and the property is dataType:
dataType: 'json',
Because of that, jQuery is not being told to automatically parse the JSON, so the result is just treated as html or plain text.
You also need to remove the content-type header because that specifies the content type for the request not response. You are sending form/url encoded in the request, not JSON.
$.ajax({
type: 'POST',
url: '/ajax/load.php',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: {ID: ID},
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
success: function(result) {
if (result.success) {
// do something
}
} // Maybe your forgot this
});
in other words - Basic Debugging
in your PHP page put this on top of the page (you are accepting only json response but probably your response headers content type is text/html
header('Content-type: application/json');

jQuery Ajax posting not working

My jQuery ajax posting is not working. Here is the javascript
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: postData,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
I am saving the data to be posted inside a hidden div like
<div class='WrapperDiv hidden'>{"post_id":392,"url":"http:\/\/www.wordpress-site\/post\/post-title\/","title":"SEO Friendly title"}</div>
All I am getting in return from the post.php page is an empty array. Here is my code for post.php
<?php
if(isset($_POST)){
print_r($_POST);
} else {
echo "0";
}
?>
Any Idea whats wrong?
EDIT : Its working after I removed
contentType: "application/json",
dataType: 'json'
What about something like this:
var postData = "data=" + encodeURCIComponent($buttonWrapper.html());
Than in PHP:
echo $_POST["data"];
Than parse it or something....
Couple of things to try,
Try to pass the data directly in to the data object first. If it
works then you can debug and see why it's not ready your hidden div.
instead of $buttonWrapper.html try $buttonWrapper.text();
function SocialButtons() {
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
var postData = $buttonWrapper.**text**();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: **{'id':1}**,
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Inside your jQuery ajax call, your data is not set to $_POST variable names. Hence why nothing is showing
Try changing your function to this:
function SocialButtons() {
var buttonWrapper = jQuery('.WrapperDiv');
if (buttonWrapper.length){
var postData = buttonWrapper.html();
jQuery.ajax({
type: 'POST',
url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
data: {postData: postData},
cache: false,
success: function(data) {
console.log(data);
},
contentType: "application/json",
dataType: 'json'
});
}
}
Then you should have a $_POST['postData'] variable on your print_r or var_dump of $_POST.
Its working after I removed
contentType: "application/json",
dataType: 'json'

undefined object from php json

I try to send json array to ajax (from PHP to jQuery)
in my PHP script:
$value = 'test';
echo json_encode(
array(
'key' => $value
)
);
exit;
Javascript side:
function sweety_ajax(url, datas)
{
$.ajax({
url: url,
type: 'POST',
cache: false,
dataType: 'json',
data: datas,
success: function(r){
return r;
}
});
}
I get the correct value with r.key inside the function, but I would like to get my "r" object like this:
var response = sweety_ajax(url, datas);
alert(response.key);
But the problem is that response object is undefined and cannot get the value of key...
Any idea?
AJAX request in asynchronous. You need to pass a callback if you want to do this.
function sweety_ajax(url, datas, callback)
{
$.ajax({
url: url,
type: 'POST',
cache: false,
dataType: 'json',
data: datas,
success: callback
});
}
sweety_ajax(url, datas, function(response) {
alert(response.key);
});

Categories