Send json string in ajax post - php

var myData = JSON.stringify($('form').serializeArray());
$.ajax({
cache: false,
url: "http://localhost/Demo/store.php",
type: "POST",
data: myData,
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert(status);
}
else {
var r = xhr.responseText;
}
}
});
$decoded = json_decode($_REQUEST['myData'],true);
print_r($_REQUEST);
exit;
if (is_array($decoded))
{
foreach ($decoded as $value) {
echo $value["name"] . "=" . $value["value"];
}
}
When i am trying to decode the data in php the error is undefined index myData..Please help me..Thanks.

Give it a try with:
$decoded = json_decode($_POST['myData'],true);

Try this when call ajax
data: {'myData' : myData},
Then access using
json_decode($_POST['myData'],true);
or
json_decode($_REQUEST['myData'],true);

try this pass datatype :
$.ajax({
url: 'http://localhost/Demo/store.php',
type: 'POST',
dataType: 'json',
data: $('#form').serialize(),
success: function(xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert(status);
}
else {
var r = xhr.responseText;
}
}
});

When you pass a string as the data property is just appends it as a parameter query string to the URL. If you want to send an encoded JSON string you still need to give it a name:
data: {myData: myData}
Now you can use the myData request parameter in your PHP script.

used dataType:json;tosend json.

Related

jQuery Ajax get json returned result

I want to get the return result of a php function in an Ajax request in order to make some verification in onSucces. How can I get the JSON result from the php function into the ajax request?
public function verifyEmailAction()
{
$is_valid = true;
$is_duplicate = false;
$email_reset = false;
$register = $this->getRegisterHelper();
$register->addEmailCheck();
$register->setData($this->getAllParams());
$validationErr = $register->getValidationResult();
if (!empty($validationErr['badWords']['email']) || $validationErr['banned']['email'] == true
|| empty($validationErr['isEmailValid'])
) {
$is_valid = false;
} elseif (!empty($validationErr['duplicates']['email'])) {
$is_duplicate = true;
$email_reset = $this->sendResetEmail();
}
$result = [
'duplicate' => $is_duplicate,
'valid' => $is_valid,
'reset' => $email_reset
];
$this->getResponse()->setBody(json_encode($result));
}
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
}
});
});
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
dataType:'json',
success:function(response){
console.log(response);
var duplicate=response.duplicate;
var valid=response.valid;
var reset=response.reset;
},
error:function(err){
console.log('Error '+err);
}
});
You need to use the success and error functions like below,
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
success : function(data, status, xhr) {
console.log(JSON.stringify(data));
},
error: function(jqXhr, textStatus, errorMessage){
console.log("ERROR " + errorMessage);
}
});
});
$.ajax({
type: 'GET',
url: url,
data: {
'email': value
},
dataType:'json',
}).success(function(response){
//YOUR Json KEY
if(response.success){
}
});
I hope this article will help you.
http://api.jquery.com/jquery.ajax/
Specially you can use this
jQuery.ajax({
url: "YOURURL",
type: "YOURTYPE",
dataType:"json",
}).done(function(data) {
console.log(data) // to see the reqested data
// manipulate data here
});
Add dataType:'json':
jQuery.validator.addMethod("checkDuplicate", function (value, element) {
jQuery.ajax({
type: 'GET',
url: '/user/register/verify-email.ajax',
data: {
'email': value
},
dataType:'json'
});
});
You can use this to convert JSON string to a JavaScript object:
var txtReturned = JSON.parse(data);
Reference:
jQuery AJAX Call to PHP Script with JSON Return

Json unable to pass array to php

As the title says, I failed to pass the data array via json ajax to php. I am using codeigniter, what did I do wrong? here is the jQuery code:
function load_page_data1(){
var data = [];
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Here is the php code:
function getdata(){
$parameter = '';
if(isset($_POST))
{
if(isset($_POST['val']))
{
$parameter = $_POST['val'];
} else
{
echo "failed!";
}
}
$this->load->model('Chart');
$this->load->helper('url');
$data1 = $this->Chart->getdata_solid($parameter);
echo json_encode($data1);
}
Final:
Guys, it turn out that the values did passed from jQuery to php, the problem is that I stupidly call the same php function twice within the javascript function, then the second time calling without posting the 'val', so that the php function error and stop.
Thank you all for your answers, at least I learn the different ways to passing data by using jQuery.
Don't make a array if it's not a array just make a object
var data = {};
data.val = "solid_t1";
// equivalent to
data ={val:"solid_t1"};
// equivalent to
data['val'] ="solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
Update 1: if you need to send array you need to make a proper array object like below
Example :
var data=[];
item ={val:'value'};
data.push(item);
var new_data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: new_data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
For Debugging :
May be problem with your server side code .so for the testing purpose comment all the line in function just do this echo json_encode($_POST); and in your ajax success function just add console.log(output); and let me know the result.
create one json object
jsonObj = [];
create array list as per your need
item = {}
item ["val"] = "solid_t1";
push the array list in to the json.
jsonObj.push(item);
Please have a try like this. It is working in my case.
Your full code will be like
function load_page_data1(){
jsonObj = [];
item = {}
item ["val"] = "solid_t1";
jsonObj.push(item);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
The another way to use this is given below.
function load_page_data1(){
var jsonObj = {};
jsonObj["val"] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Instead of var data = []; use var data = {}; to initialize your data. It should solve your problem.
Your data wasn't being passed as json, now it will.
Code will be:
function load_page_data1(){
var data = {};
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/welcome/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
One more suggestion please use CI input library for post request in controller.
e.g.
$parameter = $this->input->post('val');

Ajax success not reading PHP echo as string

I have a simple PHP script which, when it executes correctly from an AJAX call, ends with:
echo "ok";
Yet when I try to parse this information it tells me its not a string.
In the example below the result is: alert('error: Type Mismatch');
Why does JQuery not read the php echo as a string?
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
success: function (response) {
if(typeof response == typeof 'string'){
if( response == 'ok')
alert('all is good');
else
alert('error:');
} else {
alert('error: Type Mismatch');
}
}
});
Screenshot below shows that the response is correct and simply says 'ok'
As I'm reading from jquery Api Doc I understand that you can get a "string" or something else as a response, based on what kind of dataType you passed (if u did) in your $.ajax object. Otherwise it will be assumpted from jQuery, based on some its own logic.
In my opinion you should avoid every assumption and explicitly pass your dataType based on the response format you'll send.
So,
in case you'll set response.php to return
echo "ok";
you should set dataType "text" in your ajax call:
$.ajax({
url: 'imageUpload.php',
type: 'POST',
dataType: "text",
...
and get the response with:
if(typeof response == "string")
{
console.info(response);
...
Or
in case you'll set response.php to return something like
echo json_encode(array("data" => "ok"));
you should set dataType "json":
$.ajax({
url: 'imageUpload.php',
type: 'POST',
dataType: "json",
...
and get the response with:
if(typeof response == "object")
{
console.info(response.data);
...
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
success: function (response) {
if (typeof response === "string"){
if (response == 'ok')
alert('all is good');
else
alert('error:');
} else {
alert('error: Type Mismatch');
}
}
});
Do it another way:
In you php script echo back a JSON: json_encode("ok");
In AJAX specify dataType: "json" and add event:
complete: function(jsondata, stat)
{
if(stat == "success")
alert( $.parseJSON( jsondata.responseText ) );
}
The response is not string type, it is a PlainObject object.
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
typeof response == 'object' // true
Try this:
$.ajax({
url: '/ajax/actions/imageUpload.php?act_id=<?=$act_id?>',
type: 'POST',
dataType: "text",
success: function (response) {
if( response == 'ok')
alert('all is good');
else
alert('error:');
}
});

Ajax request posting

I apologize for my bad english :)
I'm doing php file with ajax request. json response comes in the format of. but in some cases can be redirect. In this case I want the redirect of the page.
Could you please help me. Thank's.
Example PHP File :
<?php
$status = $_POST['status'];
if($status == 'a'){
// return json response
}else{
echo "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>";
}
?>
Example JS File :
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com'
});
Use success function https://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com'
data: { status : statusVar },
success: function(response){
if (response.status == 'a'){
$( "#results" ).append( response);
}else{
window.location = 'http://www.url.com'
}
});
});
Try this.
url: "http://www.my_php_file.com",
success: function(data) {
document.location.href='YouNewPage.php';
}
You need to detect if the response data is valid JSON:
$.ajax({
type: "POST",
url: 'http://www.my_php_file.com',
success: checkAJAX
});
function checkAJAX(data)
{
var response = $.parseJSON(data);
if(typeof response === "object")
{
}
else
{
// If the AJAX response is not JSON, append the HTML to the document
$('body').append(data);
}
}
Return the html that you want to echo as JSON also:
if($status == 'a'){
// return json response
} else {
echo json_encode(array("redirect" => "<form action='http://www.url.com'>..</form><script type='text/javascript'>form.submit();</script>"));
}
And check redirect in the ajax response:
$.ajax({
type: "POST",
dataType: "json",
url: 'http://www.my_php_file.com',
success: function(data) {
if(typeof data.redirect !== "undefined") {
$("body").append(data.redirect);
}
}
});
Just two reminders, there will be no redirection if request fails( no fail callback) and I assume your casual JSON response doesn't have an attribute redirect.

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