Jquery function cant access json object - php

I'm using bootstrap validator to validate my form data. If form is validated I'm posting those data to php. In php I'm returning json string. Even though my post is success and get correct response, I can't access json object.
$('#dealForm')
.bootstrapValidator({
message: 'This value is not valid',
fields: {
deal_description: {
message: 'The deal discription is not valid',
validators: {
notEmpty: {
message: 'The deal discription is required and can\'t be empty'
}
}
}
}
})
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
// Get the form instance
var formObj = $(e.target);
var formURL = formObj.attr("action");
$.ajax({
url: formURL,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
dataType:JSON
}).done(function(data) {
console.log(data);
});
});
debugger output
php
$temp= $_POST['deal_description'];
if(!empty($_FILES['userfile']['name'])){$temp2='has';} else $temp2='no has';
echo json_encode(array(
'message' => $temp,
'test' => $temp2
));

Either set the correct header in php:
header('Content-Type: application/json');
echo json_encode(array(
'message' => $temp,
'test' => $temp2
));
Or use JSON.parse in js:
}).done(function(data) {
data = JSON.parse(data);
console.log(data);
alert(data.mesage);
});
EDIT just noticed you also have a spelling mistake in your js. data.mesage should have two s data.message

Try
.done(function(data) {
var res=$.parseJSON(data);
alert(res.message);
});

Your AJAX request is wrong I think. It should be
function getData(){
$.ajax({
url: formURL,
type: "POST",
data: new FormData(this),
contentType: 'application/json; charset=utf-8',
cache: false,
dataType: 'json'
}).success(function (data) {
console.log(data);
workWithData(data);
}).done(function(e){
console.log("I'm done");
});
}
function workWithData(data){
if (typeof data != 'undefined') {
var jsonData = $.parseJSON(data);
// do stuff with data
}
}
The reason for having it in a second function is that it is a callback. We don't know how long the AJAX request might take, so we must not interrupt execution of the page whilst waiting for a response. By using a callback, when the data eventually arrives it will be processed.
I'd like to recommend you go through this to learn more about AJAX requests http://api.jquery.com/jquery.ajax/

Related

How do I send files(images) in an array in PHP via ajax?

$('.result').click(function(event) {
var st = JSON.stringify(fileList);
$.ajax({
url: 'mailer.php',
type: 'POST',
data: st,
})
.done(function(data) {
console.log(st);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
Mistake
https://i.stack.imgur.com/mtsAP.png
However, if you enter just:
console.log(fileList);
It shows everything correctly
https://i.stack.imgur.com/kNptA.png
PHP
<?php
$data = json_decode($_POST['fileList']);
echo $data;
From the console output in the second image it appears that fileList is an array of File objects. As such you should append them to a FormData object and set that as the data of your $.ajax() call. Try this:
$('.result').click(function(event) {
var fd = new FormData();
fileList.forEach(file => fd.append(file.name, file));
$.ajax({
url: 'mailer.php',
type: 'POST',
data: fd,
contentType: false, // required when sending FormData
processData: false // required when sending FormData
}).done(function(data) {
console.log(data);
}).fail(function() {
console.log("error");
}).always(function() {
console.log("complete");
});
});
From there you will need to use the $_FILES collection in PHP to access the files sent in the request, not $_POST.
https://i.stack.imgur.com/fYbhv.png
108 line
fileList.forEach(file => fd.append(file));

Ajax Form Submission with Files

I have a form that is handled via $.post, sending data to a php script. My client just asked me to include the ability to upload an image using this (and a few other) forms.
I have been googling around on this for about an hour, and haven't seen any evidence that you can actually do this using $.post(), so I wanted to reach out and see if there is a way to do this.
the form is handled this way:
jQuery( '.js-saveProduct' ).click(function(e) {
e.preventDefault();
acSaveProduct( jQuery(this).serializeArray() )
};
var acSaveProduct = function( form ) {
var _data = {
action: 'ac_save_product',
form: JSON.stringify( form )
}
jQuery.post(
ajaxscript.ajaxurl,
_data,
function( response ) {
// Do Stuff
}
);
};
If I console.log(form) after acSaveProduct() is called, the upload fields aren't even in the array of objects that gets logged.
I haven't even started on the PHP side of this, as I know that the form object that gets passed to my PHP function doesn't contain the values I am looking for.
EDIT TO SHOW NEW ATTEMPT
So, trying the technique linked by #Andreas, I'm still having trouble with this. Below is my update jQuery / PHP code:
HTML
<input type="file" name="acImageNew" id="acImageNew">
jQuery
var acSaveProductAlt = function( form ) {
var file_data = jQuery( '#acImageNew' ).prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
jQuery.ajax({
url: the_ajax_script.ajaxurl,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
action: 'ac_ajax_save_product_alt',
success: function( response ) {
alert(JSON.parse(response.success));
}
});
};
PHP
function ac_ajax_save_product_alt(){
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
$response = json_encode(
array(
'success' => true,
)
);
header( "Content-Type: application/json" );
echo $response;
exit;
}
At the end of it all, I get an alert with 0 as the contents of the alert. What am I doing wrong?
Try JSON parsing the response first, then accessing the success key.
jQuery.ajax({
url: the_ajax_script.ajaxurl,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
action: 'ac_ajax_save_product_alt',
success: function( response ) {
alert(JSON.parse(response).success);
}
});

Array and AJAX returning messages after ajax

I have my AJAX working and I can INSERT new data in the database. Basically I can not get an array to echo back into my page. I was wondering, do I need a separate AJAX to get the information from my first AJAX and will it work? Here is my code:
<?
$msg = array ("MSG1"=>"Error","MSG2"=>"Registered");
if(isset($_POST['register'])){
echo $msg['MSG1'];
}
?>
<script>
function Registration(){
var values = {};
values['register'] = '';
$.ajax({
'url' : '',
'type' : 'POST',
'data' : values,
success : function(data){
}
})
}
</script>
How can I get my Array to echo back from AJAX?
How about this one?
formData = {
register: register
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "http://localhost/register.php",
dataType: "json",
data: formData,
success: function(data) {
console.log(data);
//success handler
},
error: function(data) {
//error handler
}
});
about your 'Array to echo back from AJAX', you need to setup if else condition in your 'http://localhost/register.php' . Let say if condition A, "MSG1"=>"Error". If condition B, "MSG2"=>"Registered".
Please refer to this site for your reference.
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

Getting JSON in PHP from jQuery .ajax()

I'm having trouble getting JSON data sent from JavaScript to PHP. Here is my Javascript:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: sendData,
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
Here is how I just test if the data is even being passed to PHP, it always returns back null.
<?php
$nData = json_decode($_POST['nData']);
echo json_encode($nData);
?>
What am I doing wrong?
You are sending the data as raw JSON to PHP, not as POST parameter.
There are two alternatives. The first one leaves your PHP intact:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: {
nData: sendData
},
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
The second one modifies the PHP side alone. You need to read the input stream directly to obtain the raw data.
<?php
$nData = json_decode(file_get_contents('php://input'));
echo json_encode($nData);
This one might be slightly different depending on the server configuration. See the documentation on the input stream wrappers.
Tell your post request that you are sending json object
contentType: "application/json"

Cant get value back from PHP

JavaScript
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
success:function (data) {
if (data==null) { alert("darnit!!!!");}
//$("#response").append(data);
alert(dataString);
}
});
});
in PHP file just a simple
print_r($_REQUEST);
Also tried
echo "got iT!";
But nothing, been looking of over tried differant things but no luck
first //alert (dataString); works
but after the success:function (data) I don't get any alerts - no response within the page!
What am I doing wrong?
There's a SyntaxError in your snippet. I'm not sure if that's also in your real code.
Be sure to use json_encode in your PHP file and dataType: 'json' in jQuery.ajax. And always use an error callback as well. You don't want your application to become indefinitely frozen if something fails.
Something like this:
$.ajax({
url: 'api.php',
data: {
action: 'greet',
foo: 'bar',
baz: 'quux'
},
type: 'POST',
dataType: 'json',
}).then(function (response) {
console.log(response); // DEBUG
if (response.error) {
alert('Greet Error: ' + response.error);
} else {
alert(response.greet);
}
}).catch(function (jqXHR) {
console.log('AJAX Error', jqXHR); // DEBUG
alert('AJAX Error: Request failed');
});
PHP:
<?php
$input = $_POST;
$response = array();
if (!isset($input['action'])) {
$response['error'] = 'Action parameter required';
} else {
if ($input['action'] === 'greet') {
if (!isset($input['foo']) || !isset($input['bar'])) {
$response['error'] = 'Invalid greet request';
} else {
$response['greet'] = 'Welcome home, David!';
}
} else {
$response['error'] = 'Unknown action';
}
}
header('Content-Type: application/json; charset=utf8');
echo json_encode($response);
First: you missed dataType property from ajax function, next, you need to pass json type data, and you had a syntax error in code, try this:
$.ajax({
type : 'POST',
url : 'post.php',
dataType: 'text',
data: {
data_to_pass: dataString
},
success:function (data) {
if (data==null) {
alert("darnit!!!!");
} else {
//$("#response").append(data);
alert(dataString);
}
});
});
in PHP:
$dataString = $_POST['data_to_pass'];
if($dataString) {
echo "got IT!";
}
JQuery ignoring your data return usually means it doesn't understand the format that's being returned, or doesn't know what to expect. Set the dataType to an acceptable format and also double check that your PHP script is actually sending something back to the page in Firebug's console.
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
dataType: 'text',
success:function (data) {
if (data==null) { alert("darnit!!!!");}
//$("#response").append(data);
alert(dataString);
}
});
});
I would like share the following, and I think I've solved the problem.
Besides the fact that I did made a mistake, retrieving the values from the form a bit wrong.
so the first alert gave me name=[Object name], now that was stupid.
The problem of not getting results seemed to be a problem with jquery itself, in my case.
I do not know if it is the same problem other people are having. I replaced the included file of jquery 1.7 with 1.4.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
than with the following code (only from $.ajax).
var dataString = $("#contactForm").serialize();
$.ajax({
type: 'POST',
url: './php/mail.php',
data: dataString,
success: function(msg){
if (msg === 'sent'){
$('#success').text('Message sent!');
} else{
$('#success').text('Mail Error. Please Try Again.!');
}
}
});
Now i have it working - and gonna tweak it a bit to my needs!
Thx all for all help!
Try this:
$.ajax({
type : 'POST',
url : 'post.php',
data: dataString,
success:function (data) {
if (data===undefined) { alert("darnit!!!!");}
//$("#response").append(data);
alert(data);
}
});
});
Also I would look into using json_encode on an array in your php file and returning a json object.

Categories