Entity decode in jquery ajax form - javascript

I have a jquery ajax form to add/edit/delete username list in mysql db.
When I retrieve data with special chars from DB I'd like to populate the modal edit form with entity decoded chars...so for example ù wouldn't show as ù
Here you are the code I'm using:
$("body").on("click",".edit-user",function(){
var id = $(this).parent("td").prev("td").prev("td").prev("td").prev("td").text();
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : url + '/ajax_edit/' + id,
// type: "POST",
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="username"]').val(data.username); // Populate edit modal form with retrieved username data
$('#con-close-modal').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Contributor'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
});

Solved using echo html_entity_decode(json_encode($data)); in server side PHP script.

Related

How to refresh modal body when submit Ajax Post?

Im submitting ajax request using Bootstrap Modal when i submit i want refresh modal body. it means what i have saved from my form im showing my modal body i want show that row in table. when i use this that table got hide not refreshing anything rong ?
$('#uploadform').submit(function(e) {
e.preventDefault();
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
formData.append('task_id','{{$task->id}}');
formData.append('title',$('#title').val());
$.ajax({
type:'POST',
url:'{{url('/uploadTask')}}',
data:formData,
success:function(data){
$("#images-table").replaceWith($('#images-table', $(data)));
$("#some_form")[0].reset();
},
error:function (data) {
alert('error');
},
async:false,
processData: false,
contentType: false,
});
});
You can simply refresh the Modal html by putting some new html into it like:
success:function(data){
// here data contains the response for your ajax call
var newHTML = data;
$("#images-table").html(newHTML); // This will put new html and remove old
}

Send Ajax post request and retrieve the inserted id

I am trying to submit a form which will insert data into a mysql database which is working fine. I then would like to return the id of the new inserted row (id auto increment in mysql table) as I want to open up a modal once the form is submitted so I can provide a link which includes id as a parameter in the url.
To send the data for the form I am using the following code:
$(document).ready(function(){
$("#submitForm").click(function(){
var string = $('#commentForm').serialize();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "SubmitData.php",
data: string,
cache: false,
success: function(result){
//alert(result);
}
});
});
});
The SubmitData.php file then inserts the form data into the database.
In the SubmitData.php I can create a variable to pick up the id of the newly inserted row like
$last_id = mysqli_insert_id($conn);
Is there a way I can return the $last_id from the SubmitData.php file within the same function?
Yes return from SubmitData.php the id using the following echo:
echo json_encode(['id'=>$last_id]);
js:
$(document).ready(function(){
$("#submitForm").click(function(){
var string = $('#commentForm').serialize();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "SubmitData.php",
data: string,
cache: false,
success: function(result){
alert(result.id);//this will alert you the last_id
}
});
});
});
print last id in that php file
echo $last_id;
get that in ajax success function
success: function(result){
alert(result);
}

codeigniter HMVC ajax on update function

i have this ajax function i found in an opensource code.
function edit_person(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('person/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
$('[name="firstName"]').val(data.firstName);
$('[name="lastName"]').val(data.lastName);
$('[name="gender"]').val(data.gender);
$('[name="address"]').val(data.address);
$('[name="dob"]').val(data.dob);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Person'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
it does open a form over the data table with the information to be updated..
to briefly explain what i want to happen,
i have this folders in my module
folder
--controller
--model
--views
----main.php
----edit.php
----add.php
what i want to do is when i click the button, ajax will get the values i need to update and go to my edit.php and show the values there
No you can't call edip.php from VIEWS folder with AJAX request. Create a class called Person with edit_ajax method. And send your information from Ajax to edit_ajax method.
folder
--controller
----person.php /*Person class, contains edit_ajax method*/
--model
----person.php /*Contains update_person method, Call it from edit_ajax,
this model method will update Database with new information*/
--views
----main.php
----edit.php
----add.php

Eror 500 with ajax and codeigniter

I have a problem with calling ajax on my view on codeigniter website. Ajax is calling method in controller on same project.
I have ajax search, which is work correctly. When I chose one of results, he open a new tab and show me a detail information from database. In some cases when I click on some results(I didn't find rule when it will be happening), ajax return me a 500 error, without go into controller method, but when I refresh the page (F5) he shows me a correct result. Did someone have a same problem, or can help me to fix it?
Here is my ajax call:
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '<?=site_url('index/ajax_read_details')?>',
dataType: 'json',
cache: false,
async:true,
data: {'param':'<?=$selected?>'},
beforeSend: function (xhr) {
$('#loading').show();
},
success: function (data) {
$('#loading').hide();
var details = '<tr>' +
'<td>'+data['title']+'</td> '+
'<td>'+data['code']+'</td>' +
'</tr>';
$('#data >tbody').append(details);
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: '+ errorThrown);
}
});
});
</script>
I know now that he didn't go into controller method "ajax_read_details" in index controller in case when it give me an 500 error.But when I refresh, he go into that method and do it correctly job. In both cases, he send a same values but in first he didn't return values, after refresh page he give me a values :(
Short controller method is:
public function ajax_read_details()
{
$param = $this->input->post('param');
echo json_encode(array('title' => $param, 'code'=>param));
}

Tornado doesn't send Ajax response to client

Upon form submit the Tornado server does some checks and sends a response back to the client, which should appear in that current page as an alert.
Instead a blank html page is rendered with the Json response, but not as an alert on the current page where the form was submitted.
On submit the form is sent via post to /dh (DataHandler)
This is the Jquery:
$.post("/dh",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
},"json");
The Tornado code:
class DataHandler(BaseHandler):
def post(self):
# Checks are done with form data received
dupInfo={
'tel' : duptel,
'name' : dupName
}
self.write(json.dumps(dupInfo, default=json_util.default))
self.finish()
So how can you return this json to the current page?
After the "alert" statement, add return false;. This disables the browser's default handling of the POST event. The browser's default behavior is to navigate to the new URL, and you want to prevent that.
Give your form an id and stop the default redirect after submission:
$("#yourForm").submit(function (event) {
event.preventDefault();
jQuery.ajax({
url: "/dh",
data: {
// whatever data you are passing to handler
},
dataType: "json",
type: "POST"
}).done(function (data, textStatus, jqXHR) {
// call was successful
// access response data
alert(data['tel'])
alert(data['name'])
}).fail(function (jqXHR, textStatus, errorThrown) {
// call error
// access response data
var data = jqXHR.responseJSON;
alert(data['tel'])
alert(data['name'])
});
});
Based on your handler, you should end up in the done callback rather than the fail one.

Categories

Resources