Print Json data into html format - php

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

Related

Ajax getting 400 Bad Request when submitting Form only on Firefox

I have written a php code in wordpress to submit a form using ajax. It working fine on chrome but getting 400 Bad request on Firefox. This is my code:
jQuery(document).ready(function($){
jQuery( 'form[name="contact-me"]' ).on( 'submit', function(e) {
e.preventDefault();
var form_data = {};
$(this).serializeArray().forEach( function(element){
form_data[element.name] = element.value;
});
$.post(zt_send_form_obj.ajax_url, {
action: "zt_save_campain_form_data",
_ajax_nonce: zt_send_form_obj.nonce,
type: "POST",
contentType: 'application/json; charset=utf-8',
values: JSON.stringify(form_data),
}, function(data) {
if (data.success) {
if(data.data.info.message=='no'){
$('#myModal').show();
console.log('cod is in')
}
if(data.data.info.message=='yes'){
$('#CodeModal').show();
$('.the_cod_div').append('<span>'+data.data.info.code+'</span>');
console.log('data saved');
}
}
else{
console.log("not working");
}
});
});
});
Try this
$('form[name="contact-me"]').submit(function (e) {
e.preventDefault();
var form = $('#form_id')[0]; //set form id
var varform = new FormData(form);
varform.append("action", "zt_save_campain_form_data");
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: varform,
processData: false,
contentType: false,
cache: false,
crossDomain: true,
success: function (response) {
//if success do this...
console.log(response);
},
error: function (xhr, textStatus, error) {
console.log(xhr, textStatus, error);
}
})
});
Inside your form you can put this code for nonce validation
<?php wp_nonce_field( 'name_of_my_action', 'name_of_nonce_field' ); ?>

before submit and uploadProgress doesnt work in ajax jquery

can any one help me in this problem and i try many ways but beforeSubmit and uploadProgrss doesnt work
$.ajax({
url:"include/ajaxPages/admin/insertNewItem.php",
type:"POST",
data:new FormData(this),
processData:false,
contentType:false,
beforeSubmit:function(){
$(this).find(".progress").width("0%");
},
uploadProgress:function(event,position,total,complete){
$(this).find(".progress").animate({
width: complete+"%"
},{
duration:1000
})
},
success:function(data){
console.log(data);
alert("تم الاضافه بنجاح");
$(".loadingViedo").fadeOut();
window.location = document.URL;
}
})
Try this:
var fd = new FormData();
fd.append('rName', $('#upload-resource .upload').attr('data-name'));
fd.append('rfile', $('#upload-resource .upload').attr('data-file'));
$.ajax({
url: 'include/ajaxPages/admin/insertNewItem.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
xhr: function () { // custom xhr
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // if upload property exists
myXhr.upload.addEventListener('progress', function (e) {
var done = e.position || e.loaded
var total = e.totalSize || e.total;
var percent = Math.round(done / total * 100);
//console.log('xhr progress: ' + percent + '%');
$(this).find(".progress").animate({
width: percent +"%"
},{
duration:1000
});
}, false);
myXhr.addEventListener('load', function (e) {
//upload done
});
$('#upload-resource .cancel').show().click(function () {
//cancel upload
myXhr.abort();
});
}
return myXhr;
},
success: function (data) {
//to do for success result
}
});

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

How to upload image file with ajax?

problem when upload image MVC with ajax, i have controls_class.php content function upload_img_admin in class settings calling from page c_ajax_img.php
page c_ajax_img.php
include_once('controls_class.php');
$ajax_up_img = new settings;
$ajax_up_img->upload_img_admin(#$_FILES['file_upload']);
function upload_img_admin in class settings
function upload_img_admin()
{
$dir_name=dirname(__FILE__)."/upload/";
$path=#$_FILES['file_upload']['tmp_name'];
$name=#$_FILES['file_upload']['name'];
$size=#$_FILES['file_upload']['size'];
$type=#$_FILES['file_upload']['type'];
$error=#$_FILES['file_upload']['error'];
...
...
if( isset($_FILES['file_upload']) )
{
move_uploaded_file($path,$dir_name.$name);
...
...
echo "ok";
}
else
{
echo "File not found";
}
}
function ajax get data form and send to function previous for upload image
$(document).ready(function() {
$(".btn_upload_avatar").click(function(e) {
$('.msgerror').hide().fadeIn(1000).html( '<div class="loading"></div>');
e.preventDefault();
$.ajax({
type:"POST",
url: "../controls/c_ajax_img.php",
cache: false,
processData:false,
contentType: false,
data:$("#form_up_img").serialize(),
success: function (data)
{
if(data == 0){
$('.msgerror').addClass('msgerror_in2').html(data);
}else{
$('.msgerror').addClass('msgerror_in2').html(data);
}
}
});
});
});
Something like this might help you mate.. :)
$(document).ready(function () {
$('#UploadForm').on('submit',(function(e) {
$('.msgerror').hide().fadeIn(1000).html('<div class="loading"></div>');
e.preventDefault();
var formData = new FormData(this);
formData.append('file', input.files[0]);
$.ajax({
url: '../controls/c_ajax_img.php',
data: formData,
contentType: false,
type: 'POST',
processData: false,
success: function (data) {
console.log("success");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
});
});
});
FYI
FormData
ProcessData is set to false so that it prevents jQuery from automatically transforming the data into a query string

Sending array using ajax

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

Categories