Ajax jquery always running error function, althought success function run and i can get session value,i can't run window.location="profile.php";
$(document).ready(function(){
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
type: "POST",
url: "model/user.php",
data: {
user_log : username,
password : password
},
dataType: 'json',
error: function (xhr,textStatus,errorThrown) {
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
},
success: function(json){
window.location="profile.php";
},
beforeSend:function()
{
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
user.php
<?php
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
require_once(dirname(__FILE__).'/../model/connect.php');
?>
<?php
global $pdo;
if(isset($_POST['user_log'])) {
// username and password sent from Form
$username=$_POST['user_log'];
$password=$_POST['password'];
$qr= "SELECT * FROM user where username='$username' AND password='$password'" ;
$stmt= $pdo->query($qr);
$row= $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$_SESSION['id']=$row['id'];
$_SESSION['name_mem']=$row['username'];
$_SESSION['level_mem']=$row['level'];
}
header("location:../../../../index.php");
}
?>
Remove this line :
header("location:../../../../index.php");
If above doesn't work, omit this from ajax properties :
dataType: 'json',
you can use ajax like this,
<script>
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//progress
xhr.upload.addEventListener("progress", function(e) {
//progress value : you can load progress bar in here
}, false);
return xhr;
},
type: "POST",
url: "model/user.php",
data: {'username' : username, 'password' : password},
dataType:json,
success: function(msg) {
//when success //200 ok
if(msg.status=="done"){
window.location="profile.php";
}else{
$("#error").html("<span style='color:#cc0000'>Error:</span> "+msg.massage);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//when error: this statement will execute when fail ajax
}
});
});
</script>
server side code like this(inside user.php),
$username=$_POST['username'];
$password=$_POST['password'];
...........
//$status="fail" or "done"
//success must be always success
//$massage= "password or username not match"
$respond=array("success"=>"success","status"=>$status,"massage"=>$massage);
echo json_encode($respond);
exit;
I hope you useful this.
Related
So I am working on this form that contains both form and files data. I want to submit it through Ajax. So when it can't pass form Validation, use won't loose the whole entry.
create.php
<script type="text/javascript">
$("#add-product-form").submit(function(e){
e.preventDefault();
var formData = new FormData(this);
console.log(formData);
var url="products/ajax_add_single_product";
$.ajax({
type:"post",
url:"<?php echo base_url() ?>"+url,
data:formData,
dataType:'json',
cache: false,
contentType: false,
processData: false,
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR,textStatus,errorThrown);
error = jqXHR.responseJSON.error;
$(".submit-message").html(error);
console.log(error);
$("html, body").animate({ scrollTop: 0 }, 200);
},
success: function (data, textStatus, jqXHR) {
message = jqXHR.responseJSON.success;
$(".submit-message").html(message);
location.href = "/products";
}
})
})
</script>
controller
public function create(){
$data\['title'\] = "Add Product";
$data\['categories'\] = $this->category_model->get_categories();
$data\['children'\] = $this->category_model->get_child_cats(0);
$data\['vendors'\] = $this->vendor_model->get_vendors();
$data\['attributes'\] = $this->product_model->get_attributes();
$this->load->view('templates/header', $data);
$this->load->view('products/create');
$this->load->view('templates/footer');
}
public function ajax_add_single_product(){
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('productname', 'Product Name', 'required');
$this->form_validation->set_rules('partnumber', 'Part Number', 'required|is_unique\[items.itemSKU\]');
$this->form_validation->set_rules('catID', 'Category', 'required', array('required'=>"You need to pick a %s"));
header('Content-Type: application/json');
if ($this->form_validation->run() === FALSE)
{
$this->output->set_status_header(400);
$errors = validation_errors();
echo json_encode(['error'=>$errors]);
}
else
{
$this->output->set_status_header(200);
$imageData = $this->images_upload();
$this->product_model->create_product($imageData);
echo json_encode(['success'=>'Record added successfully.']);
}
}
With above code, when entry can't pass form validation, It will give me form validation errors. When the entry is success, it will insert data to database as I expected. but it will still give me a error. seems like i am not getting JSON data, and getting html.
So turns out, there was one line in the create_product() function in the model. After insert data to tables, I put redirect('/products')after, that's why I am getting the html source code of page products.
As the title says I want to run the if and else inside the success condition in Ajax, For example after running the Ajax and sees that there is a record it will go to success then inside the success it must look for the "if statement" and display the alert inside the "if statement" if the statement is true but instead it always display the "else statement" with the alert('no') inside of it, even if there is a record, Thank you
<script>
function renderAttendees(id)
{
///$("#attendeesContent").empty();
var dataString = { "id": id };
$.ajax({
type: 'POST',
url: server+'webservice/crm/viewAttendeesDetails',
data: dataString,
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
cache: true,
success: function(data)
{
if($.trim(data) === 'error')
{
alert('yes');
}
else
{
alert('no');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error connecting to server. " + XMLHttpRequest + ", " + textStatus +", "+ errorThrown);
}
</script>
//My Controller Code
public function viewAttendeesDetails()
{
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
$data = array();
$id = $_POST['id'];
$AttendeesDetails = $this->model->GetAttendeesDetail($id);
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
}
echo json_encode($data);
exit;
}
?>
//My Model Code
db->prepare("SELECT * FROM crm_contact_list WHERE id = :AttendId");
$stmt->bindParam(":AttendId", $id);
$stmt->execute();
return $stmt;
}
catch (Exception $e)
{
return $e->getMessage();
return $stmt;
}
return;
}
?>
//Here is the result of console.log(data);
Object
email:"kyle#localhost.com"
full_name:"Test kim"
id:"1"
interest:"Test"
number:"123456"
position:"Prog"
venueID:"1"
I would return from your controller something like
{status: 'success', data: myArrayWithFoundData}
so when you receive the ajax response you could do a json_decode, and check the status.
So in you controller you would have
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
$rsp_data = {status: 'success', data: $data};
}else{
$rsp_data = {status: 'error', data: null};
}
echo json_encode($resp_data);
Something like that, so in the ajax response you would do a
var a = JSON.parse(data);
and check the a.status for error
I am trying to delete images with Ajax and all the php seems to work except when I try to send variables to another php document.
Php that shows and grabs neccessary values.
// show images
$image_display = "";
foreach(glob($pathimages.'*') as $filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$name_only = basename($filename, ".".$ext);
$image_display .= "<img src=\"images/" .$targetID."/" .$name_only.".".$ext. "\" width=\"30\" />
<a onclick=\"DeleteImage('".$name_only."','".$ext."','".$targetID"'); return false;\" href=\"javascript:;\">X</a>
<br />";
}
.JS document, I get the sent and the success messages when pressing the X
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
delete_imgs.php document
include('session_check.php');
$name_only = $_POST['name_only'];
$ext = $_POST['ext'];
$targetID = $_POST['targetID'];
$pathimages = "images/$targetID/";
unlink($pathimages . $name_only .".". $ext);
echo "Deleted";
Any thoughts are more than welcome since I have banged my brain out of my head by now ...!
Cheers!
Try with async:false
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
async : false,
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
Maybe that can help
Here I read about many types of notification system like push, web socket, nodejs etc. But those all so complex for me. So as a easy way (In my preliminary step) I am going to use Below method to make a notification(new friend, new like, new comment/reply, new mail etc). So I used particular JS and php for a particular notification.
Now I want to implement keep all together in a JS to minimize my scripts. Here I faced a problem that is every notification have different sent data and php page and different result div. So how to keep them together?
A additional Question please(I knew stackoverflow rules): Can it make my server too many connection problem?
new mail notification JS:
function addrep(type, msg){
// do here with result
}
var name = '<?php echo $username; ?>';
function waitForMail(){
$.ajax({
type: "GET",
url: "/server/mail.php",
cache: false,
data: {name : name
},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(waitForMail, 15000 );
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForMail, 15000);
}
});
}
$(document).ready(function(){
waitForMail();
});
new post notification JS:
function addpost(type, msg){
// do here with result
}
var name = '<?php echo $username; ?>';
var profileid = '<?php echo $profileid; ?>';
function waitForPost(){
$.ajax({
type: "GET",
url: "/server/post.php",
cache: false,
data: {name : name, profileid : profileid
},
timeout:15000,
success: function(data){
addpost("postreply", data);
setTimeout(waitForPost, 15000 );
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForPost, 15000);
}
});
}
$(document).ready(function(){
waitForPost();
});
And all php file like as
while (true) {
if($_GET['username']){
$res = mysqli_query(// here) or die(mysqli_error($dbh));
$rows = mysqli_fetch_assoc($res);
$id = $rows['id'];
//etc all
//do something
$data['id'] = $id;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
}
sleep(5);
}
mysqli_close($dbh);
Well, I am not sure is this comfortable with your application design. Anyway it seems obvious that if you have to fetch notifications with the same interval it is better to have one ajax that checks everything. Something like:
$.ajax({
type: "GET",
url: "/server/notification.php",
cache: false,
data: {name : name, profileid : profileid
},
timeout:15000,
success: function(data) {
/**
* backend should return now single object for all notification types
* something like
* {
* newpost: { ... },
* mail: { ... },
* somethingelse: { ... }
* }
*/
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForPost, 15000);
}
});
If you can not do it for some reasons you can keep all urls and their callbacks in object and create ajax requests in array. Something like:
// list of ajax request names and their callbacks
var reqs = {
mail: function(data) { doSomethingWith(data);},
post: function(data) { doSomethingWith(data);}
};
// this function will send ajax by given type
function fetchNotification(type, callback) {
$.ajax({
type: "GET",
// ajax url, for example /server/mail.php
url: "/server/" + type + ".php",
cache: false,
data: {name : name, profileid : profileid},
timeout: 15000,
success: function(data) {
// run callback. In this example execute doSoemthingWithData
callback(data);
// in 15 seconds repeat this reqest
setTimeout(function() {
fetchNotification(type, callback);
}, 15000)
},
error: function(req, status, err){
// something went wrong, try again in 15 seconds
setTimeout(function() {
fetchNotification(type, callback);
}, 15000);
}
}
}
for (var i in reqs) {
// init first ajax for each type and its callback from reqs object
fetchNotification(i, reqs[i]);
}
I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}