Data is not transmitted via formData - ajax

I have a script that should update a user's post without rebooting. But the form data, for some reason, is not transferred through the formData object, everywhere is null, except for those fields that are manually registered in the controller (id, user_id). What can be wrong?
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.infinite-scroll').on('click', '#editPostButton', function(e) {
e.preventDefault();
var id = $(this).data('id');
var user_id = $('#userForm').val();
var form = document.getElementById('EditPostForm'+id);
var formData = new FormData(form);
$.ajax({
url: "id"+user_id+"/"+id+"/edit",
type: "PATCH",
data: formData,
success: function(data) {
console.log(data);
$("#textpostdata"+id).html($(data).find("#textpostdata"+id).html());
$("#closeButton"+id).click();
},
error: function() {
console.log('error');
},
contentType: false,
processData: false,
});
});
And my controller
public function editPost(storeRequest $request, $id, $postId) {
$user = User::find($id);
if(!$user && $user != Auth::user()->id) {
return abort(404);
}
$post = Profile::find($postId);
if(!$post) {
return abort(404);
}
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->message = $request->message;
$post->videoPost = str_replace('watch?v=', 'embed/', $request->videoPost);
if($request->file('img')) {
$path = Storage::putFile('public/' . Auth::user()->id . '/post', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;
}
$post->update();
//return redirect()->back();
return $post;
}

Related

Ajax submission triggers Error = True by default even at success

Laravel ajax submission.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url : '{{URL::to('expense_bill/store2')}}',
method: 'POST',
data: $("#expense_create").serialize(),
success:function(data){
console.log(data)
if(data['success'] = true){
}
if(data['error'] = true){
//Clear Valdiation Errors
console.log('hi');
}
},
error: function (xhr) {
$('#validation-errors').html('');
$.each(xhr.responseJSON.errors, function(key,value) {
$('#validation-errors').append('<div class="alert alert-danger">'+value+'</div');
});
},
});
});
Controller:
public function store2(Request $request)
{
if($request->ajax()){
//return response()->json($request);
$validator = Validator::make($request->all(), [
'supplier' => 'required',
]);
if ($validator->fails()) {
$returnArray['error']=true;
$returnArray['err_msg']=json_decode(json_encode($validator->errors()), true);
return $returnArray;
}
if ($validator->passes()) {
$request->merge(['total' => $request->total*100]);
$request->merge(['tax_value' => $request->tax_value*100]);
$expensebillheader = ExpenseBillHeader::create($request->all());
$expense_bill_no = $expensebillheader->id;
$count = $request->input('count');
for ($i = 0; $i <= $count; $i++){
//checks if input with this name exists (incase if any middle row was deleted)
if (isset($request->input('amount')[$i]))
{
$line = new ExpenseBillBody;
$line->bill_no = $expense_bill_no;
$line->description = $request->input('description')[$i];
$line->amount = $request->input('amount')[$i];
$line->account = $request->input('account')[$i];
$line->save();
}
};
$successArray = ['success'=>'true','msg'=>"Expnese No".$expense_bill_no." Created"];
return response()->json($successArray);
}
}
}
When validator fails, it's all fine. When validator passes it is supposed to give success=" true" message. But along with that it also gives error="true" as well. Not sure what am I doing wrong. See in the screenshot, the highlighted portion should not come.
Larave returns correct response. You have error here
success:function(data){
console.log(data)
if(data['success'] = true){
}
if(data['error'] = true){
//Clear Valdiation Errors
console.log('hi');
}
}
...
if(data['success'] = true) and if(data['success'] = true) isn't comparasion, these are assigning values
Try to write comparasion operators ==
success:function(data){
console.log(data)
if(data['success'] === true){
}
if(data['error'] === true){
//Clear Valdiation Errors
console.log('hi');
}
}
...

how to create a new div of json response array from controller

I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}

codeigniter foreach not displaying all records in table

Hi I am able to retrieve data from a specific table using codeigniter ajax but i don't see everything.
It's simply a chat system I implemented allowing users to send messages to one another.
Everytime a new record is inserted, the latest record does not show up but the previous ones do.
Please see my code attached with this.
Thank you.
Controller - Chats.php
public function ajax_get_chat_messages()
{
echo $this->_get_chat_messages();
}
public function _get_chat_messages()
{
$recipient = $this->input->post('recipient');
$chat = $this->Chats_model->get_chat_messages($recipient);
if($chat->num_rows() > 0)
{
$c_html = '<ul>';
foreach($chat->result() as $cht)
{
$c_html .= '<li>'.$cht->username.'</li>';
$c_html .= '<p>'.$cht->chat_message_content.'</p><hr><br>';
}
$c_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $c_html);
return json_encode($result);
}
}
JS - Chat2.js
$(document).ready(function () {
setInterval(function () { get_chat_messages();}, 2500)
function get_chat_messages()
{
$.post(base_url + "user/chats/ajax_get_chat_messages", {recipient: recipient}, function (data) {
if (data.status == 'ok')
{
$("div#view").html(data.content);
} else
{
//there was an error do something
}
}, "json");
}
/*function get_chat_messages() {
$.ajax({
type: "POST",
dataType: 'json',
url: base_url +"user/chats/ajax_get_chat_messages",
data: {recipient: recipient}, // pass it as POST parameter
success: function(data){
$("div#view").html(data);
console.log(data);
}
});
} */
get_chat_messages();
});
model - Chats_model.php
public function get_chat_messages($recipient)
{
$session = $this->session->userdata('user_id');
$query = "SELECT * FROM chat_messages cm JOIN users u on u.user_id = cm.user_id where cm.user_id = $session and cm.recipient = $recipient or cm.user_id = $recipient and cm.recipient = $session ORDER BY cm.chat_message_id ASC ";
$result = $this->db->query($query, array($recipient));
return $result;
}
Image also attached

How to modify a controller variable?

There is a variable sent by a controller :
public function ajout()
{
$data = array();
$data['_mode'] = MODE_AJOUT;
$this->load->view('mission/mission', $data);
}
In the view I want to change the variable $_mode to have a value MODE_MODIF ( a constant from the constants.php config file ) after submitting a form by ajax:
$("#form_sample_1").on("submit", function(){
var url_ = "<?php echo ( $_mode == MODE_AJOUT ? site_url('ajax/ajouterMission') : site_url('ajax/modifierMission') ); ?>";
$.ajax({
data: $(this).serialize(),
type: "POST",
url: url_,
async: false,
success: function (data, textStatus, jqXHR ) {
alert("Donn\351es enregistr\351es !");
}
});
return false;
});
How to do that ? or is that impossible ?
Add atribute .
MY_Class Extends CI_Controller{
private $_mode;
}
public function ajout(){
$data = array();
$data['_mode'] = MODE_AJOUT;
$this->load->view('mission/mission', $data);
}
//Call this function with ajax
public checkForm(){
$this->_mode = $newValue; //set attribute
$data['_mode'] = $this->_mode; //get attribute
echo json_encode($data);
}

Symfony2 handle jQuery serialized Form and extra data sent with ajax post

I'm trying to handle the form and some extra data sent with ajax.
Here is my ajax post code :
$(document).on('submit', '#edit-entreprise', function (e) {
e.preventDefault();
var $entreprise = $("#liste-entreprises").val();
var $url = Routing.generate('load_edit_entreprise_form');
var $formSerialize = $('#edit-entreprise').serialize() + "&entreprise=" + $entreprise;
$(".panel-entreprise").empty().append('<div class="progress"> <div class="indeterminate"></div> </div>');
$.ajax({
url: $url,
type: 'POST',
data: $formSerialize,
success: function(html) {
console.log(html);
}
});
});
And here, my controler :
public function editAction(Request $request)
{
$entreprise = $request->request->get('entreprise');
$entreprise = $this->getDoctrine()
->getRepository('AvisClientsBundle:Entreprise')
->find($entreprise);
$editForm = $this->createForm('AvisClientsBundle\Form\EntrepriseType', $entreprise);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entreprise);
$em->flush();
return new Response(json_encode(array('status' => 'success')));
}
return new Response(json_encode($this->render('AvisClientsBundle:Admin/Entreprise:edit.html.twig', array(
'entreprise' => $entreprise,
'edit_form' => $editForm->createView(),
))->getContent()));
}
I don't know how to receive the form and the extra data :(
Can you explain me how to do this ?
Thanks !
I do it like this :
Ajax (I use FormData ):
$('#formId').submit(function (event) {
// Eviter le comportement par défaut (soumettre le formulaire)
event.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
type: $this.attr('method'),
data: new FormData($this[0]),
processData: false,
contentType: false,
error: function (request, status, error) {
callback(request.responseText);
},
complete: function () {
//
},
statusCode: {
//traitement en cas de succès
200: function (response) {
var message = response.message;
callback(response, event);
},
412: function (response, event) {
callback(response);
}
}
});
});
In sf2 here is the handler:
public function updateAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('testBundle:testEntity')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find entity.');
}
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
//envoi des données JSON en front
$response = new JsonResponse();
$response->setStatusCode(200);
//ajout de données éventuelles
$response->setData(array(
'message' => "Ligne buffer updated",
'form' => json_encode($this->getHtmlForm($entity))));
return $response;
} else {
//form non valide
//envoi des données d'erreurs JSON en front
$response = new JsonResponse();
$response->setStatusCode(412);
$response->setData(array(
'form' => json_encode($this->getHtmlForm($entity)),
'message' => $editForm->getErrorsAsString(),
));
return $response;
}
}

Resources