Ricardo Melo Ricardo Melo - 4 days ago 5
Javascript Question

Execute Ajax call on user confirmation that should appear depending on a previous Ajax call

I'm dealing with a difficult problem concerning asynchronous calls:

A JQuery function executes on user click, it then calls for a php file to check is the user input will overlap with information already in the database.
If it does, the user then should be prompted for confirmation if he wants to proceed anyway or cancel, if he clicks ok, then it executes another call to write data in the database.

The structure I was thinking is something like

User clicks button:


  • Ajax -> Success: true or false.

  • If True -> User is prompted -> It overlaps, want to proceed?

  • If Yes -> Ajax -> Write stuff on database.



The problem is, I couldn't find a single solution that would let me do this.
Any help is appreciated!

DGS DGS
Answer

Javascript

$.ajax({
    type: "POST",
    url: 'your_url.php',
    data: your_data
  })
  .success(handleResponse);

function handleResponse(data) {
  if (data.request_overide) {
    if (confirm('There is an overlap... Proceed?')) {
      data.force = true;
      $.ajax({
          type: "POST",
          url: 'your_url.php',
          data: your_data
        })
        .success(handleResponse);
    }
  } else {
    alert('Successfully added!')
  }
}

PHP - your_url.php

$duplicate = false;
//Check if duplicate
if(!$_POST['force']){
   $duplicate = somecheck();
}
if(!$duplicate){
   addData();
}
echo json_encode(['request_overide' => $duplicate]);
Comments