Unable to receive response from PHP to Ajax - php

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

Related

$.ajax $_POST to php returns empty array [duplicate]

I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Base on lonesomeday's answer, I create a jpost that wraps certain parameters.
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
Usage:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
you can post data using ajax as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {
"name":"jonsa",
"e-mail":"qwerty#gmail.com",
"phone":1223456789
};
$.ajax({
type: 'POST',
url: '/form/',
data: Data,
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}

Ajax Post and CodeIgniter not working

I am trying to echo back code I received from Ajax. But it does not work when I am using contentType:false, processData:false.
Here is my ajax. The url is correct. If I comment out the line with post_data['file'] and contentType:false, processData:false I will be able to get the echo, but as soon as contentType:false, processData:false is in I cannot get anything.
post_data = {};
post_data['file']= document.getElementById('fileToUpload').files[0];
post_data['paper-type']=$("#paper-input :selected").val();
$.ajax({
url:'/admin/upload_paper',
data: post_data,
type: 'post',
contentType: false,
processData: false,
success: function(data){
console.log(data);
},
error: function(data){
console.log(data+"error");
}
});
Here is the code snippet from CI
public function upload_paper(){
echo $this->input->post('paper-type');
echo "testing";
echo "testing2";
}
Does anyone know what that is? Thank you.
instead of doing this:
post_data['paper-type']=$("#paper-input :selected").val();
try
var val = $("#paper-input :selected").val();
and in ajax:
$.ajax({
url:'/admin/upload_paper',
data: {'paper-type':val},
type: 'post',
success: function(data){
console.log(data);
},
error: function(data){
console.log(data+"error");
}
});

How to save ajax post response in to database?

My code is here.
<script type="text/javascript">
function test(){
alert('return sent');
$.ajax({
type: "POST",
url: "http://remotewebsite.com/process.php",
data: somedata;
dataType:'text'; //or HTML, JSON, etc.
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
</script>
But how can i save that response coming from remote website in to my database?
And how can i send multiple input?
$.ajax({
type: "POST",
url: "http://remotewebsite.com/process.php",
data: somedata;
dataType: 'text'; //or HTML, JSON, etc.
success: function(response) {
alert(response);
$.ajax({
type: "POST",
url: "youphppagewhereyoudothesavingindatabase",
data: response;
dataType: 'text'; //or HTML, JSON, etc.
success: function(data) {
console.log(data);
alert("Saved in database")
}
});
}
});
Have it something like this

How to pass value to PHP Script

I have code in my html file as below. I am using jQuery Mobile
$.ajax({
type: "GET",
url: "http://localhost/owner_pickup.php",
cache: false,
dataType:'json'
success: function(data)
{
// On success
}
});
owner_pickup.php returns me data by executing query. Now i need to pass a value which i would read in my owner_pickup.php file.
Kindly suggest me how would we pass the value
in your php file:
$value = array(
"dat_1" => "this is data number 1",
"dat_2" => "this is data number 2"
);
echo json_encode($value);
in your jquery finction:
$.ajax({
type: "GET",
url: "http://localhost/owner_pickup.php",
cache: false,
dataType:'json'
success: function(data)
{
var value1 = data.dat_1;
var value2 = data.dat_2;
}
});
please look at this answers:
retrieve multiple values from ajax call
if you don't know how to use JSON please google it.
edit:
pass a value to the php:
$.ajax({
type: "GET",
url: "http://localhost/owner_pickup.php",
cache: false,
data: {
first_value:50,
second_value:55
}
dataType:'json'
success: function(data)
{
var value1 = data.dat_1;
var value2 = data.dat_2;
}
});
in the php:
if(isset($_GET['first_value']))
$first = $_GET['first_value'];
$.ajax({
type: "GET",
url: "http://localhost/owner_pickup.php",
data: {param1: 123, param2: "text value"},
cache: false,
dataType:'json',
success: function(data) { // On success }
});
$.ajax({
type: "GET",
url: "http://localhost/owner_pickup.php",
data:{key1:value1}
cache: false,
dataType:'json'
success: function(data)
{
}
});
In php aaccept it as
<?php
$_REQUEST['key1'];
?>

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'

Categories