Ajax template function Ask Question

            $.ajax({
                type: "POST",
                url: "<?php echo base_url('profile/update_user_password'); ?>",
                cache: false,
                data: $('#form_changepassword').serialize(),
                dataType: "json",
                beforeSend: function () {
                    $('#btn_updatepassword').addClass('disabled');
                    $('#btn_updatepassword').attr('disabled', true);
                    $('#btn_updatepassword').html("<i class='fa fa-spinner fast-spin'></i>");
                },
                complete: function () {
                    $('#btn_updatepassword').removeClass('disabled');
                    $('#btn_updatepassword').attr('disabled', false);
                    $('#btn_updatepassword').html(' <?php echo lang('update_password_button_text') ?>');
                },
                success: function (response) {

                }
            });

This above is a function of ajax.
I want to make a function that take beforesend as a parameter
like below

function myAjax(ajax_url, ajaxcallback , dataType = "json" , cache = false , reqtype = "POST" , data = "" , errorId = "" ) {
    type: reqtype,
    url: ajax_url,
    cache: cache,
    data : data,
    dataType: dataType,
    success:ajaxcallback ,

}

I want to call this function with before function as a parameter in function

myAjax("url " , clouse_fun_for_success, "" , false , "POST" , data , "#error" )

How can I set some setting before call this AJAX template function because every time login in before function would be change

how can I do a post with thymeleaf with spring 4 mvc from a table? Ask Question

I have a DataTable on my page reg_clientes.html

<tr  th:each="listado : ${lista}">
     <td th:text="${listado.id}">1</td>
     <td th:text="${listado.ci}">1</td>
     <td th:text="${listado.division}">1</td>
     <td th:text="${listado.nombre}">1</td>
     <td th:text="${listado.apellido}">1</td>
     <td th:text="${listado.direccion}">1</td>
     <td th:text="${listado.email}">1</td>
     <td th:text="${listado.telefono}">1</td>
     <td>
           <form method="POST" id="formdelete" >
            <input type="submit" name="submit" value="borrar" class="link-button" th:onclick="'eliminar('' + ${listado.id} + '');'"/>
            </form>
    </td>
                     </tr>

`

delete_ = function(id) {
$.ajax({
    url : 'delete',
    type : 'POST',
    data : {
        id : id
    },
    success : function(response) {
        alert(response.message);

        location.reload();
    }
});

}

function eliminar(id) {
    var statusConfirm = confirm("Realmente desea eliminar esto?");
    if (statusConfirm == true) {
        delete_(id);
    } else {
        load();
    }



return statusConfirm;

ClienteController.java

@RequestMapping("/clientes/reg_clientes")
public String contacts(Model model) {
    model.addAttribute("lista",clienteservice.list());
    return "abm/clientes/reg_clientes";
}

@RequestMapping(value = "/delete", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> delete(Long id) {
    Map<String, Object> map = new HashMap<String, Object>();

    if (clienteservice.delete(id)) {
        map.put("status", "200");
        map.put("message", "Registro eliminado exitosamente");
    }

    return map;
}

but it does not work, it gives the POST error 404 (NOT FOUND) clientes / reg_clients / delete … when I press the delete button of the table

Can I help me?

How to load vector map again onchanging dropdown menu? Ask Question

HTML:

<form>
    <select id="mySelect" onchange="getMap()">
      <option value="SI">Slovenia</option>
      <option value="SR">Serbia</option>
    </select>
</form>

<div id="map_vector">

Script to load map

<script>
  $(document).ready(function () {
    getMap();
  });

  function getMap() {
    var focus = document.getElementById("mySelect").value;
    var map = new jvm.Map({
      container: $('#map_vector'),    
      map: 'europe_mill',   
      focusOn: [focus]
    });
  }

</script>

I want to on change select menu to change focus and that’s why I call function getMap() again onChange event , but map is not load again. I know I missing something big but I am not familiar with JS.

JS XMLHttpRequest wrong result Ask Question

i have begin learning JavaScript from w3schools and i’ve stucked on sending GET request – i get wrong status code (0) and no content.
maybe my code in mvc is wrong:

  [ProducesResponseType(typeof(Insider.Dto.CustomerDto),200)]
        [HttpGet]
        public HttpResponseMessage Get()
        {
            var response = service.GetCustomers();
            var result = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json");
            return new HttpResponseMessage(System.Net.HttpStatusCode.OK)
            {
                Content = result,
            };

        }

It works, when i debug it in VS i get right dto’s, but when i try to display it by js, i get only ‘0’ (its status code), other properties are null

<script>
    function GetData()
    {
        var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4) {
     document.getElementById("demo").innerHTML = this.responseText + this.status + this.responseXML
     var response = this.responseText;
    }
  };
  xhttp.open("GET", "http://localhost:3784/api/customers", true);
  xhttp.send();
    }
</script>

<button onclick="GetData()">Get data</button>
<p id="demo">data...</p>

i susspose that something is wrong with returning result on my mvc application, but what am i doing wrong 🙁 ?

Is there an ASP.NET Boilerplate Way of getting JSON data? Ask Question

I am currently trying this, but I keep seeing the dreaded error:

Unexpected token o in JSON at position 1

enter image description here

I am struggling to find a solution and was wondering if anyone has any tips on how to solve this?

The class being serialized to JSON:

[Serializable]
public class GeoCoordinate
{
    public GeoCoordinate()
    {
    }

    [JsonProperty(PropertyName = "lat")]
    public double Latitude { get; }

    [JsonProperty(PropertyName = "long")]
    public double Longitude { get; }

    public GeoCoordinate(double latitude, double longitude)
    {
        Latitude = latitude;
        Longitude = longitude;
    }

    public override string ToString()
    {
        return string.Format("{0},{1}", Latitude, Longitude);
    }
}

Ajax call:

function getLocationData() {
    jQuery.ajax({
        url: abp.appPath + "Home/GetLocationsAsync",
        type: "GET",
        dataType: "json",
        async: true,
        success: function (data) {
            var myArray = jQuery.parseJSON(data);
            locations = [];
            $.each(myArray, function (index, element) {
                locations.push([element.lat, element.long]);
            });
        }
    });
}

Controller:

[HttpGet]
public async Task<JsonResult> GetLocationsAsync()
{
    var cords = await _practiceAppService.GetAllGeoCoordinates();
    return Json(cords);
}

AppService:

public async Task<IList<GeoCoordinate>> GetAllGeoCoordinates()
{
    var geoCoordinates = await Repository.GetAll()
        .Where(x => !x.Disabled && !x.Latitude.Equals(0) && !x.Longitude.Equals(0))
        .Select(x => new GeoCoordinate(x.Latitude, x.Longitude))
        .ToListAsync();

    return geoCoordinates;
}

Console.log of data before attempted call to parseJSON:

console.log(data);
var myArray = jQuery.parseJSON(data);

enter image description here

Add button with dynamic data attributes that matches row information Ask Question

function getItems() {
  let name = inputVal.value;
  console.log(name);
  clearTable();
  $.ajax({
    type: "GET",
    url: "../php/includes/search.php",
    dataType: "json",
    data: { "name": name },
    success: function (data, status) {
      if (data == false) {
        clearTable();
      } else {
        for (let i = 0; i < data.length; i++) {
          createRow(i, data[i].name, data[i].Item_Id);
        }

        if ($('td').hasClass('cell4')) {
          $('.cell4').append('<button class="btn-addToCart btn btn-success btn-rounded btn-sm my-0 my-cart-btn font-weight-bold" data-summary="test" data-quantity="1"><i class="fas fa-shopping-cart fa-lg align-middle mr-1"></i>Add to cart</button>');
        }
      }
    },
    complete: function (data, status) {
      console.log(status);
    }
  });
}

function createRow(id, name, Item_Id) {
  let row = table.insertRow(id);

  let cell1 = row.insertCell(0);
  let cell2 = row.insertCell(1);
  let cell3 = row.insertCell(2);
  let cell4 = row.insertCell(3);

  cell1.appendChild(document.createTextNode(id));
  cell2.appendChild(document.createTextNode(name));
  cell3.appendChild(document.createTextNode(Item_Id));
  $(cell2).addClass('cell1');
  $(cell2).addClass('cell2');
  $(cell3).addClass('cell3');
  $(cell4).addClass('cell4 text-center');
}

This code works so far, but now I want to add data attributes to the button so it matches the row it’s placed on.

I’m thinking something like this when it comes to adding the values:

$('.btn-addToCart').attr("data-id", Item_Id);
$('.btn-addToCart').attr("data-name", name);

But how can I do that dynamically so it can loop through every row and match the rows info in cell2 and cell3 and then create a button that’s connected to that row? Hope you understand what I mean.

Updating html table with new php variable Ask Question

I am trying to refresh my table when the user clicks the button. This is because when the user clicks the button that row will be moved to the next table. (Not in this code example to make it simpler). How the tables are created are with the php code which executes in index code.php. Indexcode.php creates the variable $waiting which is then fetched in index.php and used to populate the table. When the button is clicked a request is sent to indexcode.php which updates the mysql tables. This is why I want to refresh the tables to display the new updated information. I have tried quite a few ways but to no avail.

index.php

<html>
<style>

<?php include 'table.css'; ?>
</style>
<?php include 'indexcode.php'; ?>


<script src="js/jquery.js"></script>
<script>
function orderPacked(val) {

$.ajax({
       type: "POST",
       url: 'indexcode.php',
       data: "packed=" + val,
       success: function(){
       var container = document.getElementById("yourDiv");
       var content = container.innerHTML;
       container.innerHTML= content;
       }
       });

}

</script>
<h1> <center> Warehouse </center></h1>
<p><center>This is for warehouse use</center></p>
<body>

<h2 class="text-waiting">These orders need to be packed</h2>
<body>

<table id="wtable" class="waiting-table" cellpadding="11"><tr>.   
<th>Order ID</th><th>Customer</th><th>Vendor</th><th>Address</th>.   
<th>Cart_ID</th><th>Cart</th><th>Checked</th></tr>

<?php while($row = mysqli_fetch_row($waiting)){
?>
<tr>
<?php
echo '<td>',$row[0],'</td>';
echo '<td>',$row[1],'</td>';
echo '<td>',$row[3],'</td>';
echo '<td>',$row[7],'</td>';
echo '<td>',$row[2],'</td>';
echo '<td>',"items",'</td>';
?>
<td>
<button onclick="orderPacked('<?php echo $row[0]; ?>')" id="button"     
name="packed" >Packed</button>
</td>
</tr>
<?php } ?>

</table>

</body>
</html>

indexcode.php

...
$stmt = $conn->prepare("SELECT * FROM sale WHERE wh_state =     
'waiting'");

$stmt->execute();

$waiting = $stmt->get_result();


$stmt = $conn->prepare("SELECT * FROM sale WHERE wh_state = 'packed'");

$stmt->execute();

$packed = $stmt->get_result();
$stmt->close();
// define variables and set to empty values
$orderErr = "";
$order = "";

    if (empty($_POST["packed"])) {

                 $orderErr = "Error";
       else {

        $orderp = test_input($_POST["packed"]);

        // update the state of the sale
        $stmt = $conn->prepare("UPDATE sale SET wh_state = 'packed' WHERE id = '{$orderp}'");
        $stmt->execute();

        $waiting = $stmt->get_result();

        $stmt->close();

    }       

   }
...

Checkbox change won't fire form submit via AJAX Ask Question

I’m trying to build a webpage where you can search for specific media in a database. You have multiple checkboxes to filter data. The backend query is working fine.

The problem is that none of the checkboxes will submit the form via Ajax.
The alert(“test”) gets displayed. If I submit the form manually via the submitbutton the form is submitted and the data is shown.

HTML:

<form id = "extended_search_form" method = "post" action = "extended_search.cfm">
    <div id = "datatype_filter">
        <ul class = "selectbox">
            <li id = "datatype_filter_select">
                Bitte einen Dateityp wählen             
                <ul class = "checkboxes">
                <!--- checkboxes getting loaded on datatype_filter click --->
                <!--- example checkbox --->
                   <li>
                      <label><input name="datatype_filter_checkboxes" value="1" type="checkbox"> Fotograph</label>
                   </li>
                </ul>
            </li>
        </ul>
    </div>
    <input type = "submit" value = "Submit">
</form>

Javascript:

$("#datatype_filter").on("change","input[name=datatype_filter_checkboxes]", function() {
    alert("test");
    $("#extended_search_form").unbind("submit").submit(function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        console.log(formData);
        $.ajax({
            url: "test.cfc?method=testSearch",
            type: "post",
            dataType: "json",
            data: formData,
            contentType: false,
            processData: false,
            error: function(event,jqhxr,ajaxSettings,error) {
                console.log(error);
            }
        }).done(function(result) {
            alert("Success");
        });
    });
});

What am I missing, that the form wont be submitted on the checkbox change event?

How to reference deserialized object properties received from javascript in C# generic handler? Ask Question

I have a JavaScript script that makes a jQuery AJAX call, and passes a serialized javascript object in the “data” property:

data: { Specific: JSON.stringify({DAY: “1”, DEP: “2”, CARRIER: “3”,
FLT: “4”, LEGCD: “5”})

It is received in a C# Generic Handler thusly:

var Specific = JsonConvert.DeserializeObject(context.Request.Params["Specific"]);

In the Generic Handler, within Visual Studio debugger, I can see the received object.

Specific = {{ “DAY”: “”, “DEP”: “”, “CARRIER”: “”, “FLT”: “”,
“LEGCD”: “” }}

My question is, how do I reference the received object’s properties (DAY, DEP, FLT, etc)?

I tried Specific.DAY, and Specific["DAY"], with no success.

Pass data to front end without timer Ask Question

am creating a blogging project. i want everytime a new post is created, the user doesnt have to refresh the page to see the post, it will just append to the already existing ones. this is what am doing presently

function postTin() {
$.ajax({
    type:'POST',
    url: "frextra.php",
    data:"ins=passPost",
    success: (function (result) {
        $("#post").html(result);
    })
})
}

postTin(); // To output when the page loads
setInterval(postTin, (5 * 1000)); // x * 1000 to get it in seconds

what am doing here is that every 5 seconds the page goes to reload the posted data in which case it will also add the newly posted ones

what i want is this:
i don’t want to use a timer, i want the request to only load when there is a new post added in the database. been stuck here for two weeks. searched around and have not seen anything to help.