vendredi 31 juillet 2015

Trying to make a call using $resouce and get uncaught identifier response

I'm trying to play with the ajax call from angular. I tried to make from some rest API.. using

$resource(url, { callback: "JSON_CALLBACK" }, { get: { method: "JSONP" }});

I get the data back.. but I can't get rid of the header.. I keep getting Uncaught SyntaxError: Unexpected identifier

thus the parsing can't be done:

Checking origin: '*' (regex: '[a-z0-9]+')<br>Matched!<br>
{"success":1,"errorMessage":"","message":{"chatBotName":"Huge Dragon",
"chatBotID":"110966","message":"You're repeating yourself.","emotion":null}}

How do I delete this part?

Checking origin: '*' (regex: '[a-z0-9]+')<br>Matched!<br>

from my call back?

Any help would appreciated.

How to Increment the quantity using ajax, php sessions?

session_start();

    $id=$_POST['id'];

    $productByCode= Yii::app()->db->createCommand("SELECT * FROM products where id='".$id."'")->queryRow();
    $itemArray = array($productByCode["id"]=>array('ItemName'=>$productByCode["ItemName"], 'id'=>$productByCode["id"], 'price'=>$productByCode["price"], 'quantity'=>$quantity));


if(!empty($_SESSION["cart_item"])) {
    if(in_array($productByCode[0]["code"],$_SESSION["cart_item"])) {
        foreach($_SESSION["cart_item"] as $k => $v) {
        if($productByCode[0]["code"] == $k)
            $_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
        }
    } 
    else {
        $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
    }
} 
else {
    $_SESSION["cart_item"] = $itemArray;
}


if(isset($_SESSION["cart_item"])){
    $item_total = 0;
?>  
<table cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th><strong>Name</strong></th>
<th><strong>Quantity</strong></th>
<th><strong>Price</strong></th>
</tr>   
<?php       
    foreach ($_SESSION["cart_item"] as $item){
        ?>
                <tr>
                <td><strong><?php echo $item["ItemName"]; ?></strong></td>
                <td><?php echo $item["quantity"]; ?></td>
                <td align=right><?php echo "$".$item["price"]; ?></td>
                </tr>
                <?php
        $item_total += ($item["price"]*$item["quantity"]);
        }
        ?>

<tr>
<td colspan="5" align=right><strong>Total:</strong> <?php echo "$".$item_total; ?></td>
</tr>
</tbody>
</table>        
  <?php
}

i have above example code, it shows result when we click on add to cart product, n stores in session

Name    Quantity    Price
Banana  1           $50.00
Banana  1           $50.00
Banana  1           $50.00
Banana  1           $50.00
Banana  1           $50.00
Banana  1           $50.00
                 Total: $300

But i want to display like this, when we click on add to cart button on product, only quantity increase not repeat the products.

Name    Quantity    Price
Banana  6           $50.00

                     Total: $300

Pass single textbox value to the ajax call using jquery

I am using pricing tables. It is having multiple plans with Amount Textbox. Every plan have submit Button. So user can change the textbox value. By clicking submit function the particular pricing table value should pass to the ajax function.

Html Code:

<div class="pricing_table">
            <h3 class="title">RD195</h3>
                <span class="price">Rs.195</span>
                   <ul class="features">
                        <li>10 items</li>
                        <li>Unlimited</li>
                         <li><input type="text" class="discountAmount" value="176" style="width:75px;" /></li>
                        <li>7 Days</li>
                  </ul>
                   <a href="#" class="btn btn-default" onclick="javascript:Plans.Subscribe('RD195','RDPurchase','195');return false;">Subscribe</a>
                  <%--<a href="#" class="btn btn-default" onclick="return vas_confirmcandi('RD195','RDPurchase','195')">Subscribe</a>--%>
             </div>
          </div>

         <div class="pricing_table">

            <h3 class="title">RD545</h3>
                <span class="price">Rs.545</span>
                   <ul class="features">
                        <li>50 items </li>
                        <li>Unlimited</li>
                          <li><input type="text" class="discountAmount" value="491" style="width:75px;" /></li>
                        <li>30 Days</li>
                  </ul>
                   <a href="#" class="btn btn-default" onclick="javascript:Plans.Subscribe('RD545','RDPurchase','545');return false;">Subscribe</a>
                  <%--<a href="#" class="btn btn-default" onclick="return vas_confirmcand('RD545','RDPurchase','545')">Subscribe</a>--%>
             </div>

i want to take the value of discount amount to pass the ajax function. But when i click second table amount of 545, the submit function it is always taking the first value of 176

My Ajax Code:

Plans.Subscribe = function (planName, Description, amount){
var data = $('input[class=discountAmount]').val();
$("#wait").show();
if (planName != undefined) {
    $.ajax({
        type: "POST",
        url: "/plans/getdetail",
        data: { 'Plan': plan, 'Type': Description, 'Amount': amount, 'DiscountAmount': data },
        dataType: "json",
        success: function (response) {
            if (response.Success) {
                $("#wait").hide();
            } else {
               $("#wait").hide();
            }
        },
        error: function (xhr, status, error) {
            $("#wait").hide();
        }
    });
}

};

angular $http service singleton clash

$http service in angular is singleton, and my previous experience with xhr/ ajax request shown to have clash when two request share the same xhr object. Should it not a problem with angular ? if yes how angular handles such situation ?

Control not transferring in JSP Ajax

<script type="text/javascript" language="javascript">  

     var index_x;
        function ajax_login(s,u,p)
        {   
            index_x=new XMLHttpRequest();
            var url="control.jsp?uid="+u+"&sid="+s+"&pwd="+p;
            index_x.onreadystatechange=show_ajaxlogin;
            index_x.open("GET",url,true);
            index_x.send(null);
        }
        function show_ajaxlogin()
        {
            if(index_x.readyState==4 ||index_x.readyState==200)
            {   
                    document.getElementById("forgot").innerHTML=index_x.responseText;
            }

        }

        </script>

When i call this function ajax_login(s,u,p) by button click, function is working but control is not transferring to control.jsp

Getting result to ajax call as Object/undefined

I'm sending response from struts action with a message and I want to display it in JSP Page. But I'm getting result as Object and "result.fieldname" as "undefined"

struts.xml

 <action name="uploadSuccess" class="com.truepush.client.controller.UploadFileController">
  <result name="success" type="stream">
                <param name="contentType">text/html</param>
                <param name="inputName">inputStream</param>
            </result>
             <result name="error" type="stream">
                <param name="contentType">text/html</param>
                <param name="inputName">inputStream</param>
            </result>

Ajax:

function uploadFile(Blob) {
                $.ajax({
                    type: "GET",
                    url: "uploadSuccess",
                    dataType: "json",
                    data: "response=" + JSON.stringify(Blob),
                    success: function(result) {
                        console.log("success : ");
                        console.log(result.inputStream);
                        console.log(result);
                    },
                    error: function(result) {
                         alert(result[0].word);
                        console.log("error : " + result.inputStream);
                        console.log("error : " + result.inputStream);

                    }
                });
            }

I'm setting the value to inputStream in my class and I'am sure it is returning "success" (As i can see from debugging)

loading json data from local file into React JS

I have a React component and I want to load in my JSON data from a file. The console log currently doesn't work, even though I'm creating the variable data as a global

'use strict';

var React = require('react/addons');

// load in JSON data from file
var data;

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "data.json", true);
oReq.send();

function reqListener(e) {
    data = JSON.parse(this.responseText);
}
console.log(data);

// create component
var Accordion = React.createClass({      
  render: function(){
    return (
      <div>
          Accordion component          
      </div>
    );
  }
});

module.exports = Accordion;

Ideally, I would prefer to do it something like this, but it's not working - it tries to add ".js" onto the end of the filename.

var data = require('./data.json');

Any advice on the best way, preferably the "React" way, would be much appreciated!

ajax post data undefined

I'm using xampp-control to emulate a local server. I have a html file and i'm trying with ajax to post some data into a json file. I can get the data from the json, but when I'm trying to post doesn't work.

here is the html

<!doctype html>
<html class="no-js" lang="">
    <head>
        <script src="http://ift.tt/1LdO4RA"></script>
        <script src="js/main.js"></script>
    </head>

    <body>
        <h1> Family Perez</h1>
        <form>
            <label>Name</label><input type="input" id="name" name="name"></input>
            <label>Last Name</label><input type="input" id="lastName" name="lastName"></input>
            <input type="submit" id="submitBtn" value="Add family Member" name="submit"></input>

        </form>

        <div></div>
    </body>
</html>

and here is the js

$(function(){

  $('#submitBtn').click(function(e){
    e.preventDefault();
    var firtsName = $('#name').val();
    var lastName = $('#lastName').val();

    $.ajax({
      type: 'post',
      url:'http://localhost/angel/Jquery_advanced/ajax/family.json',
      dataType: 'json',
      async: false,
      data: {name: firtsName, last: lastName},
      success: function(newMember){
          alert(newMember.name + ' ' + newMember.last + ' ' + 'has benn added');
      },
      error: function (jqXHR, textStatus, errorThrown){
        console.log(jqXHR);
        console.log(textStatus);
        console.log(textStatus);
      }
    })

  });

  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: 'http://localhost/angel/Jquery_advanced/ajax/family.json',
    success: function(data) {
      $.each(data, function(i, member){
        $('div').append('<p>'+ member.name + ' ' + member.last +'</p>');
      })
    }
  });
});

the file http://localhost/angel/Jquery_advanced/ajax/family.json has:

[{"name":"Juliseth","last":"Hernandez"},{"name":"Angel","last":"Perez"}]

JSON return value to global variable

Simply my code looks like this:

 var thevariable = 0;

For(){
//somecode using thevariable
$.getJSON('',{},function(e){
//success and i want to set the returned value from php to my variable to use it in the forloop

thevariable = e.result;
});
}

my main problem that the variable value stays "0", during the whole For loop, while i only want it to be "0" at the first loop, then it takes the result returned from PHP to use it on for loop.

here it my real code if you need to take a look:

var orderinvoice = 0;
for(var i=0; i<table.rows.length; i++){
                            var ordername = table.rows[i].cells[5].innerText;
                            var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g,'')).replace(/Qty /g,'');
                            var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g,'');
                            var ordertype = table.rows[i].cells[3].innerText;
                            var orderlink = table.rows[i].cells[4].innerText;

      $.getJSON('orderprocess.php', {'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink}, function(e) {
          console.log();
          document.getElementById("result").innerText= document.getElementById("result").innerText + "Order #"+e.result+" Created Successfully ";
         document.getElementById("invoker").innerText = ""+e.invoice;
         orderinvoice = e.invoice;

          if(i+1 == table.rows.length){
            document.getElementById("result").innerText= document.getElementById("result").innerText + "With invoice #" + e.invoice;
          }
 });

Retrive the value from text input and updating/saving with ajax

I'm trying to make it work the code below but i dont know what's wrong with the meta values. I cant get the values from the input and the php is saving the variable. All i want is to update meta values by meta id (Wordpress) but i really dont understand what is wrong.

HTML

<input name="in_meta-5852-submit" id="in_meta-5852-submit" class="button updatemeta button-small buttons_span" value="Update">
<input name="in_meta[5852][value]" id="in_meta-5852-value" size="14" type="text" value=" enter numbers and letters ">

JS

    $('#in_meta-5852-submit').click(function(){
    var meta_id =  "5852";
    var values =   $('#in_meta-5852-value').val();
    var data = {

        action:             'my_action',
        post_id:            $('#post_ID').val(),
        meta_id:            meta_id,
        values:             values,
    };

    $.post(ajaxurl, data, function(response) {
        if( 0 == response ) {
        $( Saving failed);
        }
    });

PHP

add_action( 'wp_ajax_my_action', 'isave_meta' );
function isave_meta( $post ) {
$post_id = 'post';
$values = 'values';

if(isset($_POST) && isset($_POST['meta_id'])) 
{ 
update_metadata_by_mid( $post_id, absint( $_POST['meta_id'] ), $values, );
}
}

Decoding ajax returned obfuscated image

Myfonts.com offers an open API that generates screenshots like so: http://ift.tt/1IzYUCk

I am trying to use the generated png file using a standard jQuery ajax request like so:

  $.ajax({
    url:'http://ift.tt/1IzYUCk',
    dataType: "html",
    success: function (response) {
      console.log(response);
    }
  });

This is returning some super funky encoded png unicode like so �PNG IHDR*��}PLTE����������� <-- super abbreviated version

At first I tried appending the image as a data URI but that didn't work. Any idea what to do with this data to generate an image? Clicking on the link generates it.

Rails responding to different formats with AJAX request

I'm trying to understand AJAX requests in Rails. I have a form that I currently submit using remote: true. I want to respond with an HTML redirect if the request is successful, and run an error message with Javascript if it is unsuccessful. However, no matter what the outcome is, the request seems to expect a .html as the return.

respond_to do |format|
  if conversation
    format.html { redirect_to(conversation_path(conversation)) }
  else
    format.js
  end
end

This is called after I save the conversation call on AJAX. On a successful save, the path is correctly rendered. But on an unsuccessful save, it expects the .html and throws an error. How do I accept .js as a response? My goal is to just pop up an error if the call is unsuccessful

Edit: My form_fro:

            <%= form_for :conversation, url: :conversations, html: { class: "conversation-form" } do |f| %>

Depending selects in symfony2

I have two selects, where the user chooses the first product to carry, and I want you automatically in the second quantities of the product that can be loaded. Examples: If you choose dishes , it can lead to a 6, 12 or 24 dishes. However , if you choose glasses , it can take one of a 5 or a 10. I'm working on Symfony2 and have an entity called Categories , which has 1 field ' category ' , and a ratio of 1 to many with another entity having the amounts by which the products of that category ( of 6 , 12, 24 ) are sold . and then I have a relationship of one to many with the entity 'Products' where all the products in each category . I'm told you do with AJAX, but nevertheless not how. Someone can give me a hand?

JQuery.ajax does not wait for C# Server's response and calls error function, testing on localhost

On the user-side, I have a javascript code, that POSTs to the server via JQuery.ajax. On the server-side, I receive the request and handle it, but the user-side script does not wait for the servers response and calls error: getFail (see below) function.

How did I check if the user-side waits for the server or not?
I've just run the server in debug mode, and set a breakpoint where it receives the POST-ed values. And the user-side already called the error function.

  • Could anybody tell me, why it is not working "properly" or what and where is the source of error?

What I suspect to be one of the sources of the "improper" behavior is the dataType parameter of the JQuery.ajax function. It is supposed to specify the expected type of the return value from the server. I am not sure what to set this, so I did not specify hoping the default will find out.

[For the dataType parameter] If none is specified, jQuery will try to infer it based on the MIME type of the response. Possible types are: xml, html, script, json, jsonp, text, multiple. (Source: http://ift.tt/gmB8Sv, JQuery docs).


Here are the codes:

User-side javascript code:

function logIn() {
try {
    alert('try in logIn');
    jQuery.ajax({
        type: "POST",
        url: "http://localhost:8080/Token",
        cache: false,
        data: {
            "grant_type": "password",
            "username": document.getElementById("username").value,
            "password": document.getElementById("password").value
        },
        contentType: "application/x-www-form-urlencoded", // data type sent to server
        // dataType: "json", // data type expected from server <- THIS may be a source of the problem
        success: getSuccess,
        error: getFail
    });
} catch (e) {
    alert(e);
}
function getSuccess(data, textStatus, jqXHR) {
    alert(data.Response);
};
function getFail(jqXHR, textStatus, errorThrown) {
    //jqXHR.status is 0
    //textStatus is "error"
    //errorThrown is empty
    alert(jqXHR.status); // <-- THIS is what gets called, instantly after the post.
};

};

Server-side C# code:

public class ApplicationOAuthServerProvider
    : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(
        OAuthValidateClientAuthenticationContext context)
    {
        await Task.FromResult(context.Validated()); // break-point was here
    }

    // This is called by await Task.FromResult(context.Validated())
    public override async Task GrantResourceOwnerCredentials(
        OAuthGrantResourceOwnerCredentialsContext context)
    {
        // Here manager will have correct values from the POST-ed data
        var manager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        var user = await manager.FindAsync(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError(
                "invalid_grant", "The user name or password is incorrect.");
            context.Rejected();
            return;
        }

        foreach (var userClaim in user.Claims)
        {
            identity.AddClaim(new Claim(userClaim.ClaimType, userClaim.ClaimValue));
        }

        context.Validated(identity);
    }
}

Can't get 401 response body

I managed to get JSON content using jQuery.ajax(). Currently, it fetches the content from another host containing a single index.php file returning a 401 response with the following body: {'status':401}.

This is the JS:

$(document).ready(function() {
    $.ajax({
        url: 'http://restapi',
        type: 'GET',
        dataType: 'json',
        success: function() { document.write('works'); },
        error: function(xhr) { document.write('failed, status:' + xhr.status); },
        beforeSend: setHeader
    });
});

function setHeader(xhr) {
    xhr.setRequestHeader('Authorization', 'Bearer 12345');
}

And the PHP:

<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Headers: X-Requested-With, Authorization");

header("HTTP/1.1 401 Unauthorized");

echo json_encode(['status' => 401]);

exit;

If I remove the header, xhr.setRequestHeader('Authorization', 'Bearer 12345');, everything works fine (the response has a json body and xhr.status returns 401). But with the Authorization header the body returns nothing and xhr.status returns 0.

I need to send the auth token in that header.

Ajax call to local .py script works fine until I add a simple import at the top, upon which it fails with a 500 error

This is all happening on the Django platform. Here is my ajax call:

$.ajax({
        type: 'GET',
        url: 'get-dropdown-contents', //a url mapping to controller_ajax.py
        dataType:'json',
        data: {'selection_path': selectionPath},
        success: function (data) {
               //blah blah blah.... it doesn't reach here

Here is the .py script that is called:

from hs_restclient import HydroShare, HydroShareAuthBasic
from django.http import JsonResponse
from functions import irods_query


def get_dropdown_contents(request):
    print "Entered"
    if request.method == 'GET':
        selection_path = request.GET['selection_path']
        irods_data = irods_query(selection_path)
        return JsonResponse({
                                'success': "Response successfully returned!",
                                'irods_data': irods_data
                            })


def upload_to_hydroshare(request):
    if request.method == 'GET':
        hydro_username = request.GET['hydro_username']
        hydro_password = request.GET['hydro_password']
        try:
            print hydro_password
            print hydro_username
            hs = HydroShare(auth=HydroShareAuthBasic(username='joe', password='shmoe'))
        except Exception, err:
            print "Err: " + str(err)
            return JsonResponse({'error': 'Username or password invalid'})
        return JsonResponse({'success': 'Response successfully returned!'})

The ajax call, which calls the get_dropdown_contents() function worked perfectly fine. However, with the simple addition of the from hs_resclient import... statement, the ajax call now fails with a 500 internal server error. If I comment out that one statement, the call works without a problem. I cannot figure out why for the life of me.

Any ideas?

Ajax copy text from one textarea to another via post

I am trying to use ajax to post the text from one text area to a php page to echo back into another textarea. When I do this it works for about 5 characters and then stops completely. I've tried with and without encoding doesn't seem to make a difference since I'm just trying simple plan text like "ddddddddddd".

in example.html

<!DOCTYPE html>
<html>
<body>
<style>
.center{
margin: 0 auto;
margin-left: auto;
margin-right: auto;
text-align:center;
}

</style>

<div class="center">

<textarea   onkeyup="changed()" onkeydown="changed()" onkeypress="changed()"  id="b1" rows="30" cols="81">
</textarea>

<textarea id="b2" rows="30" cols="81">
</textarea>

</div>

</body>
</html>
<script>
function changed(){

var text =document.getElementById("b1").value;

if(!text){
text ="";
}

     var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {

                document.getElementById('b2').value =xhr.responseText;

        }
    }

    xhr.open('POST', 'echo.php');
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("text=" + text);



}

</script>

In echo.php

<?php 
 $mytext = $_POST["text"];
 echo $mytext;

?>

I've looked at several similar posts but none of them fix my issue. I'm not using a form. Do I have to? Textarea not POSTing with form

rails 4 refresh only specific div with ajax

this is my second question on stackoverfloy. If i did a mistake, i'm sorry, i'm really new to here. So please be gentle.

I just learned RoR and i want to build a rails app for my GF's birthday. I have 2 models and 2 controllers. One of for image and the other one for the text.

I did randomize they in my images controller's index function to show in index.html And placed a button for refreshing the page so image and text randomize again.

But i want to add background music to this. So i need to use ajax for button to keep music from restarting over again. I did a research and tried many solutions. But i cant succeed.

Here is my controller:

class ImagesController < ApplicationController


    def index
      @randimg = Image.order("RANDOM()").first
      @randtext = Text.order("RANDOM()").first

      respond_to do |format|
        format.js 
        format.html
      end

Here is my images index.html.erb:

<!DOCTYPE html>
<html lang="tr">
<head>
  <title>2 Ağustos 1993</title>
  <meta charset="utf-8">
  <link href='http://ift.tt/1nio39n' rel='stylesheet' type='text/css'>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <%= javascript_include_tag "application" %>
</head>

<body>
  <div class="container">
    <%= render 'text' %>
    <%= render 'image' %>
  </div>
  <center>
    <%= link_to "İyi ki doğdun bebeğim, seni çok seviyorum",
              {:controller => 'images', :action => 'index'},
              :remote => true,
              class:'btn btn-info' %>
  </center>

  <audio autoplay="true" loop="true" preload="">
 <source src="bg.mp3" type="audio/mpeg"></source>
 Your browser does not support the audio element.
</audio>
</body>
</html>

And as far as i know i need to specify index.js.erb to use ajax, here it is;

$("#container").html("<%= j render :partial => 'image' %>")

I know my app is not the best or cleanest. This is my first app on rails. Thanks in advance.

PS: English is not my native language, i'm sorry if i type something mistaken.

Ajax call to REST service returns status:0

Ajax call from cordova android application to the REST service, returns

{ "readyState" : 0, "responseText" : "", "statusText" : "error" }

I've added <access origin="*" /> to the config.xml

    $.ajax({        
        type: "POST",    
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(dataObject),
        url: "http://ift.tt/1KGirAu",
        success: function(result){            
            if(result.auth){ 
                window.localStorage["authentication"] = result.authCode;
                window.localStorage["authDetails"] = result.details;                                    
                $.mobile.changePage("#home");    
            }                
            else{
                navigator.notification.alert('Login failed. Try again.', function() {});                        
            }
        },
        error: function(err){
            navigator.notification.alert('Error occurred unexpectedly.' + JSON.stringify(err) , function() {});
        }    
    });

The service is running in the localhost. I'm using GenyMotion as the Emulator.

Spring Security AJAX / JSON Login Issues

I am trying to implement Spring Security with the login form being submitted via Ajax. I have created my own custom authenticationFailureHandler and my own custom authenticationSuccessHandler. I'm not sure if my issue lies in my Spring / Java code or on my client side code. I've also seen the cross site scripting protection could be causing the issue. When I login it does authenticate fine, but i actually get a new HTML page with my JSON on it but the content type is html/text.

enter image description here

When the login is unsuccessful I get the same thing.

enter image description here

The Request and Response Headers do not look right to me. First there are no response headers, and secondly the request headers does not have X-Requested-With.

enter image description here

Some items to note

  1. I am using Spring Boot 1.2.5
  2. I have CSRF enabled in Spring Security, it is a requirement from client
  3. There cannot be a login page, the login must be in the top right of the top navigation / header, hence why I am submitted the from via JS/Ajax

This is what the login form will look like:

enter image description here

Here are my custom handlers

@Component
public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {

        userMapper.incrementFailedLogin(request.getParameter("sec-user"));

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().print("{\"success\": false}");
        response.getWriter().flush();
    }
}

-

@Component
public class AuthSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws ServletException, IOException {

        userMapper.updateUserOnAuthSuccess(request.getParameter("sec-user"));

        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().print("{\"success\": true}");
        response.getWriter().flush();
    }
}

My Spring Security config

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    AuthFailureHandler authFailureHandler;

    @Autowired
    AuthSuccessHandler authSuccessHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/", "/about","/public/**").permitAll()
                    .anyRequest().fullyAuthenticated()
                    .and()
                .formLogin()
                    .usernameParameter("sec-user")
                    .passwordParameter("sec-password")
                    .failureHandler(authFailureHandler)
                    .successHandler(authSuccessHandler)
                    .permitAll()
                    .and()
                .logout()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/")
                    .deleteCookies("remember-me", "JSESSIONID")
                    .permitAll()
                    .and()
                .rememberMe();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(new BCryptPasswordEncoder());
    }
}

Login Form (Thymeleaf)- embedded in navigation menu

<div th:fragment="login">
        <form th:action="@{/login}" method="post" accept-charset="UTF-8" class="login-pane" id="login-form">
            <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
            <div class="form-group">
                <label for="sec-user">Email</label>
                <input type="email" class="form-control" id="sec-user" name="sec-user" placeholder="Email" />
            </div>
            <div class="form-group">
                <label for="sec-password">Password</label>
                <input type="password" class="form-control" id="sec-password" name="sec-password" placeholder="Password" />
            </div>
            <button type="login-btn" class="btn btn-danger">Login</button>
        </form>
    </div>

And last but not least my javascript code

$(document).ready(function() {

    $("#login-btn").click(login)

});

function login() {

    console.info("Attempting to authenticate");

    $.ajax({
        type: 'POST',
        url: '/login',
        data: $('#login-form').serialize(),
        cache: false,
        dataType: "json",
        crossDomain: false,
        success: function (data) {
            var response = jQuery.parseJSON(data);
            if (response.success == true) {
                console.info("Authentication Success!");
                window.location.href("/");
            }
            else {
                console.error("Unable to login");
            }
        },
        error: function (data) {
            console.error("Login failure");
        }
    });
}

Get AJAX Request and Looping Through JSON

I am using a GET ajax request to retrieve some JSON data from the database. I want to loop through it and print certain items. For example, I want to print all the address in stylist_1 only. The problem is that it only prints the last item.

Here's what the code looks like:

var stylist1Addresses;

    function getData() {
        $.ajax({
            url: '/getData',
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            success: function (data) {
                for (var i = 0; i < data.stylist_1.length; i++) {
                    stylist1Addresses = data.stylist_1[i];
                }
            }
        });
        console.log(stylist1Addresses);
    }

Sample data:

{
  "stylist_1": [
    {
      "Address": "1 Stn Main", 
      "Phone": "403-990-9033"
    }, 
    {
      "Address": "474 Cirrus Rd", 
      "Phone": "403-995-3243"
    }, 
    {
      "Address": "1591 Stn St", 
      "Phone": "403-982-8893"
    }
  ], 
  "stylist_2": [
    {
      "Address": "219 Welch Blvd", 
      "Phone": "587-436-3171"
    }, 
    {
      "Address": "374 Main Rd", 
      "Phone": "587-315-9431"
    }, 
    {
      "Address": "564 Main Rd", 
      "Phone": "403-938-9983"
    }
  ]
}

jquery mobile 1.4.5 single-page template href querystring ajax

I am a newbie to JQM (I use 1.4.5) and my webapp (asp.net C# apache Cordova) contains many separate pages of .cshtml (single-page template) only. I am testing my webapp on a Samsung Galaxy Grand using Android 4.2.2

A. I am not sure about my understanding of 'linking pages', even after reading all the JQM docs on this and also after reading up many, many posts on this topic about passing querystring values to another page; mainly because I find that ALMOST ALL the examples are directed towards providing answers for internal pages (Multi-Page template) within a single html page.

So I request some of you JQM experts to confirm or correct the following understanding of mine....

From the JQM docs I understood that

  1. I could use in any link (e.g button), href="page2.cshtml?par1=1&par2=2"; and JQM will automatically use Ajax for this link to work.

  2. I also understood that use of querystring is always allowed in such cases of different html pages of the same domain and it will work via Ajax automatically ; so long as the attr such as rel="external", data-ajax="false" etc. are not used in the same link.

  3. but querystrings are not allowed in case of the internal pages (multi-page template) only....;

  4. and if I need to use the above href to link to a page in another domain e.g. http://ift.tt/1OET0Qv, then I need to use rel="external".

Are all my above points (that reflect my understanding) CORRECT? KIndly confirm ro please correct me ...

B. In my app, I find that most of the links work according to my understanding as above, to connect to different pages in the same domain; and I assume it happens via Ajax. Is it correct? I am also able to use the querystring params in page2 ( i.e. To-Page).

  1. But in one case, though it works, in the To-Page the Panel features do not operate correctly, unless I introduce rel="external' in the href link !!! I suppose it means it IS NOT AJAX anymore? Also I am unable to find the reason..

  2. Further independent of the above topic, I face another issue. The loading time (i.e. Time taken to display the To-Page) varies.

Mostly it is OK, but at times the loading-circle goes on forever.... and I presume it has crashed....??? then If I go back using the back button and come forward again, many times it loads immediately...!!!!! Any thoughts or suggestions.....?

Thanks in anticipation... Ratna

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?

Django and SimpleUploadedFile

My form contains imagefield but the values of this form are recuperated by a method ajax...

The probleme is when ajax recuperated value of imagefield, this value is just a name of the image and not imagefield, So I can't save the image entered by user in my form...

How can I do ?

I make this, my method ajax send to my view the name of image ("tree.jpeg") entered by user. I try this in my view :

    from django.core.files.uploadedfile import SimpleUploadedFile
        file_contents = SimpleUploadedFile("%s" %(imagename), request.body)
        llog = ModelContainsImageField()
        llog.image.save(imagename, file_contents, True)
        llog.save()
        projet.log = llog

It don't works :/

500 Internal Server Error on AJAX Call ONLY on GoDaddy Plesk Server

I have a chat application that utilizes jQuery's AJAX method. The program works just fine on my local Apache (MAMP) server, but the same exact code is not posting the messages on my remote server. On my GoDaddy (Plesk/ASP.NET) site, I'm receiving the 500 internal server error on my xhr POST (post.php) request.

[post.php]

session_start();
if (isset($_SESSION['name'])) {
    $text = $_POST['text'];

    $fp = fopen("log.html", 'a');
    fwrite($fp, "<div class='msgln'>(".date("g:i A").") <b>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
    fclose($fp);
}

Do you guys have any idea what might be causing this? Thank you so much!!

Putting an ajax call results into a variable that can be manipulated as a div

I'm making an ajax call and get results back.

  $.get('/page.html',function(data){

      var myData = data;

    });

Is there a way that i can store the results in a variable and then manipulate that variable as if it was a container? If i make a change, something like this:

$('#myData ul').remove()

Now the myData variable still has the information but now with the ul removed?

MVC: Send parameters to method by a button

I have the following button in a View

    <button id="Export" class="btn btn-default custom" type="button">
          <i class="glyphicon glyphicon-file"></i>Export to Excel
    </button>

And I want it to export a list of materials that I have in a ViewData

I already have the logic. The code could be in a ActionResult or a normal method and it would be something like this:

    [HttpPost]
    public void Export(List<int> listPassed)
    {
           //stuff here
    }

I tried adding href="@Url.Action("Export", "Materials", new { export_documentation = true })" but it didn't work out.

I could do it with an override of the ActionLink method but I would lose the glyphicon. Thing that I want to avoid. Overrides of the ActionLink that tricks the helper to have a glyphicon also didn't work out.

I tried Ajax but I suck at jscript and ajax and all that stuff at the moment.

So, how can send the parameters to the method?

Jquery FormData limitation

Using FormData and jquery i am sending a lot of inputs using ajax but not all of them are coming trough.

If i look in developer tools (Chrome) i am seeing something like:

1
------WebKitFormBoundaryGBYjXeMfAVtlYyAq
Content-Disposition: form-data; name="position[660]"

15
------WebKitFormBoundaryGBYjXeMfAVtlYyAq--

So clearly the data is cut off.

Is there a limitation in the amount of data i can use with formdata and ajax?

The form works great with a small number of inputs, but with about 800 inputs it doesn't.

Thanks

Jquery Ajax call to java rest api success function is not firing

I am trying to send HTML form data as a JSON to java rest api and it generates response as JSON. Here is my code.

HTML FORM:

<html>
<body>
<form action ="" method= "post" name= "testform">
    <p> Balance : <input type="text" id="balance" name="balance" /></p>
    <p>Pin : <input type="text" id="pin" name="pin" /></p>
    <p>CardID : <input type="text"  id="cardId" name="cardId" /></p>
    <input type ="submit" id="add-account" value="add user"></input>
</form>
<script src="http://ift.tt/1yCEpkO"></script>
<script src="js/main.js"></script>
</body>
</html>

Jquery CODE:

$(function(){
console.log("Jquery called");
$('#add-account').click(function(){
    var balance = $("#balance").val();
    var pin = $("#pin").val();
    var cardId = $("#cardId").val();
    var firstcall = 
    $.ajax({
        type: "POST",
        url: "http://localhost:8081/quickpay/webapi/myresource",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({
            "balance":balance,
            "pin": pin,
            "cardId": cardId
        }), 
        dataType: "json",
        success:function (successResponse,textStatus,jqXHR) {
            alert("first api");         
        },
        error: function (errorResponse1) {
            console.log(errorResponse1);
            alert("failed first api");
        }
    });
});
});

JAVA REST API:

@Path("myresource")
public class MyResource {
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Account createAccount(Account acc){
        Account account =  AccountService.createAccount(acc.getBalance(),acc.getPin(),acc.getCardId());
        return account;
    }
}

OUTPUT I'm getting is:

When I try to call the api in POSTMAN, it runs successfully and data is inserted successfully. When I try to click on ADD USER button , data is inserted into database successfully but ALERT messege of success function does not appear.

I'm monitoring network tab of Google chrome, There I find this error in myresource status is cancelled and type is xhr.

When hovering mouse on Jquery.min.js I get this..

n.ajaxTransport.k.cors.a.crossDomain.send @ jquery.min.js:4

n.extend.ajax @ jquery.min.js:4

(anonymous function) @ main.js:9

n.event.dispatch @ jquery.min.js:3

n.event.add.r.handle @ jquery.min.js:3

Problem : How can I make success function of ajax call working ?? Where I'm going wrong.?

Manipulating data from an ajax call before putting results in div

I'm calling a page and my returned results is the data of that page (duh). Here's what it looks like:

$.get('/myPage.html',function(data){

$('#results').html(data);

});

What i need to do is remove an element from that returned data. After I do that, i need to extract just the contents of the . Once that's complete, i want to put the results into a variable. The only way I know of to do this is have a container, #results, and send the data there. Once my data is there, then i could remove/extract. Is there a way for me to do this without first putting it into the #results?

Thanks for your help in advance!

Replace javascript ajax with jquery ajax

I am currently using Javascript + AJAX to request and return the data from a CKeditor instance to a PDF renderer. I need to change this to JQuery + AJAX. I am working in a GSP in Grails 2.4.3.

Here's my working Javascript:

function getCK(){
    return CKEDITOR.instances.thisInstance.getData();
}

function upDate(){

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "https://someURL/app/someController/someAction", false);
    xhr.onreadystatechange = function () {
        if (xhr.status === 200 && xhr.readyState === 4) {

            document.getElementById("pdf").setAttribute("data", xhr.responseText);

        }
    };
    xhr.send(getCK());
}
upDate();

The code above works, but my employer wants JQuery.

Here's what I have so far that doesn't work:

function upDate(){

    $.ajax('${createLink(controller:'someController', action:'someAction')}',{
        type:'POST',
        data: CKEDITOR.instances.thisInstance.getData();
        },
        success: function (data) {
            $('#pdf').attr('data', data);
        },
        error: function(jqXHR, textStatus){ alert(jqXHR.responseText);}
    });
}
upDate();

Not sure why this isn't working, this exact code works throughout our gigantic application numerous times.

Thanks in advance!

How Crop image with fengyuanchen/cropper and save in database the path of image crop?

I'm trying to upload an image to a temporary folder for editing (crop) image and create an avatar with the selected, but not working.

The button load should charge the image, once loaded should be displayed in: but it does not. I'm doing wrong.

Note: if the image is static, if it works. but I need upload with button for make dinamic.

from there, I intent generate a preview of the selection of the image with cropper. for see the result end of selected

after I get the values of the cropper intent create a new json format, to send and save the data in the database.

but I do not get !. someone can guide me!.

I have not worked with these technologies, so it is, I not understand how upload. and save in database the path and the image crop!.

Note: the image crop, will be stored in a folder, the original is not stored, it is only necessary to crop!.

thanks for your suggestions!.

this is the plugin: http://ift.tt/YTzyuY

that, better than pediar helps people experienced in these technologies, Thank you for your help !.

This is my code!. ------ Perhaps this bad my code, so I need, that guide me, or show me, how to do or should do. thanks ----------


Start the code!

<!DOCTYPE html>
<html>
<head>
 <title>TEST DEMO UPLOAD</title>
    <script src="jquery/jquery-2.1.4.min.js"></script><!-- jQuery is required -->
        <link  href="css/cropper.min.css" rel="stylesheet">
        <link  href="css/cropper.css" rel="stylesheet">
         <link  href="css/cropper.css" rel="stylesheet">
    <script src="javascript/cropper.min.js"></script>
    <style>
      .img-container img {
            width: 400px;
            height: 500px;
        }
    </style>
</head>
<body>
    <div class="columns">
        <div class="img-container">
        <img id="My_Image" alt="Picture Uploaded, To Crop" class="cropper" src="#">
        </div>
        <div class="columns">
            <div class="previews ">
                <div class="img-preview preview-lg">
                </div>
            </div>
        </div>

        the cropper JQuery info: http://ift.tt/YTzyuY 
    <p>Example Upload and Crop with Cropper JQuery Plugins And Previews </p>
    <form id="form" action="Demomode.php" method="post" enctype="multipart/form-data">
        <lobel>Select image a Upload:</lobel>
            <input type="file" id="Upload" name="Up" >
            <input type="submit" value="Upload Image" name="submit">
    </form>
    <div>
        <label id="image-data"></label>
    </div>
<body>
</html>
    <script>

    // make references to file to charge in temp folder for edit with cropper    
    $('#Upload').click(function (){
          var cp = $('#My_Image > img').cropper({
          preview: ".img-preview", // A jQuery selector string, add extra elements to show preview.
          aspectRatio:4/4,
          strict:true,
          background:false,
          guides:false,
          autoCropArea:0.6,
          rotatable:false,
          crop: function(data){

          //create the preview of image original
                $('.img-preview').cropper({
                  preview: ".img-preview",
                  aspectRatio:1/1,
                  strict:true,
                  });

              //get data of part crop and send in format json for send to database
              if(data.height < 100 || data.width < 100){
              }else{
                  var json = [
                      '{"x":' + data.x,
                      '"y":' + data.y,
                      '"height":' + data.height,
                      '"width":' + data.width + '}'
                  ].join();
                  $().val(json);
              }

              // Send data of the image crop for save in database
                       $.ajax({
                        type:'POST',
                        url: $(this).attr('action'),
                        data:json,
                        cache:false,
                        contentType: false,
                        processData: false,
                        success:function(data){
                            console.log("success");
                            console.log(data);
                        },
                        error: function(data){
                            console.log("error");
                            console.log(data);
                        }
                        });

          }
        });
    </script>

DataTables Javascript AJAX with plain data arrray

I have an ajax call that returns:

[{"fields": 
    {"account_to": ["Bank Account - SECU", "11000"],
     "posted_by": 1, 
     "amount": "1000", 
     "created_date": "2015-07-31T14:53:03.766Z", 
     "posting_date": "2015-07-31T14:53:03.763Z", 
     "account_from": ["Consulting Income - ABC", "41000"], 
     "company": "S&S Co"},

     "model": "base.glentry", "pk": 8},
  {"fields": ...
]

Note that there is no: {'data': [ data array ]} which all the examples have. I can find how to change the name so that 'data' can be something else, but how do I make it render like this with AJAX without manually processing the return value wrap the data?

Here is my javascript:

$('#dt').dataTable( {
    "processing": true,
    "ajax": "http://localhost:8000/gl/",
"columns": [
    {"": "fields.amount"}
]
} );

I've tried all sorts of things, but get the same result. What can I do?