mardi 4 août 2015

Spring 4 response to form submission dosent go thru view resolver. Gives back return string in response

I inherited a spring 4 web project at work which is configured with Tiles view framework, Spring framework for dispatcher servlet and IOC.

I am trying to build a reset password functionality which has three screens with three forms.

1)reset form. Takes the user's email and controller method sends an email with a temp password.

<form:form class="form-horizontal" action="/NCHP/reset.htm" method="post" id="resetForm">
                                    <fieldset>
                                        <legend>Enter your registered email address</legend>
                                        <div class="form-group">
                                            <div class="col-sm-12">
                                                <input id="resetEmail" name="email" class="form-control" placeholder="Email" required="required" tabindex="1" type="email">
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <div class="col-sm-12 ">
                                                <span class="pull-right">
                                                    <button type="reset" class="btn btn-default" data-dismiss="modal">Back</button>
                                                    <button type="submit" class="btn btn-primary" >Submit</button>
                                                </span>
                                            </div>
                                        </div>
                                    </fieldset>
                                </form:form>

2) Form to enter temp pwd:

<form:form class="form-horizontal" name="verify" method="POST" id='verifyform'>

                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-user form-control-feedback"></i>
                                            <input type="text" id="inputEmailVerify" name="userNameVerify" placeholder="User Name" class="form-control" autofocus="autofocus">
                                        </div>

                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-lock form-control-feedback"></i>
                                            <input type="password" name="passwordVerify" id="inputPasswordVerify" placeholder="Password" class="form-control" autofocus="autofocus">
                                        </div>
                                        <div class="form-group" id="verify-btn">
                                            <div class="col-sm-12 ">
                                                <span class="pull-right">
                                                <input type="submit" formaction="/NCHP/resetVerify.htm" value="Verify" class="btn btn-primary btn-block">
                                                </span>
                                            </div>
                                        </div>
                                    </form:form>

3) form to enter new password:

<form:form class="form-horizontal" name="resetPass" method="POST" id='resetPassForm' >

                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-lock form-control-feedback"></i>
                                            <input type="password" id="newpass" name="newpass" placeholder="new Password" class="form-control" autofocus="autofocus">
                                        </div>
                                        <div class="form-group has-feedback">
                                            <i class="glyphicon glyphicon-lock form-control-feedback"></i>
                                            <input type="password" name="newpass2" id="newpass2" placeholder="re enter Password" class="form-control" autofocus="autofocus">
                                        </div>
                                        <div class="form-group" id="new-login-btn">
                                            <div class="col-sm-12 ">
                                                <span class="pull-right">
                                        <input type="submit" formaction="/NCHP/changePass.htm" value="Save Password" onsubmit="modaljay();" class="btn btn-info btn-block">
                                        <div class="modaljay"><!-- Place at bottom of page --></div>
                                        </span>
                                        </div>
                                        </div>
                                    </form:form>

The first two forms i do an ajax submit and get back just the data without a view like below with jquery $.ajax()

$('#resetForm').submit(function(event) {
                                        $("#verifyModal").hide();
                                        $("passModal").hide();
                                        var resetmail = $('#resetEmail').val();
                                        console.log(resetmail);
                                        var json = {
                                            "email" : resetmail
                                        };

                                        $.ajax({
                                                    url : "http://localhost:8080/NCHP/reset.htm",
                                                    data : json,
                                                    dataType : 'text json',
                                                    type : "POST",

                                                    success : function(e) {
                                                        $('#resetModal').modal('hide');
                                                        $("#verifyModal").modal('show');
                                                        console.log(e);
                                                    },
                                                    error : function(e) {
                                                        console.log(e);
                                                        if (e.responseText == "email sent") {
                                                            $('#resetModal').modal('hide');
                                                            $("#verifyModal").modal('show');
                                                        } else if (e.responseText == "email not sent. UNAUTHORIZED") {
                                                            $("#emailResponce").html("there was an error. We could not process your request at this time. Please contact support@nexiscard.com");
                                                        }
                                                    }
                                                });

                                        event.preventDefault();
                                    });

The third form is a regular form submission and no ajax submission. because i want the user to be forwarded to their home page after they login with temp and set new password.

Below are the controller mappings for first two forms.

@Controller
public class UserLoginreset
{
@Autowired
public UserDao userDao;
@Autowired
public BCryptPasswordEncoder encoder;
@Autowired
public SecureServiceClient serviceClient;

@RequestMapping(value = "/reset", method = RequestMethod.POST)

public @ResponseBody String  reset( @RequestBody(required=true) String email, 
                                            HttpServletRequest request) 
{
    String mail="";
    try{
            mail = java.net.URLDecoder.decode(email, "UTF-8").replace("email=", "");
        }
    catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
    User user =userDao.findUserByemail(mail);
    request.getSession().setAttribute("user",user);
    String resetPwd= encoder.encode("xxxx");

    if(user!=null && email!=null){
        userDao.resetPass(user.getUser_name(), resetPwd);
        return (String) serviceClient.returnRestTemplate("email", mail);//"home";
    } else {
        return "login";//"index";
    }
}

@RequestMapping(value = "/resetVerify", method = RequestMethod.POST)
public @ResponseBody String  resetVerify( @RequestParam(value="user",required=true) String user,@RequestParam(value="pass",required=true) String pass, 
                                            HttpServletRequest request) 
{
    User user1 =userDao.findUserByName(user);
    if(user1!=null && pass.matches("xxxx")){
        return "success";//"home";
    } else {
        return "unauthorised";//"index";
    }

}

}

and third form.

@RequestMapping(value = "/changePass", method = RequestMethod.POST)
public @ResponseBody String  resetPass( @RequestParam(value="newpass", required=true) String newpass, @RequestParam(value="newpass2", required=true) String newpass2,
                                            HttpServletRequest request, Model model, HttpServletResponse httpServletResponse) 
{
    User user = (User)request.getSession(false).getAttribute("user");
    if(user.getUser_name()!=null && newpass.matches(newpass2)){
        userDao.resetPass(user.getUser_name(), encoder.encode(newpass));
        String news = userDao.getDynamicNewsByUser(user.getUser_name());
        model.addAttribute("user",user);
        model.addAttribute("news", news);
        return "MainLayout_Jay";//"home";

    } else {
        return "login";//"index";
    }

}

And below is my spring config

<bean id="annotationResolver" class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<context:component-scan base-package="com.nexis.cardholder" />
<mvc:annotation-driven >
</mvc:annotation-driven>
<mvc:default-servlet-handler />
<mvc:interceptors>
    <bean class="com.nexis.cardholder.session.interceptors.URLInterceptor" />
</mvc:interceptors>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean   class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/Pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
    <property name="order" value="1" />
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" >
    <property name="order" value="2" />
</bean>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="tilesViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
    <property name="order" value="0" />
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
    <property name="definitions">
        <list>
            <value>/WEB-INF/views.xml</value>
        </list>
    </property>
</bean>

I have two issues. 1) The last form submission dosent return a view with the data in it. It just returns an empty page with controller method's return string in it.

2) I configured my home page in both tiles.xml and put it in /web-inf/pages folder. so if tiles view resolver could not find it, regular resolver should have. i doubt if its treating this request as a ajax request and skipping the model-view mapping part totally. how do i figure out the root cause.

2.5)if i want to parse ajax requests as Json, should i use @restcontroller and will it automatically send the responce as json? i tried using MappingJackson2HttpMessageConverter but didnt see any difference in debug mode?? did it even get used?

PHP Email script only sending some messages [duplicate]

This question already has an answer here:

I'm using a php mail script from http://ift.tt/PtDpvh connected to a contact form on a website I'm building.

I have everything put together and it seems to function properly (doesn't display any errors), but I am not receiving most of the emails. If I test the contact form using one of my personal email accounts I will receive the message. If I use any other emails (for example something from http://ift.tt/12zcGwQ) I won't receive anything. I've attached all of the code below. Is there something I'm missing that anyone can spot?

If it helps, the site is hosted in an AWS LAMP linux instance and the domain is with GoDaddy.

Thanks in advance.

contact.html

<form id="ajax-contact" method="post" action="mailer.php">
    <div class="field">
        <input type="text" id="name" name="name" placeholder="name*" required>
    </div>

    <div class="field">
            <input type="email" id="email" name="email" placeholder="email*" required>
    </div>

    <div class="field">
            <input type="text" id="school" name="school" placeholder="school" >
    </div>

    <div class="field">
            <input type="tel" id="phone" name="phone" placeholder="phone" >
    </div>

    <div class="field">
            <textarea id="message" name="message" placeholder="message" ></textarea>
    </div>

    <div class="field">
            <button type="submit">Submit</button>
    </div>
</form>

mailer.php

<?php
    // My modifications to mailer script from:
    // http://ift.tt/PtDpvh
    // Added input sanitizing to prevent injection

    // Only process POST reqeusts.
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $phone = trim($_POST["phone"]);
        $school = trim($_POST["school"]);
        $message = trim($_POST["message"]);

        // Check that data was sent to the mailer.
        if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
             echo "There was a problem with your submission. Please ensure all required fields are filled out.";
            exit;
        }

        // Set the recipient email address.
        // FIXME: Update this to your desired email address.
        $recipient = "gideon.shils@gmail.com";

        // Set the email subject.
        $subject = "The Conscious Kitchen - New contact from $name";

        // Build the email content.
        $email_content = "Name: $name\n";
        $email_content .= "Email: $email\n\n";
        $email_content .= "School: $school\n";
        $email_content .= "Phone: $phone\n";
        $email_content .= "Message:\n$message\n";


        // Build the email headers.
        $email_headers = "From: $name <$email>";

        // Send the email.
        if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            http_response_code(200);
            echo "Thank You! Your message has been sent. We'll get back to you as soon as possible.";
        } else {
            // Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong and we couldn't send your message. Please try again later.";
        }

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        http_response_code(403);
        echo "There was a problem with your submission, please try again.";
    }

?>

app.js

$(function() {

    // Get the form.
    var form = $('#ajax-contact');

    // Get the messages div.
    var formMessages = $('#form-messages');

    // Set up an event listener for the contact form.
    $(form).submit(function(e) {
        // Stop the browser from submitting the form.
        e.preventDefault();

        // Serialize the form data.
        var formData = $(form).serialize();

        // Submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {
            // Make sure that the formMessages div has the 'success' class.
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            // Set the message text.
            $(formMessages).text(response);

            // Clear the form.
            $('#name').val('');
            $('#email').val('');
            $('#phone').val('');
            $('#school').val('');
            $('#message').val('');

        })
        .fail(function(data) {
            // Make sure that the formMessages div has the 'error' class.
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            // Set the message text.
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });

    });

});

Prestashop set customer id in context and use it without refreshing the page

I have this issue with Prestashop 1.5.4 who uses the context object.

I'm creating a custom one page checkout with Ajax.

When the customers input is validated I insert this in the related database tables and receive the customer id. So when the customer changes some things I don't wanna insert it again but update his data. But I don't know how I can do with the context object.

I want something like this in my controller:

if (!$this->context->customer->id){
// there is no data of this customer, so insert it in the database

// set customer id context
}
else{
// there is data so update it
}

I tried a lot of things like:

$this->updateContext($customer);

$this->context->customer->id = (int)$customer->id;

$this->context->customer->update();

etc. etc.

Who can explain how I can update the context without refreshing the page?

How to retrieve/provide a CSRF token to/from Django as an API

I'm working on a project that uses the Django REST Framework as a backend (let's say at api.somecompany.com but has a React.js frontend (at www.somecompany.com) not served by Django that makes AJAX requests.

I can't, therefore, use Django's traditional method of having the template include the CSRF token like this <form action="." method="post">{% csrf_token %}

I can make a request to Django REST Framework's api-auth\login\ url, which will return this header: Set-Cookie:csrftoken=tjQfRZXWW4GtnWfe5fhTYor7uWnAYqhz; expires=Mon, 01-Aug-2016 16:32:10 GMT; Max-Age=31449600; Path=/ - but I can't then retrieve this cookie to send back with my AJAX requests with X-CSRFToken (my understanding is of the separate subdomain), and it doesn't seem to be included automatically.

Here's my relevant code:

// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        }
    }
});

As the page loads I call this to make sure I have a token:

$.ajax(loginUrl, { method: "OPTIONS", async: false })
    .done(function(data, textStatus, jqXHR) {
        console.log(jqXHR)
        app.csrftoken@ = $.cookie("csrftoken")
        console.log($.cookie("csrftoken"))
        console.log(app.csrftoken)
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR)
    });

This isn't exactly clean but I haven't proven the concept to myself yet.

What is the 'correct' way of authenticating / protecting against CSRF when the frontend and backend are on different ports/domains?

Can't execute 2 $http calls in angularjs at the same time

I am implementing long polling to know the state of some long running event on the server side. I create my own factory that will notify me when a server event triggers. Here is the factory.

.factory("$httpPolling", function ($http) {

        function $httpPolling($httpService) {

            var _responseListener, _finishListener;
            var cancelCall = false;
            var _pollId;

            function waitForServerCall(id) {
                console.log("executing waitForServerCall");
                    $httpService.get(href("~/polling/" + id))
                        .success(function (response) {
                            var cancelPolling = _responseListener(response);
                            if (cancelPolling || cancelCall) {
                                return;
                            }
                            else {
                                waitForServerCall(id);
                            }
                    });
                };

                function _sendData(httpMethod, url) {

                    var pollingId = guid();
                    _pollId = pollingId;
                    if (url.split("?").length == 2) {
                        url += "&pollid=" + pollingId;
                    }
                    else {
                        url += "?pollid=" + pollingId;
                    }


                    if (httpMethod == 0) {
                        $httpService.get(url).success(function (response) {
                            if (_finishListener) {
                                _finishListener(response);
                            }

                            cancelCall = true;
                        });
                    }
                    else {
                        $httpService.post(url).success(function (response) {
                            if (_finishListener) {
                                _finishListener(response);
                            }

                            cancelCall = true;
                        });
                    }
                }
                var $self = this;

                this.get = function (url) {
                    _sendData(0,url);
                    return $self;
                };

                this.post = function (url) {
                    _sendData(1, url);
                    return $self;
                };

                this.listen = function (_listener) {
                    _responseListener = _listener;
                    waitForServerCall(_pollId);
                    return $self;
                }

                this.finish = function (_finish) {
                    _finishListener = _finish;
                    return $self;
                }

            }

        return new $httpPolling($http);
    });

Where the sintax of usage should be:

$httpPolling.get("url")
.listen(function(event){
// fires when server event happend
})
.finish(function(response){
// fires when the long running process finish
});

The problem is that _sendData method does not execute asynchronously because the waitForServerCall only executes the ajax call when the _sendData method get the response from the server.

Why? Is this an angular behavior?

XML5617: Illegal XML character in IE9

My applications is working in IE11, Chrome but not in IE9. It gives XML5617: Illegal XML character error, but there is no illegal character, other wise it will not work in IE11 and Chrome. I am using Ajax to load the data. I am lost. Thanks for help.

Also it works in IE9 for english language customers but not for non-english.

yiiGridView pagination is not working after first ajax call

I have one page there are four gridviews in one page. When i click on any pagination page button (ex : 1,2,3,4,5,6) It takes me to that page without any problem [via ajax]. And replaces new html with old html. But now when i click on pagination button it just redirects to the url. It do not get loaded via ajax. Whole page gets refreshed.

It works when on click of one page button.If i initialize through console. Like when i put this and press enter in console then It will work for next page call. And for again i have to initialize via console to make it work for next page button press.

        $('#answer-grid').yiiGridView({'ajaxUpdate':['answer-grid'],'ajaxVar':'ajax','pagerClass':'pager','loadingClass':'grid-view-loading','filterClass':'filters','tableClass':'table table-responsive','selectableRows':1,'pageVar':'saved_card_id_page'});

I try to add script in ajax loaded copntent but it did not worked. Not event Alert got excuted.

<script type='application/javascript'>

    alert("This is also not getting executed. When it comes from ajax content.")

</script>

I know may be they strips down the all content except the gridview div. But the same thing works in other project.

Choosing the best way to get a variable to a php script

For my project I need to do the following:

  1. User presses his Mouse on the canvas (html page)
  2. JavaScript function saves the coordinates of the points that have been pressed
  3. Send this info to a PHP script
  4. PHP script adds this data to MySQL database
  5. Other coordinates are put into JSON and sent to back to the client and presented on the same canvas

Now, I have looked into the problem of step 3 (which is something I don't know how to do). There are different ways, I have selected these two:

  1. Using Ajax
  2. HtmlRequest (answer 3)

Which would be the best way to choose in my situation? Is there yet a better / right way to do it?

Request header field Cache-Control is not allowed in Safari

The following code looks up a user's city from their IP address.

  jQuery(document).ready(function($) {

      var message = '';

      $.ajax({
        url: 'http://ift.tt/1In4Efd',
        type: "GET",
        success: function(result) {
          message = result.city + ' - ';
        }
      })
      .always(function(){
        $('.location span').html(message);
      });

    });

It works find except in Safari where it gives the error...

Refused to set unsafe header "Access-Control-Request-Headers" Failed to load resource: Request header field Cache-Control is not allowed by Access-Control-Allow-Headers.

How can I fix this?

"POST" data with jquery ajax and MVC2

I'm using MVC2, and I'm trying to send data with jquery ajax.

There is my JS code:

$.ajax({
                      type: "POST",
                      url: "Data",
                      data: { processName: "MyProc", startDate: "2015-08-01 16:00"},
                      success: function(data) {
                      }
                    });

And there is my controller:

[HttpPost]
        public JsonResult Data(string processName,string startDate)
        {
           int i = 1;
         }

So my problem is that I DO get to "int i=1;" line in my controller, BUT for some unknown reason - processName and startDate are both null.

Can someone please assist ?

Input to Javascript from file via php

I have a setup where I want to send the results of a python script asynchronously to a webpage. I currently have a HTML page setup, with a Javascript file that deals with the information dynamically.

However, I don't really understand how to get the Javascript to interact with Server-side files, seeing as its done through PHP. What do I do to set up a php file that takes the input from a text file (generated every x seconds from the python script), and sends it to the Javascript?

Bind ajax created content to specific JS [duplicate]

This question already has an answer here:

Right now I'm loading data from another page which should respond to a AJAX catching the clicks from the elements the AJAX creates. But for some reason the button action is not caught by the JavaScript script. What should I do to make the new elements execute the JavaScript that they should? I have the following code:

function ShowMoreProdcuts(){
        scrollNode = $('.product#more').last();    
        scrollURL = $('.product#more p a').last().attr("href");
        if(scrollNode.length > 0 && scrollNode.css('display') != 'none') {
          $.ajax({
            type: 'GET',
            url: scrollURL,
            beforeSend: function() {
              scrollNode.clone().empty().insertAfter(scrollNode).append('<img class="img-responsive" src=\"{{ "http://ift.tt/1IK5DcS" }}\" />');
                                                                        scrollNode.hide();
            },
            success: function(data) {
              // remove loading feedback
              scrollNode.next().remove();
              $('#moreProducts').remove();
              var filteredData = $(data).find(".product");
              filteredData.insertBefore( $("#product-list-foot") );
            },
            dataType: "html"
          });
        } else {
            $('#moreProducts').hide();
        }
      }

      $(document).ready(function () {
        /*$(window).scroll(function(){
          $.doTimeout( 'scroll', 200, ScrollExecute);
        });*/
        $('.moreProducts').on("click", function() {
          ShowMoreProdcuts();
        });

The AJAX loads more elements into the container. These elements have a from which should trigger a JQuery AJAX. But the buttons are not working. What am I doing wrong? Am I missing something?

I'm using the JQuery .on() function, but the buttons are still not answering to the other JQuery handler. I'm not trying to add the button that loads moreProducts, but another button that comes in the HTML which the AJAX gets that is supposed to be bound to another JQuery AJAX function.

The other JQuery listens for a submit with a certain class:

$('form[action="/cart/add"]').submit(function(e) {

But with the new elements created by the AJAX syntax, this function does not execute when the Submit button is clicked.

I'm not binding the click of the class .moreProducts to the same function click, but I want to bind a submit button to the function which I stated above.

P.D. Its not the same question as the duplicated I think or I am missing something. Cause I'm trying to bind another element to be heard by another function. When the content is created by the ajax. the button which loads more products work, BUT the function which hears if there is a submit does not. What am I doing wrong?

Rails Shippo Rates

I am new to using AJAX with rails and would like to display shipping rates via Shippo and AJAX. I am successfully going through the process of creating the rates in the console, but having trouble getting those rates to display so that my users can select their desired shipping rate/price.

Any examples or recommendations?

Rails Shippo Rates

I am new to using AJAX with rails and would like to display shipping rates via Shippo and AJAX. I am successfully going through the process of creating the rates in the console, but having trouble getting those rates to display so that my users can select their desired shipping rate/price.

Any examples or recommendations?

Trying to send a POST with the folder name to dynamically load slider, cannot get the value to POST

I am working on a one page website, and am trying to load the slider with the pictures of the project dynamically each time a project is selected from the list. I cannot get the value to be passed with any means, and the POST global comes back always empty. I even tried to do it with a GET but did not work.

Here is the code for the button:

 <div class="carousel-inner">
            <div class="active item project-1">
                <img class="row" src="includes/uploads/test.png" />
                <div class="project-description project-desc-1 row">
                    <div class="background-container col-md-6">
                        <h1 class="col-md-9 project-title">Project described here</h1>
                        <p class="col-md-10"> text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text
                            <a class="btn btn-default btn-lg show-gallery project" href="#test">View Gallery
                            </a>


                        </p>

                    </div>
                </div>
            </div>

The slider to be loaded:

<?php
$project="";
if (isset($_POST['projectName']))
{
$project = $_POST['projectName'];
}
?>
<section id="projects-slider" class="cd-section">
<div class="row projects-slider-background background" id="projects-slider">
    <img src="includes/uploads/up-arrow.png" class="hide-project text-center col-xs-offset-6 col-md-offset-6" alt="Back to Projects" />
    <div id="myCarousel2" class="carousel slide" style="padding-top:10%">
        <ol class="carousel-indicators">
            <li data-target="#myCarousel2" data-slide-to="0" class="active"></li>
            <li data-target="#myCarousel2" data-slide-to="1"></li>
            <li data-target="#myCarousel2" data-slide-to="2"></li>
            <li data-target="#myCarousel2" data-slide-to="3"></li>
        </ol>
        <!-- Carousel items -->
        <div class="carousel-inner">
            <div class="active item project-1">
                <img class="row" src="includes/uploads/<?=$project?>/test1.jpg" />

            </div>
            <div class="item">
                <img class="row" src="includes/uploads/<?=$project?>/test2.jpg" />
            </div>
            <div class="item">
                <img class="row" src="includes/uploads/<?=$project?>/test3.jpg" />
            </div>
            <div class="item">
                <img class="row" src="includes/uploads/<?=$project?>/test4.jpg" />
            </div>

        </div>
        <!-- Carousel nav -->

        <a class="left carousel-control" href="#myCarousel2" role="button" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
        </a>
        <a class="right carousel-control" href="#myCarousel2" role="button" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
        </a>
    </div>
    <!-- LINKED NAV -->

</div>

finally, the JQuery code: $(document).ready(function() {

    $(".show-gallery").click(function() {
        $.ajax({
            url: 'public/projects-content.php',
            type: 'POST',
            data: {
                projectName: 'test'
            },
            dataType: 'json',
            success: function(data) {
                $('#ajax').html(data);


            },

            error: function(jqXHR, textStatus, errorThrown) {
                $('#ajax').html('');
                alert('Error Loading');
            }
        });

        $("#ajax").load("public/projects-content.php", function(response, status, xhr) {
            if (status == "error_origin") {
                var msg = "Sorry but there was an error when loading the page's content: ";
                $("#ajax").html(msg + xhr.status + " " + xhr.statusText);
            }
        });
 });

laravel views in Semantic-UI tabbed layout

I have a very basic problem with AJAX. I wish to use a tabbed layout with AJAX loading of my content.

http://ift.tt/1IK3KNj

see Retreiving Remote Content section.

My problem: I have no clue how replace the mockup AJAX

      mockResponse    : function(settings) {
    var response = {
      first  : 'AJAX Tab One',
      second : 'AJAX Tab Two',
      third  : 'AJAX Tab Three'
    };

with views defined in my controller.

May I ask somebody to show me a working example.

Thank you in advance.

What is the best way to get live updates on Shared Hosting?

Currently I am using "Traditional" Polling Ajax Method to get live updates from my mysql database. It updates 3 or 4 php files every second and time to time my CPU gets crazy.

Is there any other method to use on Shared Hosting? Or is there a way optimize codes?

I am sorry I have not have such knowlodge about javascript.

Passing a javascript variable to php and then back to html

I have an html page with a form where I'd like to submit a value and send it, using javascript (w/jquery & ajax), to a php page where a certain process occurs, which I'd like to keep track of on the html page by sending back a variable multiple times to the original html page, perhaps into the empty div (id=txtHint). Below is what I have so far...

me.html

<html>
<head>
    <title>Generator</title>
    <script src="jquery-1.9.1.min.js" type="text/javascript"></script>
    <script src="howdy.js" type="text/javascript"></script>
</head>

<body>
    <div id="form_container">
        <h1>Generator</h1>
        <form id="myForm" name="myForm">
            <input id="myStr" type="text">
            <input id="regrForm" type="button" name="submit" value="Submit">
            </center>
        </form> 
    </div>
    <div id="txtHint"></div>
</body>
</html>

howdy.js

$(document).ready(function() {

    $("#regrForm").click(function(){

        var myText = $("#myStr").val();

        $.ajax({
            url: 'tracker.php',
            type: 'POST',
            data: {
                newStr: myText},
            dataType: "text",
            success: function(data){
                console.log("It went through!");
                $('#txtHint').html(data);
            }
        });
    });
});

tracker.php

<?php
    $myName = $_POST['newStr'];
    echo "<p> My string is: " . $myName . "</p>";

    for ($i=0; $i<1000000; $i++){

        //analyze stuff

        if ($i % 100000 === 0){
            echo "Total number of things analyzed: " . $i . " from " . $myName;
        }
    }
?>

The problem is, I'm not entirely sure my variables are getting passed appropriately from javascript to php and also how exactly to pass the php updates (which iteration I'm on via $i) back to the html page...any thoughts? If I'm not providing enough information, please let me know. I appreciate any constructive help you can offer.

How to refesh conent when using CrossroadJS and HasherJS with KnockoutJS

I was following Lazy Blogger for getting started with routing in knockoutJS using crossroads and hasher and it worked correctly.
Now I needed to refresh the content using ajax for Home and Settings page every time they are clicked. So I googled but could not find some useful resources. Only these two links

  1. Stack Overflow Here I could not understand where to place the ignoreState property and tried these. But could not make it work.

        define(["jquery", "knockout", "crossroads", "hasher"], function ($, ko, crossroads, hasher) {
    
        return new Router({
            routes:
            [
                { url: '', params: { page: 'product' } },
                { url: 'log', params: { page: 'log' } }
            ]
        });
    
        function Router(config) {
            var currentRoute = this.currentRoute = ko.observable({});
    
            ko.utils.arrayForEach(config.routes, function (route) {
                crossroads.addRoute(route.url, function (requestParams) {
                    currentRoute(ko.utils.extend(requestParams, route.params));
                });
            });
            activateCrossroads();
        }
    
        function activateCrossroads() {
            function parseHash(newHash, oldHash) {
                //crossroads.ignoreState = true; First try
                crossroads.parse(newHash);
            }
            crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;
    
            hasher.initialized.add(parseHash);
            hasher.changed.add(parseHash);
            hasher.init();
    
            $('a').on('click', function (e) {
                crossroads.ignoreState = true; //Second try
            });
    
        }
    });
    
    
  2. Crossroads Official Page Here too I could not find where this property need to be set.

If you know then please point me to some url where I can get more details about this.

form validation and submission

I am using formvalidation.io but I cannot stop the form submitting on successful validation. It immediately submits request and refreshes page. I need to send form information via ajax.

I must be overlooking something obvious?

http://ift.tt/1Dqg055

jQuery('#estimateForm1')
        .formValidation({
            framework: 'bootstrap',
            err: {
                container: 'tooltip'
            },
            icon: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                Name: {
                    row: '.col-md-8',
                    validators: {
                        notEmpty: {
                            message: 'The first name is required'
                        },
                        stringLength: {
                            min: 2,

                            message: 'Must be at-least 2 characters long.'
                        },
                        regexp:
                        {
                            message: 'Please only use A-Z characters.',
                            regexp: /^[a-zA-Z]+$/
                        }

                    }
                },
                Phone: {
                    row: '.col-md-8',
                    validators: {

                        notEmpty: {
                            message: 'The phone number is required'
                        },
                        stringLength: {
                            min: 14,
                            max: 15,
                            message: 'Not a valid phone #.'
                        },
                        regexp: {
                            message: 'The phone number can only contain the digits, spaces, -, (, ), + and .',
                            regexp: /^[0-9\s\-()+\.]+$/
                        }
                    }
                },
                Email: {
                    row: '.col-md-8',
                    validators: {
                        notEmpty: {
                            message: 'The email address is required'
                        },
                        regexp: {
                            regexp: '^[^@\\s]+@([^@\\s]+\\.)+[^@\\s]+$',
                            message: 'The value is not a valid email address'

                        }


                    }
                }


            }

        }).find('[name="Phone"]').mask('(000) 000-0000')
        .on('success.field.fv', function(e, data) {
            if (data.fv.getSubmitButton()) {
                e.preventDefault();
                //data.fv.disableSubmitButtons(true);
                 console.log('prevented submission');
            }

        }).on('success.form.bv',function(e)
        {
            e.preventDefault();


           console.log('prevented submission');


        });

JSF - Ajax render only if element exists

I have the following usecase: I have a button on the screen which rerenders an other element.

<h:commandButton value="button">
  <f:ajax  execute="@this" render="toBeRendered" />
</h:commandButton>
......
<h:outputPanel id="toBeRendered"/>

My problem is that this other element (toBeRendered) does not always exists so JSF fails when it builds the view and can't find the element thats in the render attribute of the f:ajax tag. I know that this validation is no longer there in newer version of mojarra but updating is not an option. Does anybody has a workaround that so that it would only render when the other element exists?

SAP UI5 upload file and oData response

I am developing a SAPUI5 in order to upload files [mainly XML ]. I have implemented the view using XML views within the WebIDE as well as the corresponding JS controller, which is calling an oData service matched with 'create_stream' method then doing the job of reading the file content.

All is working fine but then I cannot receive the response containing the file content [parsed] from the oData back to my js controller.

Here is my ajax call, actually there are two calls but the first one is used to get the necessary security csrf token only.

jQuery.ajax({url : Service1,

                type : "GET",

                async: false,

                beforeSend : function(xhr) {

                  xhr.setRequestHeader("X-CSRF-Token", "Fetch");

                },

                success : function(data, textStatus, XMLHttpRequest) {

                  token = XMLHttpRequest.getResponseHeader("X-CSRF-Token");

                }

              });

              $.ajaxSetup({

                cache : false

              });

              jQuery.ajax({

                url : service_url,

                async : false,

                dataType : "text",

                cache : false,

                data : filedata,

                type : "POST",

                beforeSend : function(xhr) {

                  xhr.setRequestHeader("X-CSRF-Token", token);

                  xhr.setRequestHeader("Content-Type", "application/text;charset=UTF-8");

                },

                success : function(odata) {

                  oDialog.setTitle("File Uploaded");

                  oDialog.open();

                  document.location.reload(true);

                },

                error : function(odata) {

                  oDialog.setTitle("File NOT Uploaded");

                  oDialog.open();

                  document.location.reload(true);

                }

              });

Can anyone find where I am wrong within this flow ?

I think the problem might be in the ajax call, maybe in the parameters or in the way I am getting the data as response from the oData service ?

Or the issue could be whithin the oData create_stream method ?

Browser saving password with AJAX form

I'm making a web-project on PHP and it has a login form. For some reasons, the form is sending by AJAX request. So, browser does not prompt for saving login/password pair. I've googled a lot, so please don't send me there. Everywhere there is one solution.

<iframe src="about:blank" name="login_frame" style="display: none;"></iframe>
<form target="login_frame" action="about:blank" method="post" autocomplete="on" >
    <input type="text" name="username"/>
    <input type="password" name="password"/>
    <input type="submit" value="submit"/>
</form>

It works good for IE 11 and Firefox 37, but doesn't work for Chrome 44 and Opera 31. Could you please tell me how to force Chrome and Opera to prompt a 'save password' dialog?

jQuery AJAX event only firing once

First let me thank @Jasen, he spent 9 days helping me with an issue and it means a lot to me that he took him time to help me. It was this that he was helping me with, but at the last second they decided they wanted to go with AJAX since the contact page uses it and removing items from the cart utilizes it.

Let me get to my issue, I have view (this is MVC 5) that in loop loads all the products of a selected category. I want to use jQuery nd AJAX to add items to the cart. This works great for the first item in the list the first time it is added to the cart.

I imagine my problem is all the buttons have an id of AddToCart and jQuery, the way I have it written can't decide which button is being clicked.

Here is the code for the view

@model IEnumerable<AccessorizeForLess.ViewModels.DisplayProductsViewModel>

@{
    ViewBag.Title = "Products > Necklaces";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/jquery.fancybox.css?v=2.1.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-buttons.css?v=1.0.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-thumbs.css?v=1.0.7" rel="stylesheet" />
<h2>Products > Necklaces</h2>
<div id="update-message"></div>
<p class="button">
    @Html.ActionLink("Create New", "Create")
</p>
@*@using (Html.BeginForm("AddToCart", "Orders", FormMethod.Post))*@
{
    <div id="container">
        <div id="sending" style="display:none;"><img src="~/Content/ajax-loader.gif" /></div>
        <div style="color:red" id="ItemAdded"></div>
        <div class="scroll">

            @foreach (var item in Model)
            {
                <div class="scroll2">
                    <div class="itemcontainer">
                        <table>
                            <tr>
                                <td id="@item.Id" class="divId">
                                    <div class="DetailsLink" id="@item.Id"> &nbsp;&nbsp;&nbsp;@Html.ActionLink(@item.Name, "Details", new { id = item.Id })</div>
                                    <br />
                                    <div id="@item.Id"></div>
                                    <div class="divPrice" id="@item.Price">@Html.DisplayFor(modelItem => item.Price)</div>
                                    <div class="divImg"><a class="fancybox-thumbs" href="@item.Image.ImagePath" title="@item.Image.AltText" data-fancybox-group="thumb"><img src="@item.Image.ImagePath" alt="@item.Image.AltText" title="@item.Image.AltText" /></a></div>
                                    <div>&nbsp;</div>
                                    <div class="divQuantity">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity: @Html.TextBoxFor(modelItem => item.Quantity, new { @id = "quantity", @style = "width:50px;", @class = "formTextBox" })</div>
                                    <div class="form-group">
                                        <div class="col-md-offset-2 col-md-10">
                                            <input type="button" value="AddToCart" class="btn btn-default" id="AddToCart" />
                                        </div>
                                    </div>
                                    <div style="height:15px;"></div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                    }
                    <div class="button">@Html.ActionLink("Back To Categories","Categories")</div>
                    <br />
       </div>        
    </div>
@*}*@

And here is my jQuery code:

@section scripts {
    <script src="~/Scripts/jQuery-jScroll.js"></script>
    <script src="~/Scripts/jquery.fancybox.js?v=2.1.5"></script>
    <script src="~/Scripts/jquery.fancybox-thumbs.js?v=1.0.7"></script>
    <script src="~/Scripts/jquery.fancybox-buttons.js?v=1.0.5"></script>
    <script type="text/javascript">
            //$(function () {
            //    $('.scroll').jscroll({
            //        autoTrigger: true
            //    });
                $('.fancybox-thumbs').fancybox({
                    prevEffect: 'none',
                    nextEffect: 'none',

                    closeBtn: true,
                    arrows: false,
                    nextClick: false
                });

                // Document.ready -> link up remove event handler
                $("#AddToCart").click(function () {
                    //first disable the button to prevent double clicks
                    $("#AddToCart").attr("disbled", true);
                    $("#AddToCart").prop("value", "Adding...");
                    $("#ItemAdded").text("");
                    //now show the loading gif
                    $("#sending").css("display", "block");
                    // Get our values
                    var price = parseFloat($(".divPrice").attr("id"));
                    var quantity = parseInt($("#quantity").val());
                    var id = parseInt($(".divId").attr("id"));

                    $.ajax({
                        url: "@Url.Action("AddToCartAJAX", "Orders")",
                        type: "POST",
                        data: { "id": id, "quantity": quantity, "price": price },

                        //if successful
                        success: function (data) {
                            successfulCall()
                        },
                        error: function (data) {
                            alert(data.Message);
                        }
                    });

                    function successfulCall() {
                        //enable the send button
                        $("#AddToCart").attr("disbled", false);

                        //hide the sending gif
                        $("#sending").css("display", "none");

                        //change the text on the button back to Send
                        $("#AddToCart").prop("value", "Add to Cart");

                        //display the successful message
                        $("#ItemAdded").text("Your item has been added to your order.");

                        //clear out all the values
                        $("input#quantity").val("0");
                    }

                    function errorCall() {
                        $("#AddToCart").attr("disbled", false);
                        $("#sending").css("display", "none");
                        $("#AddtoCart").prop("value", "Add to Cart");
                        $("#ItemAdded").text(data.message);
                    }
                    //alert('Clicked!');
                });
            //s});
    </script>
}

Can someone show me what I am doing wrong here so I can get this working?

EDIT #1

Here is the updated jQuery code:

$(".AddToCart").click(function () {
//first disable the button to prevent double clicks
$(this).prop("disbled", true).prop("value", "Adding...");
$("#sending").css("display", "block");
var td = $(this).closest('td')

//traverse DOM and find relevant element 
var price = parseFloat(td.find(".divPrice").prop("id")),
    quantity = parseInt(td.find("#quantity").val()),
    id = parseInt(td.find(".divId").prop("id"));

$.ajax({
    url: "@Url.Action("AddToCartAJAX", "Orders")",
    type: "POST",
    data: { "id": id, "quantity": quantity, "price": price },
    //if successful
    success: function (data) {
        successfulCall()
    },
    error: function (data) {
        errorCall(data);
    }
});

It worked before making the client side changes (granted only once and only for the first item in the list), since I havent changed the server side code what could have gone wrong? EDIT #2

Here is the whole thing in it's entirity

@model IEnumerable<AccessorizeForLess.ViewModels.DisplayProductsViewModel>

@{
    ViewBag.Title = "Products > Necklaces";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/jquery.fancybox.css?v=2.1.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-buttons.css?v=1.0.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-thumbs.css?v=1.0.7" rel="stylesheet" />
<h2>Products > Necklaces</h2>
<div id="update-message"></div>
<p class="button">
    @Html.ActionLink("Create New", "Create")
</p>
@*@using (Html.BeginForm("AddToCart", "Orders", FormMethod.Post))*@
{
    <div id="container">
        <div id="sending" style="display:none;"><img src="~/Content/ajax-loader.gif" /></div>
        <div style="color:red" id="ItemAdded"></div>
        <div class="scroll">

            @foreach (var item in Model)
            {
                <div class="scroll2">
                    <div class="itemcontainer">
                        <table>
                            <tr>
                                <td id="@item.Id" class="divId">
                                    <div class="DetailsLink" id="@item.Id"> &nbsp;&nbsp;&nbsp;@Html.ActionLink(@item.Name, "Details", new { id = item.Id })</div>
                                    <br />
                                    <div id="@item.Id"></div>
                                    <div class="divPrice" id="@item.Price">@Html.DisplayFor(modelItem => item.Price)</div>
                                    <div class="divImg"><a class="fancybox-thumbs" href="@item.Image.ImagePath" title="@item.Image.AltText" data-fancybox-group="thumb"><img src="@item.Image.ImagePath" alt="@item.Image.AltText" title="@item.Image.AltText" /></a></div>
                                    <div>&nbsp;</div>
                                    <div class="divQuantity">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity: @Html.TextBoxFor(modelItem => item.Quantity, new { @style = "width:50px;", @class = "formTextBox quantity" })</div>
                                    <div class="form-group">
                                        <div class="col-md-offset-2 col-md-10">
                                            <input type="button" value="AddToCart" class="btn btn-default AddToCart" />
                                        </div>
                                    </div>
                                    <div style="height:15px;"></div>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                    }
                    <div class="button">@Html.ActionLink("Back To Categories","Categories")</div>
                    <br />
       </div>        
    </div>
@*}*@
@section scripts {
    <script src="~/Scripts/jQuery-jScroll.js"></script>
    <script src="~/Scripts/jquery.fancybox.js?v=2.1.5"></script>
    <script src="~/Scripts/jquery.fancybox-thumbs.js?v=1.0.7"></script>
    <script src="~/Scripts/jquery.fancybox-buttons.js?v=1.0.5"></script>
    <script type="text/javascript">
            //$(function () {
            //    $('.scroll').jscroll({
            //        autoTrigger: true
            //    });
                $('.fancybox-thumbs').fancybox({
                    prevEffect: 'none',
                    nextEffect: 'none',

                    closeBtn: true,
                    arrows: false,
                    nextClick: false
                });

                // Document.ready -> link up remove event handler
                $(".AddToCart").click(function () {
                    //first disable the button to prevent double clicks
                    $(this).prop("disbled", true).prop("value", "Adding...");
                    $("#sending").css("display", "block");
                    var td = $(this).closest('td')

                    //traverse DOM and find relevant element 
                    var price = parseFloat(td.find(".divPrice").prop("id")),
                        quantity = parseInt(td.find(".quantity").val()),
                        id = parseInt(td.find(".divId").prop("id"));

                    $.ajax({
                        url: "@Url.Action("AddToCartAJAX", "Orders")",
                        type: "POST",
                        data: { "id": id, "quantity": quantity, "price": price },
                        //if successful
                        success: function (data) {
                            successfulCall()
                        },
                        error: function (data) {
                            errorCall(data);
                        }
                    });

                    function successfulCall() {
                        //enable the send button
                        $(this).prop("disbled", false).prop("value", "Add To Cart");

                        //hide the sending gif
                        $("#sending").css("display", "none");

                        //display the successful message
                        $("#ItemAdded").text("Your item has been added to your order.");

                        //clear out all the values
                        $("input#quantity").val("0");
                    }

                    function errorCall(data) {
                        $(this).prop("disbled", false).prop("value", "Add To Cart");
                        $("#sending").css("display", "none");
                        $("#ItemAdded").text(data.message);
                    }
                    //alert('Clicked!');
                });
            //s});
    </script>
}

EDIT #2

Here is the code for AddToCartAJAX in OrdersController:

public ActionResult AddToCartAJAX(int id, int quantity, decimal price)
{
    var cart = ShoppingCart.GetCart(this.HttpContext);

    cart.AddToCart(id, quantity, price);

    return RedirectToAction("Index");
}

And AddToCart in ShoppingCrt.cs:

public void AddToCart(int id, int quantity, decimal price)
{
    // Get the matching cart and product instances
    var order = entities.Orders.FirstOrDefault(
        c => c.OrderGUID == ShoppingCartId
        && c.OrderItems.Where(p => p.ProductId == id).FirstOrDefault().ProductId == id);

    if (order == null)
    {
        // Create a new order since one doesn't already exist
        order = new Order
        {
            InvoiceNumber = Guid.NewGuid().ToString(),
            OrderDate = DateTime.Now,
            OrderGUID = ShoppingCartId,
            IsShipped = false
        };
        entities.Orders.Add(order);

        // Save changes
        entities.SaveChanges();

        //add the OrderItem for the new order
        OrderItem oi = new OrderItem()
        {
            OrderId = order.OrderId,
            OrderGUID = ShoppingCartId,
            ProductId = id,
            ProductQuantity = quantity,
            ProductPrice = price
        };

        entities.OrderItems.Add(oi);
        entities.SaveChanges();
    }
    else
    {
        // If the item does exist in the cart, 
        // then add one to the quantity
        order.OrderItems.Where(p => p.ProductId == id).FirstOrDefault().ProductQuantity += quantity;
    }
}

Hope that helps

Ajax Post in MVC... Why is the string null?

So basically I'm creating a Request system in a MVC application. I have this "Create Request" section where I can select the type of request I want to do in a DropDownList from Telerik. What I want to do is, every time I choose something from the list, a partial view appears with the form related to that type of request.

This is my ajax Post from the Create.cshtml View:

<script>
    function change() {
        var value = $("#RequestType").val();
        alert(value);
        $.ajax({
            url: "/Request/CreateRequestForm",
            type: "get",
            data: { requestValue : JSON.stringify(value)}
        }).done(function (data) {
            $("#partialplaceholder").html(data);
        }).fail(function () {
            alert('error');
        })
    };
</script>

This is my controller:

public ActionResult Index()
        {
           //Things
            return View();
        }

    [HttpGet]
    public ActionResult Create()
    {
        return View();
    }

    [HttpGet]
    public PartialViewResult CreateRequestForm(string dropDownValue)
    {   string partialView="";
        int RequestType = Convert.ToInt32(dropDownValue);
        switch (RequestType)
        {
            case 1 :
                partialView+="_CreateAbsence";
                break;
            case 2 :
                partialView += "_CreateAdditionalHours";
                break;
            case 3 :
                partialView += "_CreateCompensationDay";
                break;
            case 4 :
                partialView += "_CreateErrorCorrection";
                break;
            case 5 :
                partialView += "_CreateVacation";
                break;
        }
        return this.PartialView(partialView);
    }

Everytime time the even triggers my dropDownValue string is null... Why? Thanks in advance! :)

EDIT View Code

<h1>Create New Request</h1>

        @(Html.Kendo().DropDownList()
          .Name("RequestType")
          .DataTextField("Text")
          .DataValueField("Value")
          .Events(e => e.Change("change"))
          .BindTo(new List<SelectListItem>() {
              new SelectListItem() {
                  Text = "Absence",
                  Value = "1"
              },
              new SelectListItem() {
                  Text = "Additional Hours",
                  Value = "2"
              },
              new SelectListItem() {
                  Text = "Compensation Day",
                  Value = "3"
              },
              new SelectListItem() {
                  Text = "Error Correction",
                  Value = "4"
              },
              new SelectListItem() {
                  Text = "Vacation",
                  Value = "5"
              }
          })
          .Value("1")
        )


<script>
    function change() {
        var value = $("#RequestType").val();
        alert(value);
        $.ajax({
            url: "/Request/CreateRequestForm",
            type: "get",
            data: { requestValue : JSON.stringify(value)}
        }).done(function (data) {
            $("#partialplaceholder").html(data);
        }).fail(function () {
            alert('error');
        })
    };
</script>

<div id="partialplaceholder">

</div>

Web method not called from ajax post

I am trying to call a method as web method from ajax like:

$.ajax({
                    url: 'http://ift.tt/1SI1MDN',
                    method: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    //data: angular.toJson(categories),
                    data: angular.copy(categories)

Here categories is serialized as

 [
    {
        "name": "Fruits",
        "metrics": "cups",
        "entry": 0,
        "recommended": true,
        "color": "#989898"
    },
    {
        "name": "Vegetables",
        "metrics": "cups",
        "entry": 1,
        "recommended": true,
        "color": "#37A0BC"
    }
]

Webmethod is like:

        [WebMethod(true)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string AddSelfEntry(List<Entry> items)
        {

Here entry is

public class Entry
        {
            public string name;
            public string metrics;
            public int entry;
            public bool recommended;
            public string color;
            //{"name":"Sugary Drinks","metrics":"times","entry":1,"recommended":false,"$$hashKey":"00F"}
        }

I am getting error at console:

enter image description here

No breakpoint hit at webmethod in debugmode.

Please help where I am wrong?

output AJAX response in Javascript Array? [duplicate]

This question already has an answer here:

I'm not entirely sure if this is possible but I am trying to use an ajax response in a javascript array in my page.

this is what I have:

var interval = 5000;
function doAjax() {
    jQuery.ajax({
            type: 'POST',
            url: 've.php',
            dataType : 'json',
            success: function (data) {


            //var arr = data.split('|');
                    jQuery('#counterint').html(data);

                    var res = $.parseJSON(data);   



//test: simulated ajax

var testLocs = {

<<<<<<<<<<<<<< I NEED TO USE THE "data" HERE >>>>>>>>>>>>>>>>>

    };


setMarkers(testLocs); 

The ajax response looks like this when I outputs it on my page in the browser:

1: { info: '1. rooz', lat: 51.5033630, lng: -0.1276250 },2: { info: '1. Rooz555', lat: 51.5033567, lng: -0.1276444 },3: { info: '1. david', lat: 51.5033777, lng: -0.1276777 },4: { info: '1. sam', lat: 51.5033555, lng: -0.1276543 },

any help would be appreciated.

How to pass NULL value in ajax jquery call?

I have a problem with my Ajax post call. I have two fields one for amount and one for Datetime. I want to be able to pass both values as null values and the program shouldn't crash. My C# method head look like this

public ActionResult Update(int invoiceNumber, DateTime start,decimal payAmount = 0)

And my Jquery code look like this

$(document.body).on("click", ".changeInvoice", function (e) {
        e.preventDefault();
        var invoiceNr = $("#invoiceNumber").val();
        var start = $("#date").val();
        var payAmount = $("#payAmount").val();
        console.log(invoiceNr);

        var updateInvoice =
        {
            invoiceNumber: invoiceNr,
            start: start,
            payAmount: payAmount
        }
        $.ajax({
            type: "POST",
            url: "URL",
            data: updateInvoice,
            success: function (response) {
                location.reload();

            }
        });

If i run the program now its crashes if a user doesn't fill in the start datetime value. But if i set a Datetime? start in my C# code the valdidation works without a crash but then i cant do this in my C# code. As i have understood you cant add days to a nullable datetime variable. Any Suggestions?:

i.FirstReminderDate = start.Date.AddDays(10);

Access from change event to other input html jquery autocreate

My problem is:

I have a page with a table is auto generated with ajax-jquery

My table is 3 <td> 1: name 2-3: checkbox for parameters

I set event on all input:checkbox ("change") event.

The problem appears when i try to get check state of checkbox different than i click.

code:

$(document).ready(function() {

   $("#permessiAttributiDiv").on("change", "input:checkbox", function() {
        var IDPermesso = $(this).attr("id").substring(1);
        var selezionatoSpuntato = (this.checked);
        var altro = $(this).parent().find("input:checkbox").checked;
        var scheda = $("#selectTipo").val();
    });
)};

I also try to get check state by id but i always doesn't work......

I see if the checkbox is write in html static code all works ok but if i generate it with jquery i can't access to input with any selector.....

Can anyone help me?

Thanks

Share pushState generated link with social networks

before implementing history.pushState my site I wonder if there is any way to change or to include data generated URLs as targets for social networks such as fb, these metatags are essential for sharing content:

<meta property="og:title" content="My website"/>
<meta property="og:image" content="http://ift.tt/1Dg70PW"/>
<meta property="og:site_name" content="Website"/>
<meta property="og:type" content="website" />
<meta property="og:url" content="http://www.example.com/" />

My website load content via AJAX and do not really know what would be a viable solution for sharing ajax generated content in social networks.

In addition I have plugins facebook comments and likes on my website without a URL do not work, always count the likes of index.php

Another solution I think is to make a copy of each content loaded by Ajax in new HTML pages and are these that are used to share content, but do not know if this will be good. Is it bad for SEO do this? ¿Penalize me for duplicate content?You could generate a sitemap?

Can I help you could decide?

How to send image as ajax parameter

I need to save object HTMLImageElement in excel file. I am using highchart and get the image of the chart by getSVG method (Overall process in [http://ift.tt/1JJRGwy])

Now i am trying to write this image into excel file. for doing that i need to pass the image by webservice but i am stuck into overall process. what i have tried is the following:

var svg = chart.getSVG({
                 exporting: {
                     sourceWidth: chart.chartWidth,
                     sourceHeight: chart.chartHeight
                 }
             });             

             var canvas = document.createElement('canvas');
             canvas.height = render_height;
             canvas.width = render_width;

             var image = new Image;
             image.onload = function () {
                 canvas.getContext('2d').drawImage(this, 0, 0, render_width, render_height);                  
                 var data = canvas.toDataURL("image/png")
                 download(data, filename + '.png');
             };



        var dataitem= JSON.stringify({ data: image});

        $.ajax({
            type: "POST",
            contentType: "application/json;charset=utf-8",
            datatype: "json",
            data: dataitem,
            url: "FrontDesign/Sendimage",
            success: function (data) {
                 //code for success
            }
        });

I know JSON.stringify({ data: image}) is not process to pass. Any Suggestion regarding this matter?

Want to generate a pdf with Ajax response not getting in proper format

I am getting a response like that i have attached image please check it and give me solution to convert in json enter image description here enter image description here

Code.

Ext.Ajax.request({method : 'POST',url:''withCredentials : true,defaultXhrHeaders:{'Content-Type': 'application/x-www-form-urlencoded'},disableCaching : true,success: function(response){}});

Passing string which is the name of entity/perisistance class in createcriteria of hibernate

I have to dynamically load tables for which I was passing through controller and when I have to write hibernate peristance logic of suppose createCriteria, I gave:

getSession().createCriteria( Class.forName(tableName)).list()

where tableName is a string which would contain the name of the class. Even then I was unscessful and getting ClassNotFound Exception. It works for

getSession().createCriteria(Book.class).list() which I feel is hardcoding in my case. Please help regarding with which I could dynamically call tables.

how to add multiple http get methods with id as param?

I am writing web API, and have to add two get method with id as parameter.

1st api method :

[Route("{id}")]
    public IHttpActionResult GetItem(int id) {
        // some code
    }

2nd api method :

[Route("clientid/{id}")]
    public IHttpActionResult GetItemByClientID(int id) {
        // some code 
    }

ajax call :

$http({
       url: 'api/mycontroller/clientid',
       method: 'get',
       params: { id: id }
})

but its call 1st api method, so how can I call my second api method ?

Thanks in advance.

WCF Service - using AJAX to pass stored procedure name as data

I am writing a webpage which displays many different charts, using AJAX to get the data from the database and google charts to display the information.

Is there a way that I can pass in the stored procedure name from AJAX to the code behind webMetod? At the moment I am having to create a separate webMethod for each stored procedure whereas I would like to just have one method where I pass which procedure to call.

I have tried adding as a parameter and data but have not been able to make it work.

I am using WCF service to pull data from the database, here is my WebMethod, you will see the stored proc name 'GetChartDataConceptDoubleLayerComboTwoBars' which I would like to pass as a param.

[WebMethod]
public static List<ChartData> GetDoubleLayerChartTwoBars()
{
    System.ServiceModel.BasicHttpBinding userHttpBinding = new System.ServiceModel.BasicHttpBinding();
    userHttpBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
    userHttpBinding.MaxReceivedMessageSize = int.MaxValue;
    System.ServiceModel.EndpointAddress userHtpEndpointAddress = new System.ServiceModel.EndpointAddress(chartDataDoubleLayerFactoryURI);
    ChartDataDoubleLayerTDFactory chartFactory = new ChartDataDoubleLayerTDFactory(userHttpBinding, userHtpEndpointAddress);

    TDBindingList<ChartDataDoubleLayerTD> chartDataRaw = chartFactory.GetChartDataConceptDoubleLayerComboTwoBars();

    List<ChartData> chartData = new List<ChartData>();
    chartData = channelReportingSummary.getData(chartDataRaw);

    chartFactory.Close();

    return chartData;
}

Here is the Ajax

$.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    processData: false,
    url: 'http://ift.tt/1KOwoMR',
    dataType: 'json',
    timeout: 120000,
    async: false,
    success: function(result) {
        createDatatableCombo(result, data, options);
    },
    error: function(xhr) {
        alert(xhr.responseText);
    }
});

Ajax call request in CodeIgniter with CSRF enabled

I am using an ajax call to save value of a radio button through hidden field in database using ajax call, used an alert to see if its working, and it is.

The URL I mentioned in the ajax call is redirecting it to a controller but I used an alert to see if its working, but its not working. Can't locate what's the issue.

Here is the code of ajax call in view:

<script type="text/javascript">
$('#save').click(function(){
    var hint=$('#hidfield').val();
    alert('Oops, your response is '+hint);

    $.ajax({
        url: '<?php echo base_url();?>welcome/save_answer',
        type: "post",
        dataType: "html",
        data:{hint:$hint, <?php echo $this->security->get_csrf_token_name();?>: "<?php echo $this->security->get_csrf_hash();?>"},
        success: function(data) {

        }
    });
});
</script>

Here is the controller:

function save_answer()
{
    alert('You Can Do It !!');
    $data = array(
        'hint'=>$this->input->post('hint')
    );

    $this->base_model->save_answer($data);
}

Here is the model:

function save_answer($data)
{       
    $this->db->insert('questions',$data);
}

Please suggest some way out.

jquery button after ajax call [duplicate]

This question already has an answer here:

I need after a ajax call to add a on click button for a slider images. But my button on click doesn't work. What can I do?

$(document).ready(function() {

$("#imgnext").click(function() {
      console.log("ciao");
      alert( "Handler for .click() called." );
  });
$('#box2').click(function (){

    var data;
    $.getJSON('data/one.json', function(jd) {
         $.each(jd, function (index, value) {
             data = value; 
             $('#textbox').html(data['name']);
             $('#textbox').append("<br>"+data['details']);
             $('#textbox').append("<br>"+data['composition']);
             for (i=0; i<data['modelDetails'].length; i++) {
                 $('<p>' + data['modelDetails'][i] +'</p>').appendTo('#textbox');
             }
             $('<button id="imgnext" ><strong>></strong></button>').appendTo('#textbox');
             for (i=0; i<data['images'].length; i++) {
                 $('<img id="imgbox" src="'+data['images'][i]+'" />').appendTo('#textbox');
             }
            });
     });
    return false;
});

});

How to assign value to global variable in bean through ajax

I need your help in assigning the entered value in an inputText to a global variable that can be used in multiple methods in a bean. The JSF page has the code:

<p:inputText id="refNo2" value="#{Bean1.refNo}">
    <p:ajax event="keyup" update="ref2" />
</p:inputText>

<h:outputText id="ref2" value="#{Bean1.refNo}"/> 

With the above code anything that is entered in the inputText, it will be shown in the outputText. And the java code for refNo in Bean1 is:

private String refNo = "";

public void setRefNo(String refNo) {
    this.refNo = refNo;
}

public String getRefNo() {
    return refNo;
}

In Bean1, I am calling a method which is called showRef() that has the code:

public void showRef() {
    System.out.println("Reference No. is"+refNo);
}

It is printing the value as blank or empty where the user entered in the inputText the value = 777 and it was shown in the outputText. So how can I get the value of the refNo in the showRef() method?

Internet explorer hanging with long running AJAX WebMethod on SetTimeout

I have a couple of SetTimeouts for when the page loads which will load in chart data using AJAX calls to the code behind.

    $(document).ready(function() {
        window.setTimeout(drawGraphs, 0);
        window.setTimeout(drawGraphsCharts, 0);
    });

This works great in Chrome and Firefox, however if one of the methods takes a long time, e.g. 1-5 seconds to finish, Internet Explorer hangs when this is taking place until this has completed, rather than loading one by one like the other browsers.

Has anyone come across this and how to fix it.

I am simulating a long running method at the moment using the following in my web method.

    for (var i = 0; i < 1000000000; i++)
    {
        var test = i + i;
        var test2 = i * i;
    }

php user logging out with or without AJAX

My colleague and me are having a hard time trying to solve this problem. We have a special kind of webshop, because we have customers and sub-customers. If the person logged in is a sub-customer, we want to show some extra html on our page. This works, but if a sub-customer logs out, and a normal customer logs in, the extra html is still visible, but we don't understand how this is possible. The problem is also vice versa: if the first logged in is a normal user, then logs out, then a sub-customer logs in, the extra html is not visible.

1. loginck.php

//after the user types his e-mail end password, we check if its a normal user or a sub-user. If normal user then => $_SESSION['multiklant'] = 0; else sub-user then => $_SESSION['multiklant'] = 1; else $_SESSION['multiklant'] = 0; //user not found

2. index.php

if ($_SESSION['multiklant'] == 1) {
   $userid = $_SESSION['userid'];

echo "<div class='col-md-3'>";
echo "<label for='leveradres'>Leveradres*:</label><br/>";
echo "<select id='leveradres' class='form-control'>";
echo "<option value='0'>Selecteer...</option>";

$qry = "SELECT * FROM LEVERADRESSEN WHERE LA_EMAIL = '" . $_SESSION['klemail'] . "'";
$res = mysqli_query($link, $qry);
while ($row = mysqli_fetch_assoc($res)) {
echo "<option value='" . $row['LA_ID'] . "'>" . $row['LA_NAAM'] . "</option>";
}

echo "</select>";
echo "</div>"; 
}

3.1 logout click on index.php

$("#logout").click(function () {
    var lgout = $.get("logout.php");
    lgout.done(function (data) {

        $(".show-2").trigger("click");
        $("#logout").addClass("hidden");

    });
});

3.2 logout.php

<?php
    session_start();

    $_SESSION = array();
    session_unset();
    session_destroy();
    header("Location:index.php");
    exit();
?>

As you can see, we used AJAX here, but even without the problem stays. If possible we would like to keep the AJAX, but if not it can be deleted. Also a combination, where the redirect is not in de php but in the javascript part.

Could this be a caching problem? Because if we reload our browser without cache, it al works.

We are searching the internet, including this site already for 6 hours...

Code tested in Chrome on MAC and Internet Explorer 11 on Windows, gives no difference.

AJAX call not working in android emulator, works everywhere else (Cordova)

I have a cordova app that is acting weird. When I try the source on my browser (tested on both chrome and firefox), it works. Not on my Android emulator (got it from the Android SDK).

The weird part is that I have 2 calls. Only one works. Here's my structure.

var httpClient = null;

function login(..) {

  httpClient = $.ajax({
    type: 'POST',
    ...
    ...
  });

  httpClient.done(function(data) {
    ...
    ...
    secondCall();
  });

  httpClient.fail(...);

}

function secondCall() {

  if (httpClient != null) {
    httpClient.abort();
  }

  httpClient = $.ajax({
    type: 'GET',
    ...
    ...
  });

  httpClient.done(...);

  httpClient.fail(...);

}

The POST works. I added a console.log to test what is being fired. The first call works as it should. It called the secondCall() function, and that AJAX call fails. Is it to do with the Emulator not accepting GET requests?

Vue.js-resource: http request with api key (Asana)

I'm trying to extract some projects from the Asana api with vue-resource (http://ift.tt/1JQsHqO), a Vue.js add-on that makes ajax calls simple. I'm using an api key to access Asana, but I can't figure out how to pass the key in the request header using vue-resource.

In jQuery this works, using beforeSend:

 $.ajax ({
        type: "GET",
        url: "http://ift.tt/1HnFw6b",
        dataType: 'json',
        beforeSend: function(xhr) { 
            xhr.setRequestHeader("Authorization", "Basic " + "XXXXXX"); 
        },
        success: function (data){
            // console.log(data);
        }
    });

Where XXXXXX is the Asana api key + ':' converted with btoa(). http://ift.tt/1HnFw6d

Without needing to authenticate, the Vue instance should be fine with a simple request in the ready function:

new Vue({    
    el: '#asana_projects',    
    data: {
        projects : []
    },    
    ready: function() {
        this.$http.get('http://ift.tt/1HnFw6b', function (projects) {
            this.$set('projects', projects); // $set sets a property even if it's not declared
        });
    },    
    methods: {
        //  functions here
    }
});

This, of course, returns a 401 (Unauthorized), since there is no api key in there.

On the vue-resource github page there is also a beforeSend option for the request, but even though it is described right there I can't seem to figure out the correct syntax for it.

I have tried

    this.$http.get( ... ).beforeSend( ... ); 
    // -> "beforeSend is not a function", and

    this.$http.get(URL, {beforeSend: function (req, opt) { ... }, function(projects) { //set... });
    // -> runs the function but req and opt are undefined (of course)

I realize I'm being less than clever as I fail to understand a syntax that is right there in the documentation, but any and all help would be much appreciated!

Any takers?

jQuery autocomplete breaks in Firefox

I have several jQuery autocomplete searches set up like this one. They all work as expected in safari, chrome and opera but not in firefox.

Any ideas what could make firefox choke, have i used deprecated code? the jQuery ui example looks more simple but its not ajax and this method below is the way i could get it to work.

Would appreciate a pointer as to why it doesnt work in firefox.

$('#typeCode').autocomplete({
    appendTo: "#typeLeft",
    source: 'maType/typeSearch.php',
    minLength: 2,
    select: function(event, ui) {
//alert( "You selected: "+ui.item.museum_city);
        var $itemrow = $(this).closest('tr');
        $itemrow.find('#typeCode').val(ui.item.content+ " "+ ui.item.museum_city + " " + ui.item.museum_state_name);

    $.ajax({
        url: "maType/typeSearchByName.php?Type="+ui.item.content+"&City="+ ui.item.museum_city +"&StateName="+ ui.item.museum_state_name+"",
        cache: true,
        type: 'get',
        success: function(data) {
            $('#typeRight').fadeOut('100', function(){
            $(this).html(data).fadeIn('250')
            });
        } // success
    }); // ajax

 // Give focus to the next input field to recieve input from user
                $('#itemQty').focus();

        return false;
    }


// Format the list menu output of the autocomplete
}).data( "autocomplete" )._renderItem = function( ul, item ) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.content + " "+ item.museum_city + " " + item.museum_state_name +"</a>" )
        .appendTo( ul );
};

yii 1.1 datepicker's language into ajax rendered view

I am a newbie in Yii and I have a question. I have written an app with Yii (starting from Gii) where I have the admin view for a model with datepicker filters (thanks this tutorial: http://ift.tt/1HnFw66). My language in main config file is setted to "it".
It works fine, BUT if I modify my application for rendering this view after ajax request (first I open a page of my site with the layout, then click on an ajax link to request admin view (without layout)), datepicker's language is setted to japanese first time! How can I resolve this?
I have already included this code in my layout file:

Yii::app()->clientScript->registerScriptFile(Yii::app()->getClientScript()->getCoreScriptUrl() . '/jui/js/jquery-ui-i18n.min.js');

Trigger div refresh without triggering ajaxStart

I have progress bars that start and stop with ajaxStart and ajaxStop.

I have a div that i'm reloading at X interval.

This is triggering the progress bars within the ajax events.

What would be the best way to refresh the div and it be the only item that doesn't trigger the event?

Block ajax script execution before the previous call succeeded

I have a button that executes an ajax function. Sometimes the server lags so maybe an user presses it more times, thinking the first time it didn't work... The main ajax function looks like this:

$.ajax({
        type: "POST",
        url: "page.php",
        dataType: "html",
        data:"data=data",
        success:  function(){
                ajax2();
                ajax3();
        }
    });

Since that ajax function updates db and makes others 2 ajax functions i need to block the button from remake the main ajax func... Only when ajax2() and ajax3() are finished, the button, if pressed, must remake the ajax function. Hope to have explained well my problem!

Ajax request redirecting to cookies page only in Internet Explorer

On Internet Explorer 11 & Edge browsers on Windows 10 (not Windows 7) I can't add products to my shopping cart on our Magento store.

The products are added to the shopping cart with Ajax, and it works fine on all other browsers.

So far my debugging has shown the the Ajax request is redirecting to the enable cookies page of our store on IE11 & Edge for some reason even though cookies are enabled in the browser.

Network Tab on IE11 when I try to add to the cart. enter image description here

But it works in Chrome enter image description here

Nginx ACCESS Log

185.44.130.226 - devhoi [04/Aug/2015:12:10:40 +0000] "GET / HTTP/1.1" 200 12967 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"
185.44.130.226 - devhoi [04/Aug/2015:12:10:43 +0000] "GET /meigeeactions/wishlist/count HTTP/1.1" 200 32 "http://ec2-??-IP.eu-west-1.compute.amazonaws.com/" "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"
185.44.130.226 - devhoi [04/Aug/2015:12:11:11 +0000] "GET /ajax/index/add/uenc/aHR0cDovL2VjMi01Mi0xNy0xNDktMjE4LmV1LXdlc3QtMS5jb21wdXRlLmFtYXpvbmF3cy5jb20v/product/104/form_key/nBovmmLjhDBpr4aE/isAjax/1 HTTP/1.1" 302 5 "http://ec2-??-IP.eu-west-1.compute.amazonaws.com/" "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"
185.44.130.226 - devhoi [04/Aug/2015:12:11:12 +0000] "GET /enable-cookies HTTP/1.1" 200 9485 "http://ift.tt/1MJL6aX" "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"

I have no idea why this is happening, and cookies are enabled in the browser.

enter image description here

Could this be an NGINX issue as it's not happening on our theme we bought demo's page. http://ift.tt/1MJL7fc

Upload image with JavaScript from another server via AJAX

I'm trying (if it's possible) to make an upload of an image stored on another site (not on computer) via JavaScript (jQuery allowed) with an AJAX request.

Lets say that we have the image http://ift.tt/1rCW4Fp. I need to make an AJAX request, submiting this image to http://ift.tt/1M7kZe8.

  • I can't edit the file process.php to accept anything than a valid uploaded file.
  • Browser support is not important.

Is this even possible ? Because of security issues we canțt dynamicaly populate a file field, so maybe the is another way to send the file without having the user to select the file.

I think I should use FormData, not sure.

p:dataTable rowEdit doesn't update row object

I'm trying to edit rows on datatable using rowEdit mode but it doesn't work for me.

Here is the rowEdit event :

<p:ajax event="rowEdit"
        listener="#{saisirHeuresForm.updateMyRow}" 
        update=":saisirHeuresForm:messages"/>

And the managedBean corresponding method :

public void updateMyRow(RowEditEvent event) {
    event.getObject();
}

The event.getObject() method returns the object corresponding to the row which is edited but without any property modification.

Has someone any idea about this problem ?

Thanks in advance for your help