Category Archives: Code

Code is a question and answer site for professional and enthusiast programmers.

Pass JSON with segue within an asynchronous subprocess(alamofire)

Hello stackoverflow fellows!

im trying to do a login with mysql in swift, so far i got my app to receive the info from the database, but now, i need it to be in the next view controller. As far as i read i need to override the prepareForSegue with the next view variables to receive the data and the current view variables, the things is that i can’t or haven’t figured out, how to override with variables within my asynchronous alamofire request, is there another way to segue with variables as arguments, or how should i handle the JSON objects in my alamofire to pass them to the next segue.

Here’s my code:

    func login(){



    let url="http://primefitness.hostoi.com/scripts/read_user_ios.php"

    let user : String = usuario.text!
    let pass : String = password.text!
    var u : Bool = false
    var p : Bool = false

    Alamofire.request(.POST ,url,parameters: ["usuario":user]).responseJSON{

        request,response,result in

        switch result{

        case .Success(let perfil):

            let json = JSON(perfil)

            if let usuarioweb : String = json["usuario"].string{
                //print(usuarioweb)
                if user == usuarioweb{
                    u = true
                }
                else{
                    u = false
                }
            }
            if let passweb = json["password"].string{
                //print(passweb)
                if pass == passweb{
                    p = true
                }
                else{
                    p = false
                }
            }

            if u && p{
                if let activo : Bool = json["activo"].boolValue{

                    if activo {
                        JLToast.makeText("Usuario Correcto", duration: JLToastShortDelay).show()
                        //self.rutina(json, user: user)
                        //print(perf)
                        let url2="http://primefitness.hostoi.com/scripts/read_rutina_ios.php"

                        Alamofire.request(.POST ,url2,parameters: ["usuario":user]).responseJSON{

                            request,response,result in

                            switch result{

                            case .Success(let rutina):

                                let json = JSON(rutina)

                                if json["sinexito"] == "No Items Found"{
                                    JLToast.makeText("No existe rutina.", duration: JLToastShortDelay).show()
                                }
                                else{
                                    self.cargarNewView(JSON(perfil), rutina: json)
                                }


                            case .Failure(let data, let error):

                                JLToast.makeText("Error con la base de datos, intentelo de nuevo.", duration: JLToastShortDelay).show()
                                print("Fallido con error: \(error)")

                                if let data=data{

                                    print("Datos respondidos: \(NSString(data: data,encoding: NSUTF8StringEncoding))")

                                }

                            }

                        }


                    }
                    else{
                        JLToast.makeText("Usuario Inactivo, contacte a su administrador", duration: JLToastShortDelay).show()
                    }
                }

            }
            else{
                JLToast.makeText("Usuario/Contraseña Incorrecto", duration: JLToastShortDelay).show()
            }



        case .Failure(let data, let error):

            JLToast.makeText("Error con la base de datos, intentelo de nuevo.", duration: JLToastShortDelay).show()
            print("Fallido con error: \(error)")

            if let data=data{

                print("Datos respondidos: \(NSString(data: data,encoding: NSUTF8StringEncoding))")

            }

        }

    }

}//final login    

func cargarNewView(perfil: JSON,rutina: JSON){

    print(perfil)
    print(rutina)
    performSegueWithIdentifier("login", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

    if segue.identifier == "login"{
        let destinationVC = segue.destinationViewController as! rutinaViewController
        destinationVC.prueba = "hola"//testing the override
    }

    // Create a new variable to store the instance of the next view controller

}

read more

Pass JSON with segue within an asynchronous subprocess(alamofire)

Hello stackoverflow fellows!

im trying to do a login with mysql in swift, so far i got my app to receive the info from the database, but now, i need it to be in the next view controller. As far as i read i need to override the prepareForSegue with the next view variables to receive the data and the current view variables, the things is that i can’t or haven’t figured out, how to override with variables within my asynchronous alamofire request, is there another way to segue with variables as arguments, or how should i handle the JSON objects in my alamofire to pass them to the next segue.

Here’s my code:

    func login(){



    let url="http://primefitness.hostoi.com/scripts/read_user_ios.php"

    let user : String = usuario.text!
    let pass : String = password.text!
    var u : Bool = false
    var p : Bool = false

    Alamofire.request(.POST ,url,parameters: ["usuario":user]).responseJSON{

        request,response,result in

        switch result{

        case .Success(let perfil):

            let json = JSON(perfil)

            if let usuarioweb : String = json["usuario"].string{
                //print(usuarioweb)
                if user == usuarioweb{
                    u = true
                }
                else{
                    u = false
                }
            }
            if let passweb = json["password"].string{
                //print(passweb)
                if pass == passweb{
                    p = true
                }
                else{
                    p = false
                }
            }

            if u && p{
                if let activo : Bool = json["activo"].boolValue{

                    if activo {
                        JLToast.makeText("Usuario Correcto", duration: JLToastShortDelay).show()
                        //self.rutina(json, user: user)
                        //print(perf)
                        let url2="http://primefitness.hostoi.com/scripts/read_rutina_ios.php"

                        Alamofire.request(.POST ,url2,parameters: ["usuario":user]).responseJSON{

                            request,response,result in

                            switch result{

                            case .Success(let rutina):

                                let json = JSON(rutina)

                                if json["sinexito"] == "No Items Found"{
                                    JLToast.makeText("No existe rutina.", duration: JLToastShortDelay).show()
                                }
                                else{
                                    self.cargarNewView(JSON(perfil), rutina: json)
                                }


                            case .Failure(let data, let error):

                                JLToast.makeText("Error con la base de datos, intentelo de nuevo.", duration: JLToastShortDelay).show()
                                print("Fallido con error: \(error)")

                                if let data=data{

                                    print("Datos respondidos: \(NSString(data: data,encoding: NSUTF8StringEncoding))")

                                }

                            }

                        }


                    }
                    else{
                        JLToast.makeText("Usuario Inactivo, contacte a su administrador", duration: JLToastShortDelay).show()
                    }
                }

            }
            else{
                JLToast.makeText("Usuario/Contraseña Incorrecto", duration: JLToastShortDelay).show()
            }



        case .Failure(let data, let error):

            JLToast.makeText("Error con la base de datos, intentelo de nuevo.", duration: JLToastShortDelay).show()
            print("Fallido con error: \(error)")

            if let data=data{

                print("Datos respondidos: \(NSString(data: data,encoding: NSUTF8StringEncoding))")

            }

        }

    }

}//final login    

func cargarNewView(perfil: JSON,rutina: JSON){

    print(perfil)
    print(rutina)
    performSegueWithIdentifier("login", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {

    if segue.identifier == "login"{
        let destinationVC = segue.destinationViewController as! rutinaViewController
        destinationVC.prueba = "hola"//testing the override
    }

    // Create a new variable to store the instance of the next view controller

}

read more

Django field doesn’t remain incremented even after calling save()

I’ve searched all over and couldn’t find an answer for this. I really can’t understand why this doesn’t work, especially since it works in other projects. Anyway, I’m trying to increment a model field by 1 when a user gets a question correct. I’m using Django 1.8 and Python 3.5, with factory_boy for creating test data.

Here’s the views.py function:

def check_answer(request):
    front = request.POST.get('front')
    userAnswer = request.POST.get('ans')
    answerCards = Card.objects.filter(front=front)
    for ans in answerCards:
        if ans.back == userAnswer:
            ans.score += 1
            ans.save() # at this point calling print(ans.score) will return 1
            return HttpResponse('correct')
    answerCards.update(score=F('score') - 1) # using print statements I know it isn't hitting this line
    return HttpResponse('wrong')

read more

Django field doesn’t remain incremented even after calling save()

I’ve searched all over and couldn’t find an answer for this. I really can’t understand why this doesn’t work, especially since it works in other projects. Anyway, I’m trying to increment a model field by 1 when a user gets a question correct. I’m using Django 1.8 and Python 3.5, with factory_boy for creating test data.

Here’s the views.py function:

def check_answer(request):
    front = request.POST.get('front')
    userAnswer = request.POST.get('ans')
    answerCards = Card.objects.filter(front=front)
    for ans in answerCards:
        if ans.back == userAnswer:
            ans.score += 1
            ans.save() # at this point calling print(ans.score) will return 1
            return HttpResponse('correct')
    answerCards.update(score=F('score') - 1) # using print statements I know it isn't hitting this line
    return HttpResponse('wrong')

read more

Ajax request causes the page to reload – on mobile phone

The ajax code when is runned through a mobile device causes the page to reload and doesn’t execute the insert ( does not even prom a error message ), on the other hand everything runs normally on the computer, any ideas why?

 $('#pending_request_submit').on("click",function() {

    var url = "http://leagueofmusic.com/mobix-html/lib/pending_request.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#pending_request").serialize(),
           beforeSend: function(){
            $('#request_response').html('<center><img src="css/img/loader.gif"></center>');
           },
           success: function(data)
           {
              $('#request_response').html(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});

read more