In my Web Application, I want to get an error message on every ajax call.
I m using CodeIgniter using I preferred to use flashdata for this purpose I came to know that flashdata don't update until the refresh
here is my ajax code
$.ajax({
url: '<?php echo base_url();?>Auth/userlogin',
type: 'POST',
data: {
email: email,
password:password
},
dataType: 'text',
success: function(data) {
var error="<?php echo $this->session->flashdata('signup'); ?>"
if(data=='no'){
$('#loginerror').html('<div class="alert alert-danger">'+error+'</div>');
}else{
$('#loginerror').html(' ');
$('#login').hide();
location.reload();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
And here is my Controller Where I m setting Flashdata
$this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run()==FALSE) {
$this->session->set_flashdata('signup',$this->form_validation->first_error());
echo 'no';
}
I don't see any reason whatsoever of using flash data in ajax cause you already can return any data you need in your response, in your example you can just do this:
if ($this->form_validation->run() == FALSE)
{
$this->json['signup'] = $this->form_validation->first_error();
$this->json['status'] = false;
echo json_encode($this->json);
}
else
{
$this->json['status'] = true;
// your code ....
}
and in your success:
dataType: 'JSON',
success: function(data) {
if(data.status == false) {
$('#loginerror').html('<div class="alert alert-danger">'+data.signup+'</div>');
} else {
$('#loginerror').html(' ');
$('#login').hide();
location.reload();
}
...
Related
I have an ajax request where I register a user (wordpress). I want the user id to be sent back to the success response, but it just shows undefined, or blank in the case below:
$(document).on('submit', '.register_user_form', function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
dataType: 'html',
data: {
action: 'register_user_form',
currentUserName: $("#First_Name").val() + " " + $("#Last_Name").val(),
currentUserEmail: $("#email").val(),
currentUserPassword: $("#password").val(),
},
success: function(res) {
console.log(res);
}
});
});
PHP function (wordpress):
function register_user_form() {
$user_login = $_POST['currentUserName'];
$user_email = $_POST['currentUserEmail'];
$user_pass = $_POST['currentUserPassword'];
$userdata = compact( 'user_login', 'user_email', 'user_pass' );
$user_id = wp_insert_user($userdata);
echo 'this doesnt get returned';
wp_die();
}
add_action('wp_ajax_register_user_form', 'register_user_form');
add_action('wp_ajax_nopriv_register_user_form', 'register_user_form');
I have tried echo json_encode(''); but that doesn't work either. fyi - the user does get registered
This my code for send realtime message.
After send message, it is not display unless i refresh the page.
I want this chat box message to show the new message entered.
This is to show the user List In the left side of the page:
$(".user-w").click(function() {
var user_id = $(this).attr("id");
// alert(user_id);
$.ajax({
type: "POST",
url: "<?php echo base_url('Message/getMessageByLists/')?>",
data: {
'user_id': user_id
},
datatype: 'html',
success: function(data) {
$("#loadMessages").html(data);
}
}); });
This is Send function:
$("#sendMessage").click(function(e)
{e.preventDefault();// alert("test");
var msg = $("#message_text").val();
var touser = $("#touser").val();
//var reservation_id = $("#reservation_id").val();
if (!msg || msg.length == 0) {
alert("enter a message");
} else {
$.ajax({
type: "POST",
url: "<?php echo base_url('Message/addMessage')?>",
// data:{'msg' : msg, 'touser' : touser, 'reservation_id' : reservation_id},
data: {
'msg': msg,
'touser': touser
},
datatype: 'text',
// Page.Server.ScriptTimeout = 300;
success: function(data) {
if (data == 1) {
//$("#loadMessages").load();
$("#message_text").val("");
} else {
alert("noo eroor chat message");
}
},
});
//return false;
} }); // End Send Function
if I am not wrong then, their might be an element with class as "user-w", also that element have "id" attribute too. So you can just execute following line, after sending the message to user.
$(".user-w[id='"+ touser +"']").trigger("click");
above line needs to placed in "success" method, like as below:
if (data == 1) {
//$("#loadMessages").load();
$("#message_text").val("");
$(".user-w[id='"+ touser +"']").trigger("click");
} else {
alert("noo eroor chat message");
}
How do I alert a json_encode() message and reload the page? The function below only displays an undefined alert message
if($result1 == false)
$response['msg'] = "Transfer failed due to a technical problem. Sorry.";
else
$response['msg'] = "Successfully transferred";
echo json_encode($response);
$("#transfer").click(function() {
$.ajax({
type : "POST",
url : "transferProduct.php",
data : {},
success : function(data) {
data = $.parseJSON(data);
alert(data.response);
location.reload();
}
});
});
You're trying to get a undefined index response
Provided that your PHP script returns:
{
"msg": "<your-message-here>"
}
In your javascript you can do it:
$.ajax({
type : "POST",
url: "transferProduct.php",
dataType: 'json',
success : function(response) {
alert(response.msg);
location.reload();
}
});
Use code in this way
transferProduct.php
if($result1 == false)
$response['msg'] = "Transfer failed due to a technical problem. Sorry.";
else
$response['msg'] = "Successfully transferred";
echo json_encode($response);
code page
$("#transfer").click(function() {
$.ajax({
type : "POST",
url : "transferProduct.php",
data : {},
success : function(data) {
datas = $.parseJSON(data);
alert(datas.msg);
location.reload();
}
});
});
or you can use $.getJSON in place of $.ajax
$("#transfer").click(function() {
$.getJSON("transferProduct.php",function (data){
alert(data.msg);
location.reload();
});
});
I think you should format the return to correctly identify in the background:
{"success":true,"message":"---------"}
then in JavaScript: data.message
I am trying to write a script that will add the video currently being viewed to a database of favourites. However every time it runs, an error is returned, and nothing is stored in the database.
Here is the JQuery
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"localhost/stumble/site/add_to_fav.php",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
The add_to_fav.php is this...
public function add_to_fav(){
$this->load->model('model_users');
$this->model_users->add_favs();
}
And the add_favs function is below
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);
if($query){
$response_array['status'] = 'success';
echo json_encode($response_array);
}}else {
$response_array['status'] = 'error';
echo json_encode($response_array);
}
}
Thank you for the input, this has me stuck but I am aware it may be something relatively simple, my hunch is that it is something to do with returning success or error.
Try
$(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){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
Also to use base_url in javascript. In your template view :-
<script>
window.base_url = "<?php echo base_url(); ?>";
</script>
Now you can use base_url in all your ajax scripts.
Hello i'm using an ajax script redirecting to a php page where i make the validation. After there are no validation errors i want to redirect to another page but i cant manage to make it work. here is my script:
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$("#imageform").ajaxForm({
target: \'#preview \',
});
});
</script>
and here is the external php were i make the validation
<?php
require_once('../core/dbconfig.php');
mysql_query("SET NAMES utf8");
$fname=$_POST['name'];
$email=$_POST['email'];
$country=$_POST['country'];
$city=$_POST['city'];
$type=$_POST['type'];
$story=$_POST['story'];
$cookie=$_COOKIE['cookie'];
$sizee = $_FILES['img1']['size'];
if (!$fname or !$city or !$email or !$country or (!$story && $sizee==0))
{
if ($sizee==0 && !$story)
{
echo'<p style="color:red;">Please upload a photo or type your story.<p>';
}
if(!$fname)
{
echo'<p style="color:red;">Please enter your name.<p>';
}
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex, $email)) {
}
else
{
echo'<p style="color:red">Please enter a valid email.<p>';
}
if(!$country)
{
echo'<p style="color:red">Please select your country.<p>';
}
if(!$city)
{
echo'<p style="color:red">Please enter your city.<p>';
}
}
else
{
....
}
what i want to achiev is that after all the conditions are completed to redirect to a confirmation page. If i use a succes:window.location.href = "example.php" doesnt work as intended.
Thnx in advance.
$(myform).ajaxForm({
beforeSend: function() {
},
error: function() {
},
complete: function(response) {
window.location.href='yourfile.php'
}
});
With ajaxForm you'r can use function complete, according to documentation this function... "A function to be called when the request finishes (after success and error callbacks are executed)".
But you need consider property async, By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
$(myform).ajaxForm({
async: true,
error: function(response) {
//something is wrong
},
complete: function(response) {
window.location.href='yourfile.php'
}
});
OR
$(myform).ajaxForm({
async: false,
error: function(response) {
//something is wrong
},
complete: function(response) {
window.location.href='yourfile.php'
}
});
$.ajax({
type: "POST",
dataType: "json",
url: "friends/get_user_friends",
data:{
action:"action",
type:"type"
},
success: function (response) {
window.location.href = "http://google.com";
},
error: function (response, ajaxOptions, thrownError) {
}
});