Sending array using ajax - php

I'm sending this array using ajax
code jquery:
$("#btnReact").on("click", function (e) {
var post = {};
post["comment"] = $("#bug_message").val();
post["id"] = $(this).data("bid");
var request = $.ajax({
url: "ajax/save_comment.php",
type: "POST",
data: {
post: post
},
dataType: "json"
});
request.done(function (msg) {
if(msg.status == "success") {
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
e.preventDefault();
});
but I can't reach my data in php and I keep getting errors when i'm trying to send this data to my class.
code php:
if(isset($_POST["post"]))
{
try
{
$comment = $_POST['post']["comment"];
$id = $_POST['post']["id"];
$comment = new Comment();
$comment->Comment = $comment;
$comment->SaveComment($id);
$feedback['status'] = "success";
}
catch(Exception $e)
{
$feedback['message'] = $e->getMessage();
$feedback['status'] = "error";
}
header('Content-Type: application/json');
echo json_encode($feedback);
}
Is there something wrong with my syntax or is it something else?

why don't you just post the object rather than object inside an object in data option
var request = $.ajax({
url: "ajax/save_comment.php",
type: "POST",
data: post,
dataType: "json"
});
and take it as
if(isset($_POST["comment"]) && isset($_POST["id"]))
{
try
{
$comment=$_POST['comment'];
$id = $_POST["id"];
......

try this :
jQuery(document).ready(function(){
$("#btnReact").on("click", function(e){
var post = {};
post["comment"] = $("#bug_message").val();
post["id"] = $(this).data("bid");
var request = $.ajax({
url: "ajax/save_comment.php",
type: "POST",
data: {post : post},
dataType: "json"
});
request.done(function(msg) {
if(msg.status == "success"){
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
e.preventDefault();
});
});
the only difference is that i put your code inside jQuery(document).ready(function(){});

Related

Loop through ajax response in jquery

I got the following ajax response.
{"ord_item_Json_string":"[{\"code\":\"1002\",\"item\":\"Diamond Softy\",\"size\":\"15 inch\",\"color\":\"Light Blue\",\"qty\":\"2\",\"price\":\"849.45\",\"amount\":\"1698.90\"},{\"code\":\"1001\",\"item\":\"sAMPLE\",\"size\":\"Cob\",\"color\":\"Naturtal\",\"qty\":\"5\",\"price\":\"434.05\",\"amount\":\"2170.25\"}]"}
now the problem is that i want to display only code and item fields & value but i am unable. please help me how to access that fields.
my code is following.
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (data) {
$("#OrdItem").html(data);
console.log(data);
return true;
},
error: function () {
alert('Not Working');
$('#ord_buyer_pack_inst').empty();
}
});
Try this:
var abc = {"ord_item_Json_string":"[{\"code\":\"1002\",\"item\":\"Diamond Softy\",\"size\":\"15 inch\",\"color\":\"Light Blue\",\"qty\":\"2\",\"price\":\"849.45\",\"amount\":\"1698.90\"},{\"code\":\"1001\",\"item\":\"sAMPLE\",\"size\":\"Cob\",\"color\":\"Naturtal\",\"qty\":\"5\",\"price\":\"434.05\",\"amount\":\"2170.25\"}]"}
var a = JSON.parse(abc.ord_item_Json_string)
$.each(a, function(index,value){
console.log(value.code+'--'+value.item)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
try the code below...in success callback you will be getting data in json object format. so just get value using its key.
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (jsonResponse) {
var itemsList = jsonResponse.ord_item_Json_string;
$.each(itemsList, function (index, value) {
console.log(value.code + '--' + value.item);
});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
try this: you can try below code where you can iterate over json array and read each attribute
$.ajax({
url: base_url + 'order_jobcard/getOrderDetails/' + ord_id,
type: "POST",
data: JSON.stringify($('ord_id').serializeArray()),
success: function (data) {
var dataStr = "";
var jsonData = data.ord_item_Json_string; // this is already json
jsonData = JSON.parse(jsonData);//value need to parse
for (var i = 0; i < jsonData.length; i++) {
var ord= jsonData[i];
console.log(ord.code);
dataStr += ord.code;
}
$("#OrdItem").html(dataStr);
console.log(data);
return true;
},
error: function () {
alert('Not Working');
$('#ord_buyer_pack_inst').empty();
}
});
JSFiddle

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

JQuery Ajax/laravel form submit not working

I've been trying some stuff with Ajax and laravel, I've tried a lot at this point and have no idea what is going wrong. I can't seem to get the form data (that's what this is mainly about). If ANYONE is able to help, it'd be great. Here's the code, and thanks in advance.
$('.bier').on('click', bier);
$('.delete-check-close').on('click', closeDelete);
$('.delete-check-show').on('click', showDelete);
$('.message').on('click', closeMessage);
hideMessage();
$('form.page').on('submit', bier);
function bier() {
var form = $(this);
var url = form.attr('action');
console.log(url);
console.log(form);
console.log('bier');
console.log(form.find('input').serialize());
console.log('/bier');
var wtf = new FormData(form);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'json',
data: form.serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data, textStatus, jqXHR) {
console.log('success');
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
var data = $.parseJSON(jqXHR.responseText);
console.log(data);
if (data.errors) {
console.log(data.errors);
$.each( data.errors, function( key, value ) {
console.log(key);
console.log(value);
if(key.length > 0) {
var $error = $('td.' + key);
$error.removeClass('hidden');
$error.addClass('visible');
$error.html(value);
}
});
} else {
console.log('======================================== error');
console.dir(jqXHR);
console.dir(textStatus);
console.dir(errorThrown);
}
}
});
return false;
}
});
Try the following code:
$('form.page').on('submit', function() {
var form = $(this);
var url = form.attr('action');
console.log(url);
console.log(form);
console.log('bier');
console.log(form.find('input').serialize());
console.log('/bier');
var wtf = new FormData(form);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'json',
data: form.serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data, textStatus, jqXHR) {
console.log('success');
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
var data = $.parseJSON(jqXHR.responseText);
console.log(data);
if (data.errors) {
console.log(data.errors);
$.each( data.errors, function( key, value ) {
console.log(key);
console.log(value);
if(key.length > 0) {
var $error = $('td.' + key);
$error.removeClass('hidden');
$error.addClass('visible');
$error.html(value);
}
});
} else {
console.log('======================================== error');
console.dir(jqXHR);
console.dir(textStatus);
console.dir(errorThrown);
}
}
});
return false;
});

Print Json data into html format

I posted the image in an array from my form using AJAX, and in response I received a JSON data
I received the below code in my console as response;
0"C:\xampp\htdocs\3Dklik\..../1492427792slider_7.jpg"
1"C:\xampp\htdocs\3Dklik\mog/1492427792slider_2.jpg"
2"C:\xampp\htdocs\3Dklik\mo…../public/img/1492427792"
id""
user_id"1"
The following is my AJAX code:
<script type="text/javascript">
$(document).ready(function(e) {
$("#btnsubmit").on('click', function(e) {
e.preventDefault();
var formData = $('#uploadform').serialize();
var files = $("#uploadform")[0];
console.log(files);
$.ajax({
url: '<?php echo $this->url('
upload ');?>',
type: 'POST',
data: new FormData(files),
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
alert("Data Uploaded: " + data);
console.log(data);
},
error: function(result) {
alert("Error");
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
</script>
And the following is my PHP code;
public function uploadAction() {
$request = $this - > getRequest();
if ($request - > isPost()) {
$data = array_merge_recursive(
$request - > getPost() - > toArray(),
$request - > getFiles() - > toArray()
);
// echo'<pre>';print_r($data);
}
$image_array = array_slice($data, 2);
//print_r($image_array);
foreach($image_array as $files) {
//print_r($files);
$file_new_name = round(microtime(true)).$files['name'];
$destination = "public/img/".$file_new_name;
$file_name = $files['tmp_name'];
move_uploaded_file($file_name, $destination);
$data[] = __DIR__.('/../../../../../public/img/').$file_new_name;
}
return new JsonModel(array(
'data' => $data
));
}
Basically the JSON data includes the image path, but I wish to display the image in my <div>. How can I achieve this?
you can sen the JSON format like validate.php in you can use;
echo json_encode(arrayvalue);
$("#btnsubmit").on('click', function(e) {
e.preventDefault();
var formData = $('#uploadform').serialize();
var files = $("#uploadform")[0];
console.log(files);
$.ajax({
url: '<?php echo $this->url('
upload ');?>',
type: 'POST',
data: new FormData(files),
dataType: 'json',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
alert("Data Uploaded: " + data);
console.log(data);
$.each(data, function(i, item) {
alert(data[i].imgName);
});
},
error: function(result) {
alert("Error");
},
cache: false,
contentType: false,
processData: false
});
return false;
});

Longpolling : Sending extra variable

I am doing a simple longpolling using jquery and php.. It's going on great.. but when I am sending and extra variable.. then the longpolling is not showing the current value that it's supposed to show... My code is below..
The one which is working :
function getContent(time)
{
var queryString = {'time': time};
$.ajax(
{
type: 'GET',
url: 'test.php',
data: queryString,
success: function(data){
var obj = jQuery.parseJSON(data);
$('#response').html(obj.data_from_file);
getContent(obj.time);
},
error : function(){
getContent(time);
}
}
);
}
$(document).ready(function(){
getContent();
});
The one which is working on page refresh.. but longpolling is not happening...
function getContent(time)
{
var name = '<?php echo $name; ?>';
var queryString = {'time': time, 'name':name};
$.ajax(
{
type: 'GET',
url: 'test.php',
data: queryString,
success: function(data){
var obj = jQuery.parseJSON(data);
$('#response').html(obj.data_from_file);
getContent(obj.time);
},
error : function(){
getContent(time);
}
}
);
}
$(document).ready(function(){
getContent();
});
PHP side...
while (true) {
$last_ajax_call = isset($_GET['time']) ? (int)$_GET['time'] : null;
$name = $_GET['name'];
//rest of the code...............
}
else{
sleep(1);
continue;
}

Categories