I'm trying to send a form build with CodeIgniter via AJAX and trying to get the response with JSON. However, I only see the respond when I open my developer tab (I'm not even sure, if that's actually a respond since it's showing both of the json data's).
All it shows, is the loading spinner, and after that it vanishes.
Code have been tested without AJAX and it works, so there can't be errors in PHP.
Here's my controller for resetting the password:
<?php
Class Users extends CI_Controller {
public function forgot_pass()
{
if(!$this->input->post('to_email'))
{
exit("No data");
}
$this->load->model('user');
$email = $this->input->post('to_email');
$email_addr = $this->user->get_email_address($email);
if(empty($email_addr))
{
echo json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try again"));
}
$this->load->helper('string');
$new_password = random_string('alnum', 8);
$this->load->library('phpass');
$update_password = array( 'password' => $this->phpass->hash($new_password));
$update_password = $this->user->update_password($email, $update_password);
$this->load->library('email');
$config['newline'] = '\r\n';
$this->email->initialize($config);
$this->email->from('your#example.com', 'Your Name');
$this->email->to($email);
$this->email->subject('New password');
$this->email->message("Hey, " .$email_addr['name']. ". Your new password is: " .$new_password);
if($this->email->send())
{
echo json_encode(array('pls'=>1, 'msg' => "Password has been sent to given e-mail address"));
}
}
}
?>
And here's my AJAX call written with jQuery:
$(document).ready(function() {
$("form#forget_pass_form").on('submit', function(e){
e.preventDefault();
$("#loading_spinner").show();
var from = $(this);
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
data: $(from).serialize(),
}).done(function(data) {
if(data.pls == 0) {
$("#forgot-pass-success").hide();
$("#forgot-pass-error").show();
$("#forgot-pass-error").fadeIn(1000).html(data.msg);
}
if(data.pls == 1) {
$("#forgot-pass-error").hide();
$("#forgot-pass-success").show();
$("#forgot-pass-success").fadeIn(1000).html(data.msg);
}
$("#loading_spinner").hide();
});
return false;
});
});
Firstly, can you try setting the correct header in the Controller?
header('Content-Type', 'application/json');
Or better yet:
$this->output->set_content_type('application/json');
As a side note, you should make sure you are always returning JSON data, so I would remove the exit() message and put a default JSON response at the bottom of the method.
Don't forget, when you echo your JSON, you can put return; afterwards to stop any more code running afterwards in that method.
Most of your code is ok. But you need to change some lines, both in your js, and controller.
Change 1(In Ajax function)
Change your ajax function and add dataType: "json" option
$.ajax({
url: from.attr('action'),
type: from.attr('method'),
dataType: "json",
data: $(from).serialize(),
}).done(function(data) {
....
});
Change 2 (In controller)
exit("No data");
to
exit(json_encode(array('pls'=>0, 'msg' => "No data")));
Change 3 (In controller)
echo json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try again"));
to
exit(json_encode(array('pls'=>0, 'msg' => "E-mail address was not found. Try again")));
explanation
First change tell your script to handle the response data as Json
Second change is to keep all your return type same, if not when you sending only the no data response you are not handling this option from youe js.
And the last change make sure you stop further processing when sending email fails, and stop from showing both json.
I would like to suggest you about json return.
First in your ajax you have to use dataType: 'json'
$.ajax ({
url: from.attr('action'),
type: from.attr('method'),
data: $(from).serialize(),
dataType: 'json',
}).done(function(data) {
..your code..
});
CodeIgniter have output class, why don't you use output class to respond to ajax from CI.
$output = array('pls' => 1,
'msg' => "Password has been sent to given e-mail address"
);
$this->output->set_content_type('application/json')
->set_output(json_encode($output));
Use output class, this is more efficient then echo
I hope it will helps you for better code style.
Related
I have read a lot on codeIgniter ajax response. I have and modified my ajax script multiple times yet codeIgniter does not return the json response although I see the response when debugging with firefox developer browser under the network tab of web console. here's what i have written
AJAX script
$("#class_id").change(function(){
var class_id = $("#class_id").val();
alert(class_id);
alert("<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id");
$.ajax({
method: "POST",
url: "<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id",
dataType: 'json',
data: {class_id: class_id},
success: function(response) {
$("#res").html(reponse.class_id);
}
});
return false;
});
controller
function set_class_id()
{
if ($this->session->userdata('teacher_login') != 1)
redirect(base_url(), 'refresh');
//echo "dsdsd".$this->input->POST('class_id');
if (!empty($this->input->POST('class_id')))
{
$page_data = array('class_id' => $this->input->POST('class_id'));
//$response["JSON"] = json_encode($page_data);
$response = array('class_id' => $this->input->POST('class_id'));
echo json_encode($page_data);
$this->load->view('backend/index', $page_data);
}
}
Have you tried using
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
Also, check th output class for more info Codeigniter Output Class
So I figured a way out. using just php, I sent the class_id to the controller using a submit button then checked for the response on the page to enable the subject dropdown. Although i haven't figured why the ajax isn't working yet. thanks guys for your inputs
I have an AJAX script that should insert data into a mysql database when users are logged in. However it is currently running the success function, even when 'success' => 'false' is returned in the console.
Her is my code
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"http://localhost/stumble/Site/add_to_fav",
dataType: "json",
data: form_data,
success: function (data){
alert("This Video Has Been Added To Your Favourites");
console.log(data.status);
},
error: function (data){
if(data.success == false){
alert("You Must Be Logged In to Do That");
console.log(data.status);
};
}
});
})
})
here is the php, bear in mind my project is in codeigniter.
public function add_to_fav(){
header('Content-Type: application/json');
$this->load->model('model_users');
$this->model_users->add_favs();
}
and this is the actual model for adding data to db
public function add_favs(){
if($this->session->userdata('username')){
$data = array(
'username' => $this->session->userdata('username'),
'title' => $this->input->post('heading'),
'embed' => $this->input->post('embed')
);
$query = $this->db->insert('fav_videos',$data);
echo json_encode(array('success'=>'true'));
} else {
echo json_encode(array('success'=>'false'));
}
}
Thank you for any suggestions!
You aren't returning an error.
You are returning a 200 OK with the data {"success": "false"}.
You can either handle that in your jQuery success function or send a different status code (it looks like a 403 error would fit here).
You have to remember error that occurs for asynchronous requests and errors that occur for PHP backend are different. Your error occurs at PHP-level, and PHP returns valid HTML as far as the javascript frontend is concerned. You need to check if the "success" variable in the returned JSON is true.
I'm working with the Laravel framework and I'm making an AJAX request to send an email. The request works fine and the mail is sent, the problem is I can't get the server response if the mail has been sent successfully or not.
Here's the code (short version) wich is located under views/contact/mail.blade.php :
if( mail($to, $subject, $body,$headers) ) {
$data = array( 'text' => Lang::line('contact.mail-success')->get() );
return Response::json($data);
} else {
$data = array( 'text' => Lang::line('contact.mail-error')->get() );
return Response::json($data);
}
and here's the jquery :
$('#contact-form').submit(function() {
var request = $.ajax({
url: BASE+'/contact',
type: 'post',
data: { name: $('#name').val(), mail: $('#email').val(), message: $('#msg').val() },
dataType:"json",
success: function(data){
var message = $.parseJSON(data);
alert(message.text); // here I get the "cannot read property of null" in the console log
}
});
return false;
});
What am I doing wrong? Thanks for your help.
Since Laravel sends the correct headers with Response::json there's no need to parse the JSON in your Javascript, simply change the line
var message = $.parseJSON(data);
to
var message = data;
You shouldn't return Response::json() from a view file, the view are supposed to echo whatever output generated from the view but in this case you need to return the response from the route itself, as json would also include header information.
While sending a response in form of JSON must be encoded using json_encode(); in PHP. after successful reach of done method then parse the object as JSON.parse();
Example :
Modify the line in php file as
return response()->json(json_encode($data));
add the line in javascript files as
done(function (data){
console.log(JSON.parse(data));
console.log(data.text);
});
I'm currently trying to make live form validation with PHP and AJAX. So basically - I need to send the value of a field through AJAX to a PHP script(I can do that) and then I need to run a function inside that PHP file with the data I sent. How can I do that?
JQuery:
$.ajax({
type: 'POST',
url: 'validate.php',
data: 'user=' + t.value, //(t.value = this.value),
cache: false,
success: function(data) {
someId.html(data);
}
});
Validate.php:
// Now I need to use the "user" value I sent in this function, how can I do this?
function check_user($user) {
//process the data
}
If I don't use functions and just raw php in validate.php the data gets sent and the code inside it executed and everything works as I like, but if I add every feature I want things get very messy so I prefer using separate functions.
I removed a lot of code that was not relevant to make it short.
1) This doesn't look nice
data: 'user=' + t.value, //(t.value = this.value),
This is nice
data: {user: t.value},
2) Use $_POST
function check_user($user) {
//process the data
}
check_user($_POST['user'])
You just have to call the function inside your file.
if(isset($_REQUEST['user'])){
check_user($_REQUEST['user']);
}
In your validate.php you will receive classic POST request. You can easily call the function depending on which variable you are testing, like this:
<?php
if (isset($_POST['user'])) {
$result = check_user($_POST['user']);
}
elseif (isset($_POST['email'])) {
$result = check_email($_POST['email']);
}
elseif (...) {
// ...
}
// returning validation result as JSON
echo json_encode(array("result" => $result));
exit();
function check_user($user) {
//process the data
return true; // or flase
}
function check_email($email) {
//process the data
return true; // or false
}
// ...
?>
The data is send in the $_POST global variable. You can access it when calling the check_user function:
check_user($_POST['user']);
If you do this however remember to check the field value, whether no mallicious content has been sent inside it.
Here's how I do it
Jquery Request
$.ajax({
type: 'POST',
url: "ajax/transferstation-lookup.php",
data: {
'supplier': $("select#usedsupplier").val(),
'csl': $("#csl").val()
},
success: function(data){
if (data["queryresult"]==true) {
//add returned html to page
$("#destinationtd").html(data["returnedhtml"]);
} else {
jAlert('No waste destinations found for this supplier please select a different supplier', 'NO WASTE DESTINATIONS FOR SUPPLIER', function(result){ return false; });
}
},
dataType: 'json'
});
PHP Page
Just takes the 2 input
$supplier = mysqli_real_escape_string($db->mysqli,$_POST["supplier"]);
$clientservicelevel = mysqli_real_escape_string($db->mysqli,$_POST["csl"]);
Runs them through a query. Now in my case I just return raw html stored inside a json array with a check flag saying query has been successful or failed like this
$messages = array("queryresult"=>true,"returnedhtml"=>$html);
echo json_encode($messages); //encode and send message back to javascript
If you look back at my initial javascript you'll see I have conditionals on queryresult and then just spit out the raw html back into a div you can do whatever you need with it though.
My solution is using onClick event to call a PHP page, post parameters and return result using AJAX. I insert parameter right at time calling PHP page using specified URL.
Here is my Javascript:
function uploadContact() {
var name, email, phone, badgeid;
if(window.localStorage.length > 0)
{
name = window.localStorage.getItem('name');
email = window.localStorage.getItem('email');
phone = window.localStorage.getItem('phone');
}
else
{
name = $('input[name=fullname]').val();
email = $('input[name=email]').val();
phone = $('input[name=phone]').val();
}
$.ajax({
url: 'UpdateContactList.php?name=' + name + '&email=' + email + '&phone=' + phone,
type: $form.attr('method'),
dataType: 'json',
success: function(responseJson) {
$form.before("<p>"+responseJson.message+"</p>");
},
error: function() {
$form.before("<p>There was an error processing your request.</p>");
}});
}
My PHP code to get parameters:
<?php
$response = array();
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// if form has been posted process data
// you dont need the addContact function you jsut need to put it in a new array
// and it doesnt make sense in this context so jsut do it here
// then used json_decode and json_decode to read/save your json in
// saveContact()
$data = array( 'fullname' => $_POST['name'], 'email' => $_POST['email'], 'phone' => $_POST['phone']);
//These line is for testing only, remove it when done testing
$test = $_POST['name'] . ' ' . $_POST['email'];
echo "<script>alert('$test');</script>";
// always return true if you save the contact data ok or false if it fails
$response['status'] = updateContact($data) ? 'success' : 'error';
$response['message'] = $response['status']
? 'Your submission has been saved!'
: 'There was a problem saving your submission.';
header("Content-type: application/json");
echo json_encode($response);
exit;
}
...
function updateCacheFile($filename)
{
$filename = "contact";
$filename = $filename . ".appcache";
$cachefile = fopen ($filename, "a+");
....
file_put_contents($filename, $cache_content);
}
Please notice 2 problems:
I can call directly PHP page with parameters from browse address link, do this will return nothing. Is it normally?
Call from javascript. The testing line (call an alert message box) won't work, no message appeared. But the cache file still updated, which means PHP page is called and do things like writing files.
There is 2 files to be written in this PHP page. Both of them were written correctly but the parameters won't show up and no message box show.
Please instruct me what went wrong here.
P/S: small detail, Is parameter with space can be pass correctly? Because I expected users input their full name, such as 'Bill Jobs'.
Thanks to Stackoverflow community.
echo "<script>alert('$test');</script>";
// always return true if you save the contact data ok or false if it fails
$response['status'] = updateContact($data) ? 'success' : 'error';
$response['message'] = $response['status']
? 'Your submission has been saved!'
: 'There was a problem saving your submission.';
header("Content-type: application/json");
echo json_encode($response);
All headers must be executed before you begin echoing or otherwise flushing output.
header("Content-type: application/json");
echo "<script>alert('$test');</script>";
// always return true if you save the contact data ok or false if it fails
$response['status'] = updateContact($data) ? 'success' : 'error';
$response['message'] = $response['status']
? 'Your submission has been saved!'
: 'There was a problem saving your submission.';
echo json_encode($response);
$.ajax({
url: 'UpdateContactList.php',
data:{'name':name,'email': email,'phone':phone,'badgeid ':badgeid },
type: $form.attr('method'),
dataType: 'json',
success: function(responseJson) {
$form.before("<p>"+responseJson.message+"</p>");
},
error: function() {
$form.before("<p>There was an error processing your request.</p>");
}});
Try sending your info in the data param of the ajax and setting the type to post. Like this...
$.ajax({
url: 'UpdateContactList.php',
type: 'post',
dataType: 'json',
data: {'key1': value1, 'key2':value2},
success: function(responseJson) {
$form.before("<p>"+responseJson.message+"</p>");
},